blob: ee4608badc05fd3074b9a9c68bb04babe4d51b50 [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) {
139 if (!LangOpts.CPlusPlus) return NULL;
Charles Davis6bcb07a2010-08-19 02:18:14 +0000140 switch (T.getCXXABI()) {
141 default:
Charles Davis53c59df2010-08-16 03:33:14 +0000142 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000143 case CXXABI_Microsoft:
144 return CreateMicrosoftCXXABI(*this);
145 }
Charles Davis53c59df2010-08-16 03:33:14 +0000146}
147
Chris Lattner465fa322008-10-05 17:34:18 +0000148ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000149 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000150 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000151 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000152 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000153 TemplateSpecializationTypes(this_()),
154 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000155 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
156 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000157 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000158 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000159 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000160 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000161 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000162 BuiltinInfo(builtins),
163 DeclarationNames(*this),
164 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000165 LastSDM(0, 0),
166 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000167 ObjCIdRedefinitionType = QualType();
168 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000169 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000170 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000171 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000172 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000173}
174
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000175ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000176 // Release the DenseMaps associated with DeclContext objects.
177 // FIXME: Is this the ideal solution?
178 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000179
Douglas Gregor5b11d492010-07-25 17:53:33 +0000180 // Call all of the deallocation functions.
181 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
182 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000183
Douglas Gregor832940b2010-03-02 23:58:15 +0000184 // Release all of the memory associated with overridden C++ methods.
185 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
186 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
187 OM != OMEnd; ++OM)
188 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000189
Ted Kremenek076baeb2010-06-08 23:00:58 +0000190 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000191 // because they can contain DenseMaps.
192 for (llvm::DenseMap<const ObjCContainerDecl*,
193 const ASTRecordLayout*>::iterator
194 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
195 // Increment in loop to prevent using deallocated memory.
196 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
197 R->Destroy(*this);
198
Ted Kremenek076baeb2010-06-08 23:00:58 +0000199 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
200 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
201 // Increment in loop to prevent using deallocated memory.
202 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
203 R->Destroy(*this);
204 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000205 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000206
Douglas Gregor1a809332010-05-23 18:26:36 +0000207void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
208 Deallocations.push_back(std::make_pair(Callback, Data));
209}
210
Mike Stump11289f42009-09-09 15:08:12 +0000211void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000212ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
213 ExternalSource.reset(Source.take());
214}
215
Chris Lattner4eb445d2007-01-26 01:27:23 +0000216void ASTContext::PrintStats() const {
217 fprintf(stderr, "*** AST Context Stats:\n");
218 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000219
Douglas Gregora30d0462009-05-26 14:40:08 +0000220 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000221#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000222#define ABSTRACT_TYPE(Name, Parent)
223#include "clang/AST/TypeNodes.def"
224 0 // Extra
225 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000226
Chris Lattner4eb445d2007-01-26 01:27:23 +0000227 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
228 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000229 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000230 }
231
Douglas Gregora30d0462009-05-26 14:40:08 +0000232 unsigned Idx = 0;
233 unsigned TotalBytes = 0;
234#define TYPE(Name, Parent) \
235 if (counts[Idx]) \
236 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
237 TotalBytes += counts[Idx] * sizeof(Name##Type); \
238 ++Idx;
239#define ABSTRACT_TYPE(Name, Parent)
240#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregora30d0462009-05-26 14:40:08 +0000242 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000243
Douglas Gregor7454c562010-07-02 20:37:36 +0000244 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000245 fprintf(stderr, " %u/%u implicit default constructors created\n",
246 NumImplicitDefaultConstructorsDeclared,
247 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000248 fprintf(stderr, " %u/%u implicit copy constructors created\n",
249 NumImplicitCopyConstructorsDeclared,
250 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000251 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
252 NumImplicitCopyAssignmentOperatorsDeclared,
253 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000254 fprintf(stderr, " %u/%u implicit destructors created\n",
255 NumImplicitDestructorsDeclared, NumImplicitDestructors);
256
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000257 if (ExternalSource.get()) {
258 fprintf(stderr, "\n");
259 ExternalSource->PrintStats();
260 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000261
Douglas Gregor5b11d492010-07-25 17:53:33 +0000262 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000263}
264
265
John McCall48f2d582009-10-23 23:03:21 +0000266void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000267 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000268 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000269 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000270}
271
Chris Lattner970e54e2006-11-12 00:37:36 +0000272void ASTContext::InitBuiltinTypes() {
273 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner970e54e2006-11-12 00:37:36 +0000275 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000276 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattner970e54e2006-11-12 00:37:36 +0000278 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000279 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000280 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000281 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000282 InitBuiltinType(CharTy, BuiltinType::Char_S);
283 else
284 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000285 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000286 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
287 InitBuiltinType(ShortTy, BuiltinType::Short);
288 InitBuiltinType(IntTy, BuiltinType::Int);
289 InitBuiltinType(LongTy, BuiltinType::Long);
290 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner970e54e2006-11-12 00:37:36 +0000292 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000293 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
294 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
295 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
296 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
297 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000300 InitBuiltinType(FloatTy, BuiltinType::Float);
301 InitBuiltinType(DoubleTy, BuiltinType::Double);
302 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000303
Chris Lattnerf122cef2009-04-30 02:43:43 +0000304 // GNU extension, 128-bit integers.
305 InitBuiltinType(Int128Ty, BuiltinType::Int128);
306 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
307
Chris Lattner007cb022009-02-26 23:43:47 +0000308 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
309 InitBuiltinType(WCharTy, BuiltinType::WChar);
310 else // C99
311 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000312
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000313 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
314 InitBuiltinType(Char16Ty, BuiltinType::Char16);
315 else // C99
316 Char16Ty = getFromTargetType(Target.getChar16Type());
317
318 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
319 InitBuiltinType(Char32Ty, BuiltinType::Char32);
320 else // C99
321 Char32Ty = getFromTargetType(Target.getChar32Type());
322
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000324 InitBuiltinType(OverloadTy, BuiltinType::Overload);
325
326 // Placeholder type for type-dependent expressions whose type is
327 // completely unknown. No code should ever check a type against
328 // DependentTy and users should never see it; however, it is here to
329 // help diagnose failures to properly check for type-dependent
330 // expressions.
331 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000332
Mike Stump11289f42009-09-09 15:08:12 +0000333 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000334 // not yet been deduced.
335 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000336
Chris Lattner970e54e2006-11-12 00:37:36 +0000337 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000338 FloatComplexTy = getComplexType(FloatTy);
339 DoubleComplexTy = getComplexType(DoubleTy);
340 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000341
Steve Naroff66e9f332007-10-15 14:41:52 +0000342 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000343
Steve Naroff1329fa02009-07-15 18:40:39 +0000344 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
345 ObjCIdTypedefType = QualType();
346 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000347 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000348
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000349 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000350 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
351 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000352 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000353
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000354 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000355
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000356 // void * type
357 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000358
359 // nullptr type (C++0x 2.14.7)
360 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000361}
362
Douglas Gregor86d142a2009-10-08 07:24:58 +0000363MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000364ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000365 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000366 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000367 = InstantiatedFromStaticDataMember.find(Var);
368 if (Pos == InstantiatedFromStaticDataMember.end())
369 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000371 return Pos->second;
372}
373
Mike Stump11289f42009-09-09 15:08:12 +0000374void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000375ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000376 TemplateSpecializationKind TSK,
377 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000378 assert(Inst->isStaticDataMember() && "Not a static data member");
379 assert(Tmpl->isStaticDataMember() && "Not a static data member");
380 assert(!InstantiatedFromStaticDataMember[Inst] &&
381 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000382 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000383 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000384}
385
John McCalle61f2ba2009-11-18 02:36:19 +0000386NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000387ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000388 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000389 = InstantiatedFromUsingDecl.find(UUD);
390 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000391 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000393 return Pos->second;
394}
395
396void
John McCallb96ec562009-12-04 22:46:56 +0000397ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
398 assert((isa<UsingDecl>(Pattern) ||
399 isa<UnresolvedUsingValueDecl>(Pattern) ||
400 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
401 "pattern decl is not a using decl");
402 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
403 InstantiatedFromUsingDecl[Inst] = Pattern;
404}
405
406UsingShadowDecl *
407ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
408 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
409 = InstantiatedFromUsingShadowDecl.find(Inst);
410 if (Pos == InstantiatedFromUsingShadowDecl.end())
411 return 0;
412
413 return Pos->second;
414}
415
416void
417ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
418 UsingShadowDecl *Pattern) {
419 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
420 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000421}
422
Anders Carlsson5da84842009-09-01 04:26:58 +0000423FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
424 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
425 = InstantiatedFromUnnamedFieldDecl.find(Field);
426 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
427 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000428
Anders Carlsson5da84842009-09-01 04:26:58 +0000429 return Pos->second;
430}
431
432void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
433 FieldDecl *Tmpl) {
434 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
435 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
436 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
437 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000438
Anders Carlsson5da84842009-09-01 04:26:58 +0000439 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
440}
441
Douglas Gregor832940b2010-03-02 23:58:15 +0000442ASTContext::overridden_cxx_method_iterator
443ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
444 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
445 = OverriddenMethods.find(Method);
446 if (Pos == OverriddenMethods.end())
447 return 0;
448
449 return Pos->second.begin();
450}
451
452ASTContext::overridden_cxx_method_iterator
453ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
454 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
455 = OverriddenMethods.find(Method);
456 if (Pos == OverriddenMethods.end())
457 return 0;
458
459 return Pos->second.end();
460}
461
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000462unsigned
463ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
464 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
465 = OverriddenMethods.find(Method);
466 if (Pos == OverriddenMethods.end())
467 return 0;
468
469 return Pos->second.size();
470}
471
Douglas Gregor832940b2010-03-02 23:58:15 +0000472void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
473 const CXXMethodDecl *Overridden) {
474 OverriddenMethods[Method].push_back(Overridden);
475}
476
Chris Lattner53cfe802007-07-18 17:52:12 +0000477//===----------------------------------------------------------------------===//
478// Type Sizing and Analysis
479//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000480
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000481/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
482/// scalar floating point type.
483const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000484 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000485 assert(BT && "Not a floating point type!");
486 switch (BT->getKind()) {
487 default: assert(0 && "Not a floating point type!");
488 case BuiltinType::Float: return Target.getFloatFormat();
489 case BuiltinType::Double: return Target.getDoubleFormat();
490 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
491 }
492}
493
Ken Dyck160146e2010-01-27 17:10:57 +0000494/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000495/// specified decl. Note that bitfields do not have a valid alignment, so
496/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000497/// If @p RefAsPointee, references are treated like their underlying type
498/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000499CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000500 unsigned Align = Target.getCharWidth();
501
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000502 Align = std::max(Align, D->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000503
Chris Lattner68061312009-01-24 21:53:27 +0000504 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
505 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000506 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000507 if (RefAsPointee)
508 T = RT->getPointeeType();
509 else
510 T = getPointerType(RT->getPointeeType());
511 }
512 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000513 unsigned MinWidth = Target.getLargeArrayMinWidth();
514 unsigned ArrayAlign = Target.getLargeArrayAlign();
515 if (isa<VariableArrayType>(T) && MinWidth != 0)
516 Align = std::max(Align, ArrayAlign);
517 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
518 unsigned Size = getTypeSize(CT);
519 if (MinWidth != 0 && MinWidth <= Size)
520 Align = std::max(Align, ArrayAlign);
521 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000522 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000523 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
524 T = cast<ArrayType>(T)->getElementType();
525
526 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
527 }
Charles Davis3fc51072010-02-23 04:52:00 +0000528 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
529 // In the case of a field in a packed struct, we want the minimum
530 // of the alignment of the field and the alignment of the struct.
531 Align = std::min(Align,
532 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
533 }
Chris Lattner68061312009-01-24 21:53:27 +0000534 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000535
Ken Dyck160146e2010-01-27 17:10:57 +0000536 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000537}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000538
John McCall87fe5d52010-05-20 01:18:31 +0000539std::pair<CharUnits, CharUnits>
540ASTContext::getTypeInfoInChars(const Type *T) {
541 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
542 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
543 CharUnits::fromQuantity(Info.second / getCharWidth()));
544}
545
546std::pair<CharUnits, CharUnits>
547ASTContext::getTypeInfoInChars(QualType T) {
548 return getTypeInfoInChars(T.getTypePtr());
549}
550
Chris Lattner983a8bb2007-07-13 22:13:22 +0000551/// getTypeSize - Return the size of the specified type, in bits. This method
552/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000553///
554/// FIXME: Pointers into different addr spaces could have different sizes and
555/// alignment requirements: getPointerInfo should take an AddrSpace, this
556/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000557std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000558ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000559 uint64_t Width=0;
560 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000561 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000562#define TYPE(Class, Base)
563#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000564#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000565#define DEPENDENT_TYPE(Class, Base) case Type::Class:
566#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000567 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000568 break;
569
Chris Lattner355332d2007-07-13 22:27:08 +0000570 case Type::FunctionNoProto:
571 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000572 // GCC extension: alignof(function) = 32 bits
573 Width = 0;
574 Align = 32;
575 break;
576
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000577 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000578 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000579 Width = 0;
580 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
581 break;
582
Steve Naroff5c131802007-08-30 01:06:46 +0000583 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000584 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000585
Chris Lattner37e05872008-03-05 18:54:05 +0000586 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000587 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000588 Align = EltInfo.second;
589 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000590 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000591 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000592 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000593 const VectorType *VT = cast<VectorType>(T);
594 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
595 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000596 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000597 // If the alignment is not a power of 2, round up to the next power of 2.
598 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000599 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000600 Align = llvm::NextPowerOf2(Align);
601 Width = llvm::RoundUpToAlignment(Width, Align);
602 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000603 break;
604 }
Chris Lattner647fb222007-07-18 18:26:58 +0000605
Chris Lattner7570e9c2008-03-08 08:52:55 +0000606 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000607 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000608 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000609 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000610 // GCC extension: alignof(void) = 8 bits.
611 Width = 0;
612 Align = 8;
613 break;
614
Chris Lattner6a4f7452007-12-19 19:23:28 +0000615 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000616 Width = Target.getBoolWidth();
617 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000618 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000619 case BuiltinType::Char_S:
620 case BuiltinType::Char_U:
621 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000622 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000623 Width = Target.getCharWidth();
624 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000625 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000626 case BuiltinType::WChar:
627 Width = Target.getWCharWidth();
628 Align = Target.getWCharAlign();
629 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000630 case BuiltinType::Char16:
631 Width = Target.getChar16Width();
632 Align = Target.getChar16Align();
633 break;
634 case BuiltinType::Char32:
635 Width = Target.getChar32Width();
636 Align = Target.getChar32Align();
637 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000638 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000639 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000640 Width = Target.getShortWidth();
641 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000642 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000643 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000644 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000645 Width = Target.getIntWidth();
646 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000647 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000648 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000649 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000650 Width = Target.getLongWidth();
651 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000652 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000653 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000654 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000655 Width = Target.getLongLongWidth();
656 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000657 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000658 case BuiltinType::Int128:
659 case BuiltinType::UInt128:
660 Width = 128;
661 Align = 128; // int128_t is 128-bit aligned on all targets.
662 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000663 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000664 Width = Target.getFloatWidth();
665 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000666 break;
667 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000668 Width = Target.getDoubleWidth();
669 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 break;
671 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000672 Width = Target.getLongDoubleWidth();
673 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000675 case BuiltinType::NullPtr:
676 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
677 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000678 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000679 case BuiltinType::ObjCId:
680 case BuiltinType::ObjCClass:
681 case BuiltinType::ObjCSel:
682 Width = Target.getPointerWidth(0);
683 Align = Target.getPointerAlign(0);
684 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000685 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000686 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000687 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000688 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000689 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000690 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000691 case Type::BlockPointer: {
692 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
693 Width = Target.getPointerWidth(AS);
694 Align = Target.getPointerAlign(AS);
695 break;
696 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000697 case Type::LValueReference:
698 case Type::RValueReference: {
699 // alignof and sizeof should never enter this code path here, so we go
700 // the pointer route.
701 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
702 Width = Target.getPointerWidth(AS);
703 Align = Target.getPointerAlign(AS);
704 break;
705 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000706 case Type::Pointer: {
707 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000708 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000709 Align = Target.getPointerAlign(AS);
710 break;
711 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000712 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000713 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000714 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000715 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000716 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000717 Align = PtrDiffInfo.second;
718 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000719 }
Chris Lattner647fb222007-07-18 18:26:58 +0000720 case Type::Complex: {
721 // Complex types have the same alignment as their elements, but twice the
722 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000723 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000724 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000725 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000726 Align = EltInfo.second;
727 break;
728 }
John McCall8b07ec22010-05-15 11:32:37 +0000729 case Type::ObjCObject:
730 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000731 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000732 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000733 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
734 Width = Layout.getSize();
735 Align = Layout.getAlignment();
736 break;
737 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000738 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000739 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000740 const TagType *TT = cast<TagType>(T);
741
742 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000743 Width = 1;
744 Align = 1;
745 break;
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000748 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000749 return getTypeInfo(ET->getDecl()->getIntegerType());
750
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000751 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000752 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
753 Width = Layout.getSize();
754 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000755 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000756 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000757
Chris Lattner63d2b362009-10-22 05:17:15 +0000758 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000759 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
760 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000761
Douglas Gregoref462e62009-04-30 17:32:17 +0000762 case Type::Typedef: {
763 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000764 Align = std::max(Typedef->getMaxAlignment(),
765 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
766 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000767 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000768 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000769
770 case Type::TypeOfExpr:
771 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
772 .getTypePtr());
773
774 case Type::TypeOf:
775 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
776
Anders Carlsson81df7b82009-06-24 19:06:50 +0000777 case Type::Decltype:
778 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
779 .getTypePtr());
780
Abramo Bagnara6150c882010-05-11 21:36:43 +0000781 case Type::Elaborated:
782 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregoref462e62009-04-30 17:32:17 +0000784 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000785 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000786 "Cannot request the size of a dependent type");
787 // FIXME: this is likely to be wrong once we support template
788 // aliases, since a template alias could refer to a typedef that
789 // has an __aligned__ attribute on it.
790 return getTypeInfo(getCanonicalType(T));
791 }
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattner53cfe802007-07-18 17:52:12 +0000793 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000794 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000795}
796
Ken Dyck8c89d592009-12-22 14:23:30 +0000797/// getTypeSizeInChars - Return the size of the specified type, in characters.
798/// This method does not work on incomplete types.
799CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000800 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000801}
802CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000803 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000804}
805
Ken Dycka6046ab2010-01-26 17:25:18 +0000806/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000807/// characters. This method does not work on incomplete types.
808CharUnits ASTContext::getTypeAlignInChars(QualType T) {
809 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
810}
811CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
812 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
813}
814
Chris Lattnera3402cd2009-01-27 18:08:34 +0000815/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
816/// type for the current target in bits. This can be different than the ABI
817/// alignment in cases where it is beneficial for performance to overalign
818/// a data type.
819unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
820 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000821
822 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000823 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000824 T = CT->getElementType().getTypePtr();
825 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
826 T->isSpecificBuiltinType(BuiltinType::LongLong))
827 return std::max(ABIAlign, (unsigned)getTypeSize(T));
828
Chris Lattnera3402cd2009-01-27 18:08:34 +0000829 return ABIAlign;
830}
831
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000832/// ShallowCollectObjCIvars -
833/// Collect all ivars, including those synthesized, in the current class.
834///
835void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000836 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000837 // FIXME. This need be removed but there are two many places which
838 // assume const-ness of ObjCInterfaceDecl
839 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
840 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
841 Iv= Iv->getNextIvar())
842 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000843}
844
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000845/// DeepCollectObjCIvars -
846/// This routine first collects all declared, but not synthesized, ivars in
847/// super class and then collects all ivars, including those synthesized for
848/// current class. This routine is used for implementation of current class
849/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000850///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000851void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
852 bool leafClass,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000853 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000854 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
855 DeepCollectObjCIvars(SuperClass, false, Ivars);
856 if (!leafClass) {
857 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
858 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000859 Ivars.push_back(*I);
860 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000861 else
862 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000863}
864
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000865/// CollectInheritedProtocols - Collect all protocols in current class and
866/// those inherited by it.
867void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000868 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000869 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
870 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
871 PE = OI->protocol_end(); P != PE; ++P) {
872 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000873 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000874 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000875 PE = Proto->protocol_end(); P != PE; ++P) {
876 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000877 CollectInheritedProtocols(*P, Protocols);
878 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000879 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000880
881 // Categories of this Interface.
882 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
883 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
884 CollectInheritedProtocols(CDeclChain, Protocols);
885 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
886 while (SD) {
887 CollectInheritedProtocols(SD, Protocols);
888 SD = SD->getSuperClass();
889 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000890 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000891 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
892 PE = OC->protocol_end(); P != PE; ++P) {
893 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000894 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000895 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
896 PE = Proto->protocol_end(); P != PE; ++P)
897 CollectInheritedProtocols(*P, Protocols);
898 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000899 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000900 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
901 PE = OP->protocol_end(); P != PE; ++P) {
902 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000903 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000904 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
905 PE = Proto->protocol_end(); P != PE; ++P)
906 CollectInheritedProtocols(*P, Protocols);
907 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000908 }
909}
910
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000911unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
912 unsigned count = 0;
913 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000914 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
915 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000916 count += CDecl->ivar_size();
917
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000918 // Count ivar defined in this class's implementation. This
919 // includes synthesized ivars.
920 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000921 count += ImplDecl->ivar_size();
922
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000923 return count;
924}
925
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000926/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
927ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
928 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
929 I = ObjCImpls.find(D);
930 if (I != ObjCImpls.end())
931 return cast<ObjCImplementationDecl>(I->second);
932 return 0;
933}
934/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
935ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
936 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
937 I = ObjCImpls.find(D);
938 if (I != ObjCImpls.end())
939 return cast<ObjCCategoryImplDecl>(I->second);
940 return 0;
941}
942
943/// \brief Set the implementation of ObjCInterfaceDecl.
944void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
945 ObjCImplementationDecl *ImplD) {
946 assert(IFaceD && ImplD && "Passed null params");
947 ObjCImpls[IFaceD] = ImplD;
948}
949/// \brief Set the implementation of ObjCCategoryDecl.
950void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
951 ObjCCategoryImplDecl *ImplD) {
952 assert(CatD && ImplD && "Passed null params");
953 ObjCImpls[CatD] = ImplD;
954}
955
John McCallbcd03502009-12-07 02:54:59 +0000956/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000957///
John McCallbcd03502009-12-07 02:54:59 +0000958/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000959/// the TypeLoc wrappers.
960///
961/// \param T the type that will be the basis for type source info. This type
962/// should refer to how the declarator was written in source code, not to
963/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000964TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000965 unsigned DataSize) {
966 if (!DataSize)
967 DataSize = TypeLoc::getFullDataSizeForType(T);
968 else
969 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000970 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000971
John McCallbcd03502009-12-07 02:54:59 +0000972 TypeSourceInfo *TInfo =
973 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
974 new (TInfo) TypeSourceInfo(T);
975 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000976}
977
John McCallbcd03502009-12-07 02:54:59 +0000978TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +0000979 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +0000980 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +0000981 DI->getTypeLoc().initialize(L);
982 return DI;
983}
984
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000985const ASTRecordLayout &
986ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
987 return getObjCLayout(D, 0);
988}
989
990const ASTRecordLayout &
991ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
992 return getObjCLayout(D->getClassInterface(), D);
993}
994
Chris Lattner983a8bb2007-07-13 22:13:22 +0000995//===----------------------------------------------------------------------===//
996// Type creation/memoization methods
997//===----------------------------------------------------------------------===//
998
John McCall8ccfcb52009-09-24 19:53:00 +0000999QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1000 unsigned Fast = Quals.getFastQualifiers();
1001 Quals.removeFastQualifiers();
1002
1003 // Check if we've already instantiated this type.
1004 llvm::FoldingSetNodeID ID;
1005 ExtQuals::Profile(ID, TypeNode, Quals);
1006 void *InsertPos = 0;
1007 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1008 assert(EQ->getQualifiers() == Quals);
1009 QualType T = QualType(EQ, Fast);
1010 return T;
1011 }
1012
John McCall90d1c2d2009-09-24 23:30:46 +00001013 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001014 ExtQualNodes.InsertNode(New, InsertPos);
1015 QualType T = QualType(New, Fast);
1016 return T;
1017}
1018
1019QualType ASTContext::getVolatileType(QualType T) {
1020 QualType CanT = getCanonicalType(T);
1021 if (CanT.isVolatileQualified()) return T;
1022
1023 QualifierCollector Quals;
1024 const Type *TypeNode = Quals.strip(T);
1025 Quals.addVolatile();
1026
1027 return getExtQualType(TypeNode, Quals);
1028}
1029
Fariborz Jahanianece85822009-02-17 18:27:45 +00001030QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001031 QualType CanT = getCanonicalType(T);
1032 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001033 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001034
John McCall8ccfcb52009-09-24 19:53:00 +00001035 // If we are composing extended qualifiers together, merge together
1036 // into one ExtQuals node.
1037 QualifierCollector Quals;
1038 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001039
John McCall8ccfcb52009-09-24 19:53:00 +00001040 // If this type already has an address space specified, it cannot get
1041 // another one.
1042 assert(!Quals.hasAddressSpace() &&
1043 "Type cannot be in multiple addr spaces!");
1044 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001045
John McCall8ccfcb52009-09-24 19:53:00 +00001046 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001047}
1048
Chris Lattnerd60183d2009-02-18 22:53:11 +00001049QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001050 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001051 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001052 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001053 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001054
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001055 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001056 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001057 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001058 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1059 return getPointerType(ResultType);
1060 }
1061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCall8ccfcb52009-09-24 19:53:00 +00001063 // If we are composing extended qualifiers together, merge together
1064 // into one ExtQuals node.
1065 QualifierCollector Quals;
1066 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001067
John McCall8ccfcb52009-09-24 19:53:00 +00001068 // If this type already has an ObjCGC specified, it cannot get
1069 // another one.
1070 assert(!Quals.hasObjCGCAttr() &&
1071 "Type cannot have multiple ObjCGCs!");
1072 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001073
John McCall8ccfcb52009-09-24 19:53:00 +00001074 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001075}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001076
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001077static QualType getExtFunctionType(ASTContext& Context, QualType T,
1078 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001079 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001080 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1081 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001082 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001083 if (ResultType == Pointee)
1084 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001085
1086 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001087 } else if (const BlockPointerType *BlockPointer
1088 = T->getAs<BlockPointerType>()) {
1089 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001090 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001091 if (ResultType == Pointee)
1092 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001093
1094 ResultType = Context.getBlockPointerType(ResultType);
1095 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001096 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001097 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001098
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001099 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001100 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001101 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001102 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001103 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001104 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001105 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1106 FPT->getNumArgs(), FPT->isVariadic(),
1107 FPT->getTypeQuals(),
1108 FPT->hasExceptionSpec(),
1109 FPT->hasAnyExceptionSpec(),
1110 FPT->getNumExceptions(),
1111 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001112 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001113 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001114 } else
1115 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001116
1117 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1118}
1119
1120QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001121 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001122 return getExtFunctionType(*this, T,
1123 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001124}
1125
1126QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001127 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001128 return getExtFunctionType(*this, T,
1129 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001130}
1131
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001132QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1133 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1134 return getExtFunctionType(*this, T,
1135 Info.withRegParm(RegParm));
1136}
1137
Chris Lattnerc6395932007-06-22 20:56:16 +00001138/// getComplexType - Return the uniqued reference to the type for a complex
1139/// number with the specified element type.
1140QualType ASTContext::getComplexType(QualType T) {
1141 // Unique pointers, to guarantee there is only one pointer of a particular
1142 // structure.
1143 llvm::FoldingSetNodeID ID;
1144 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Chris Lattnerc6395932007-06-22 20:56:16 +00001146 void *InsertPos = 0;
1147 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1148 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001149
Chris Lattnerc6395932007-06-22 20:56:16 +00001150 // If the pointee type isn't canonical, this won't be a canonical type either,
1151 // so fill in the canonical type field.
1152 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001153 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001154 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001155
Chris Lattnerc6395932007-06-22 20:56:16 +00001156 // Get the new insert position for the node we care about.
1157 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001158 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001159 }
John McCall90d1c2d2009-09-24 23:30:46 +00001160 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001161 Types.push_back(New);
1162 ComplexTypes.InsertNode(New, InsertPos);
1163 return QualType(New, 0);
1164}
1165
Chris Lattner970e54e2006-11-12 00:37:36 +00001166/// getPointerType - Return the uniqued reference to the type for a pointer to
1167/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001168QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001169 // Unique pointers, to guarantee there is only one pointer of a particular
1170 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001171 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001172 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001173
Chris Lattner67521df2007-01-27 01:29:36 +00001174 void *InsertPos = 0;
1175 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001176 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Chris Lattner7ccecb92006-11-12 08:50:50 +00001178 // If the pointee type isn't canonical, this won't be a canonical type either,
1179 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001180 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001181 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001182 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001183
Chris Lattner67521df2007-01-27 01:29:36 +00001184 // Get the new insert position for the node we care about.
1185 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001186 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001187 }
John McCall90d1c2d2009-09-24 23:30:46 +00001188 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001189 Types.push_back(New);
1190 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001191 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001192}
1193
Mike Stump11289f42009-09-09 15:08:12 +00001194/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001195/// a pointer to the specified block.
1196QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001197 assert(T->isFunctionType() && "block of function types only");
1198 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001199 // structure.
1200 llvm::FoldingSetNodeID ID;
1201 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001202
Steve Naroffec33ed92008-08-27 16:04:49 +00001203 void *InsertPos = 0;
1204 if (BlockPointerType *PT =
1205 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1206 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001207
1208 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001209 // type either so fill in the canonical type field.
1210 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001211 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001212 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001213
Steve Naroffec33ed92008-08-27 16:04:49 +00001214 // Get the new insert position for the node we care about.
1215 BlockPointerType *NewIP =
1216 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001217 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001218 }
John McCall90d1c2d2009-09-24 23:30:46 +00001219 BlockPointerType *New
1220 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001221 Types.push_back(New);
1222 BlockPointerTypes.InsertNode(New, InsertPos);
1223 return QualType(New, 0);
1224}
1225
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001226/// getLValueReferenceType - Return the uniqued reference to the type for an
1227/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001228QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001229 // Unique pointers, to guarantee there is only one pointer of a particular
1230 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001231 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001232 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001233
1234 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001235 if (LValueReferenceType *RT =
1236 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001237 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001238
John McCallfc93cf92009-10-22 22:37:11 +00001239 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1240
Bill Wendling3708c182007-05-27 10:15:43 +00001241 // If the referencee type isn't canonical, this won't be a canonical type
1242 // either, so fill in the canonical type field.
1243 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001244 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1245 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1246 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001247
Bill Wendling3708c182007-05-27 10:15:43 +00001248 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001249 LValueReferenceType *NewIP =
1250 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001251 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001252 }
1253
John McCall90d1c2d2009-09-24 23:30:46 +00001254 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001255 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1256 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001257 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001258 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001259
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001260 return QualType(New, 0);
1261}
1262
1263/// getRValueReferenceType - Return the uniqued reference to the type for an
1264/// rvalue reference to the specified type.
1265QualType ASTContext::getRValueReferenceType(QualType T) {
1266 // Unique pointers, to guarantee there is only one pointer of a particular
1267 // structure.
1268 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001269 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270
1271 void *InsertPos = 0;
1272 if (RValueReferenceType *RT =
1273 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1274 return QualType(RT, 0);
1275
John McCallfc93cf92009-10-22 22:37:11 +00001276 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1277
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001278 // If the referencee type isn't canonical, this won't be a canonical type
1279 // either, so fill in the canonical type field.
1280 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001281 if (InnerRef || !T.isCanonical()) {
1282 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1283 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001284
1285 // Get the new insert position for the node we care about.
1286 RValueReferenceType *NewIP =
1287 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1288 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1289 }
1290
John McCall90d1c2d2009-09-24 23:30:46 +00001291 RValueReferenceType *New
1292 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001293 Types.push_back(New);
1294 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001295 return QualType(New, 0);
1296}
1297
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001298/// getMemberPointerType - Return the uniqued reference to the type for a
1299/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001300QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001301 // Unique pointers, to guarantee there is only one pointer of a particular
1302 // structure.
1303 llvm::FoldingSetNodeID ID;
1304 MemberPointerType::Profile(ID, T, Cls);
1305
1306 void *InsertPos = 0;
1307 if (MemberPointerType *PT =
1308 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1309 return QualType(PT, 0);
1310
1311 // If the pointee or class type isn't canonical, this won't be a canonical
1312 // type either, so fill in the canonical type field.
1313 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001314 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001315 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1316
1317 // Get the new insert position for the node we care about.
1318 MemberPointerType *NewIP =
1319 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1320 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1321 }
John McCall90d1c2d2009-09-24 23:30:46 +00001322 MemberPointerType *New
1323 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001324 Types.push_back(New);
1325 MemberPointerTypes.InsertNode(New, InsertPos);
1326 return QualType(New, 0);
1327}
1328
Mike Stump11289f42009-09-09 15:08:12 +00001329/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001330/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001331QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001332 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001333 ArrayType::ArraySizeModifier ASM,
1334 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001335 assert((EltTy->isDependentType() ||
1336 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001337 "Constant array of VLAs is illegal!");
1338
Chris Lattnere2df3f92009-05-13 04:12:56 +00001339 // Convert the array size into a canonical width matching the pointer size for
1340 // the target.
1341 llvm::APInt ArySize(ArySizeIn);
1342 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattner23b7eb62007-06-15 23:05:46 +00001344 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001345 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001346
Chris Lattner36f8e652007-01-27 08:31:04 +00001347 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001348 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001349 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001350 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattner7ccecb92006-11-12 08:50:50 +00001352 // If the element type isn't canonical, this won't be a canonical type either,
1353 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001354 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001355 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001356 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001357 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001358 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001359 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001360 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001361 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
John McCall90d1c2d2009-09-24 23:30:46 +00001364 ConstantArrayType *New = new(*this,TypeAlignment)
1365 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001366 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001367 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001368 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001369}
1370
Steve Naroffcadebd02007-08-30 18:14:25 +00001371/// getVariableArrayType - Returns a non-unique reference to the type for a
1372/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001373QualType ASTContext::getVariableArrayType(QualType EltTy,
1374 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001375 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001376 unsigned EltTypeQuals,
1377 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001378 // Since we don't unique expressions, it isn't possible to unique VLA's
1379 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001380 QualType CanonType;
1381
1382 if (!EltTy.isCanonical()) {
1383 if (NumElts)
1384 NumElts->Retain();
1385 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1386 EltTypeQuals, Brackets);
1387 }
1388
John McCall90d1c2d2009-09-24 23:30:46 +00001389 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001390 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001391
1392 VariableArrayTypes.push_back(New);
1393 Types.push_back(New);
1394 return QualType(New, 0);
1395}
1396
Douglas Gregor4619e432008-12-05 23:32:09 +00001397/// getDependentSizedArrayType - Returns a non-unique reference to
1398/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001399/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001400QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1401 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001402 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001403 unsigned EltTypeQuals,
1404 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001405 assert((!NumElts || NumElts->isTypeDependent() ||
1406 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001407 "Size must be type- or value-dependent!");
1408
Douglas Gregorf3f95522009-07-31 00:23:35 +00001409 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001410 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001411 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001412
1413 if (NumElts) {
1414 // Dependently-sized array types that do not have a specified
1415 // number of elements will have their sizes deduced from an
1416 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001417 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1418 EltTypeQuals, NumElts);
1419
1420 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1421 }
1422
Douglas Gregorf3f95522009-07-31 00:23:35 +00001423 DependentSizedArrayType *New;
1424 if (Canon) {
1425 // We already have a canonical version of this array type; use it as
1426 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001427 New = new (*this, TypeAlignment)
1428 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1429 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001430 } else {
1431 QualType CanonEltTy = getCanonicalType(EltTy);
1432 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001433 New = new (*this, TypeAlignment)
1434 DependentSizedArrayType(*this, EltTy, QualType(),
1435 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001436
Douglas Gregorc42075a2010-02-04 18:10:26 +00001437 if (NumElts) {
1438 DependentSizedArrayType *CanonCheck
1439 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1440 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1441 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001442 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001443 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001444 } else {
1445 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1446 ASM, EltTypeQuals,
1447 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001448 New = new (*this, TypeAlignment)
1449 DependentSizedArrayType(*this, EltTy, Canon,
1450 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001451 }
1452 }
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregor4619e432008-12-05 23:32:09 +00001454 Types.push_back(New);
1455 return QualType(New, 0);
1456}
1457
Eli Friedmanbd258282008-02-15 18:16:39 +00001458QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1459 ArrayType::ArraySizeModifier ASM,
1460 unsigned EltTypeQuals) {
1461 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001462 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001463
1464 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001465 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001466 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1467 return QualType(ATP, 0);
1468
1469 // If the element type isn't canonical, this won't be a canonical type
1470 // either, so fill in the canonical type field.
1471 QualType Canonical;
1472
John McCallb692a092009-10-22 20:10:53 +00001473 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001474 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001475 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001476
1477 // Get the new insert position for the node we care about.
1478 IncompleteArrayType *NewIP =
1479 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001480 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001481 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001482
John McCall90d1c2d2009-09-24 23:30:46 +00001483 IncompleteArrayType *New = new (*this, TypeAlignment)
1484 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001485
1486 IncompleteArrayTypes.InsertNode(New, InsertPos);
1487 Types.push_back(New);
1488 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001489}
1490
Steve Naroff91fcddb2007-07-18 18:00:27 +00001491/// getVectorType - Return the unique reference to a vector type of
1492/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001493QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001494 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001495 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattner76a00cf2008-04-06 22:59:24 +00001497 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001498 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001499
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001500 // Check if we've already instantiated a vector of this type.
1501 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001502 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1503
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001504 void *InsertPos = 0;
1505 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1506 return QualType(VTP, 0);
1507
1508 // If the element type isn't canonical, this won't be a canonical type either,
1509 // so fill in the canonical type field.
1510 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001511 if (!vecType.isCanonical()) {
Chris Lattner37141f42010-06-23 06:00:24 +00001512 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1513 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001515 // Get the new insert position for the node we care about.
1516 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001517 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001518 }
John McCall90d1c2d2009-09-24 23:30:46 +00001519 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001520 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001521 VectorTypes.InsertNode(New, InsertPos);
1522 Types.push_back(New);
1523 return QualType(New, 0);
1524}
1525
Nate Begemance4d7fc2008-04-18 23:10:10 +00001526/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001527/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001528QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001529 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001530
Chris Lattner76a00cf2008-04-06 22:59:24 +00001531 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001532 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001533
Steve Naroff91fcddb2007-07-18 18:00:27 +00001534 // Check if we've already instantiated a vector of this type.
1535 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001536 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1537 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001538 void *InsertPos = 0;
1539 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1540 return QualType(VTP, 0);
1541
1542 // If the element type isn't canonical, this won't be a canonical type either,
1543 // so fill in the canonical type field.
1544 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001545 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001546 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001547
Steve Naroff91fcddb2007-07-18 18:00:27 +00001548 // Get the new insert position for the node we care about.
1549 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001550 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001551 }
John McCall90d1c2d2009-09-24 23:30:46 +00001552 ExtVectorType *New = new (*this, TypeAlignment)
1553 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001554 VectorTypes.InsertNode(New, InsertPos);
1555 Types.push_back(New);
1556 return QualType(New, 0);
1557}
1558
Mike Stump11289f42009-09-09 15:08:12 +00001559QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001560 Expr *SizeExpr,
1561 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001562 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001563 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001564 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001565
Douglas Gregor352169a2009-07-31 03:54:25 +00001566 void *InsertPos = 0;
1567 DependentSizedExtVectorType *Canon
1568 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1569 DependentSizedExtVectorType *New;
1570 if (Canon) {
1571 // We already have a canonical version of this array type; use it as
1572 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001573 New = new (*this, TypeAlignment)
1574 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1575 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001576 } else {
1577 QualType CanonVecTy = getCanonicalType(vecType);
1578 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001579 New = new (*this, TypeAlignment)
1580 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1581 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001582
1583 DependentSizedExtVectorType *CanonCheck
1584 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1585 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1586 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001587 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1588 } else {
1589 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1590 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001591 New = new (*this, TypeAlignment)
1592 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001593 }
1594 }
Mike Stump11289f42009-09-09 15:08:12 +00001595
Douglas Gregor758a8692009-06-17 21:51:59 +00001596 Types.push_back(New);
1597 return QualType(New, 0);
1598}
1599
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001600/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001601///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001602QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1603 const FunctionType::ExtInfo &Info) {
1604 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001605 // Unique functions, to guarantee there is only one function of a particular
1606 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001607 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001608 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Chris Lattner47955de2007-01-27 08:37:20 +00001610 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001611 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001612 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001613 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001614
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001615 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001616 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001617 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001618 Canonical =
1619 getFunctionNoProtoType(getCanonicalType(ResultTy),
1620 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chris Lattner47955de2007-01-27 08:37:20 +00001622 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001623 FunctionNoProtoType *NewIP =
1624 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001625 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001626 }
Mike Stump11289f42009-09-09 15:08:12 +00001627
John McCall90d1c2d2009-09-24 23:30:46 +00001628 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001629 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001630 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001631 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001632 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001633}
1634
1635/// getFunctionType - Return a normal function type with a typed argument
1636/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001637QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001638 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001639 unsigned TypeQuals, bool hasExceptionSpec,
1640 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001641 const QualType *ExArray,
1642 const FunctionType::ExtInfo &Info) {
1643 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001644 // Unique functions, to guarantee there is only one function of a particular
1645 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001646 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001647 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001648 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001649 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001650
1651 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001652 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001653 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001654 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001655
1656 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001657 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001658 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001659 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001660 isCanonical = false;
1661
1662 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001663 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001664 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001665 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001666 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001667 CanonicalArgs.reserve(NumArgs);
1668 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001669 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001670
Chris Lattner76a00cf2008-04-06 22:59:24 +00001671 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001672 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001673 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001674 false, 0, 0,
1675 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001676
Chris Lattnerfd4de792007-01-27 01:15:32 +00001677 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001678 FunctionProtoType *NewIP =
1679 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001680 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001681 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001682
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001683 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001684 // for two variable size arrays (for parameter and exception types) at the
1685 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001686 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001687 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1688 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001689 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001690 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001691 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001692 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001693 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001694 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001695 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001696}
Chris Lattneref51c202006-11-10 07:17:23 +00001697
John McCalle78aac42010-03-10 03:28:59 +00001698#ifndef NDEBUG
1699static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1700 if (!isa<CXXRecordDecl>(D)) return false;
1701 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1702 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1703 return true;
1704 if (RD->getDescribedClassTemplate() &&
1705 !isa<ClassTemplateSpecializationDecl>(RD))
1706 return true;
1707 return false;
1708}
1709#endif
1710
1711/// getInjectedClassNameType - Return the unique reference to the
1712/// injected class name type for the specified templated declaration.
1713QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1714 QualType TST) {
1715 assert(NeedsInjectedClassNameType(Decl));
1716 if (Decl->TypeForDecl) {
1717 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001718 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001719 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1720 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1721 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1722 } else {
John McCall2408e322010-04-27 00:57:59 +00001723 Decl->TypeForDecl =
1724 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001725 Types.push_back(Decl->TypeForDecl);
1726 }
1727 return QualType(Decl->TypeForDecl, 0);
1728}
1729
Douglas Gregor83a586e2008-04-13 21:07:44 +00001730/// getTypeDeclType - Return the unique reference to the type for the
1731/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001732QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001733 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001734 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001735
John McCall81e38502010-02-16 03:57:14 +00001736 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001737 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001738
John McCall96f0b5f2010-03-10 06:48:02 +00001739 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1740 "Template type parameter types are always available.");
1741
John McCall81e38502010-02-16 03:57:14 +00001742 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001743 assert(!Record->getPreviousDeclaration() &&
1744 "struct/union has previous declaration");
1745 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001746 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001747 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001748 assert(!Enum->getPreviousDeclaration() &&
1749 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001750 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001751 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001752 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1753 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001754 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001755 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001756
John McCall96f0b5f2010-03-10 06:48:02 +00001757 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001758 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001759}
1760
Chris Lattner32d920b2007-01-26 02:01:53 +00001761/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001762/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001763QualType
1764ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001765 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001767 if (Canonical.isNull())
1768 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001769 Decl->TypeForDecl = new(*this, TypeAlignment)
1770 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001771 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001772 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001773}
1774
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001775QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1776 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1777
1778 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1779 if (PrevDecl->TypeForDecl)
1780 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1781
1782 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1783 Types.push_back(Decl->TypeForDecl);
1784 return QualType(Decl->TypeForDecl, 0);
1785}
1786
1787QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1788 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1789
1790 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1791 if (PrevDecl->TypeForDecl)
1792 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1793
1794 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1795 Types.push_back(Decl->TypeForDecl);
1796 return QualType(Decl->TypeForDecl, 0);
1797}
1798
John McCallcebee162009-10-18 09:09:24 +00001799/// \brief Retrieve a substitution-result type.
1800QualType
1801ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1802 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001803 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001804 && "replacement types must always be canonical");
1805
1806 llvm::FoldingSetNodeID ID;
1807 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1808 void *InsertPos = 0;
1809 SubstTemplateTypeParmType *SubstParm
1810 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1811
1812 if (!SubstParm) {
1813 SubstParm = new (*this, TypeAlignment)
1814 SubstTemplateTypeParmType(Parm, Replacement);
1815 Types.push_back(SubstParm);
1816 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1817 }
1818
1819 return QualType(SubstParm, 0);
1820}
1821
Douglas Gregoreff93e02009-02-05 23:33:38 +00001822/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001823/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001824/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001825QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001826 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001827 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001828 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001829 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001830 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001831 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001832 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1833
1834 if (TypeParm)
1835 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001836
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001837 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001838 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001839 TypeParm = new (*this, TypeAlignment)
1840 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001841
1842 TemplateTypeParmType *TypeCheck
1843 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1844 assert(!TypeCheck && "Template type parameter canonical type broken");
1845 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001846 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001847 TypeParm = new (*this, TypeAlignment)
1848 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001849
1850 Types.push_back(TypeParm);
1851 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1852
1853 return QualType(TypeParm, 0);
1854}
1855
John McCalle78aac42010-03-10 03:28:59 +00001856TypeSourceInfo *
1857ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1858 SourceLocation NameLoc,
1859 const TemplateArgumentListInfo &Args,
1860 QualType CanonType) {
1861 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1862
1863 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1864 TemplateSpecializationTypeLoc TL
1865 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1866 TL.setTemplateNameLoc(NameLoc);
1867 TL.setLAngleLoc(Args.getLAngleLoc());
1868 TL.setRAngleLoc(Args.getRAngleLoc());
1869 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1870 TL.setArgLocInfo(i, Args[i].getLocInfo());
1871 return DI;
1872}
1873
Mike Stump11289f42009-09-09 15:08:12 +00001874QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001875ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001876 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001877 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001878 unsigned NumArgs = Args.size();
1879
John McCall0ad16662009-10-29 08:12:44 +00001880 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1881 ArgVec.reserve(NumArgs);
1882 for (unsigned i = 0; i != NumArgs; ++i)
1883 ArgVec.push_back(Args[i].getArgument());
1884
John McCall2408e322010-04-27 00:57:59 +00001885 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001886 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001887}
1888
1889QualType
1890ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001891 const TemplateArgument *Args,
1892 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001893 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001894 if (!Canon.isNull())
1895 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001896 else
1897 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001898
Douglas Gregora8e02e72009-07-28 23:00:59 +00001899 // Allocate the (non-canonical) template specialization type, but don't
1900 // try to unique it: these types typically have location information that
1901 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001902 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001903 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001904 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001905 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001906 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001907 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001908 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001909
Douglas Gregor8bf42052009-02-09 18:46:07 +00001910 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001911 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001912}
1913
Mike Stump11289f42009-09-09 15:08:12 +00001914QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001915ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1916 const TemplateArgument *Args,
1917 unsigned NumArgs) {
1918 // Build the canonical template specialization type.
1919 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1920 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1921 CanonArgs.reserve(NumArgs);
1922 for (unsigned I = 0; I != NumArgs; ++I)
1923 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1924
1925 // Determine whether this canonical template specialization type already
1926 // exists.
1927 llvm::FoldingSetNodeID ID;
1928 TemplateSpecializationType::Profile(ID, CanonTemplate,
1929 CanonArgs.data(), NumArgs, *this);
1930
1931 void *InsertPos = 0;
1932 TemplateSpecializationType *Spec
1933 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1934
1935 if (!Spec) {
1936 // Allocate a new canonical template specialization type.
1937 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1938 sizeof(TemplateArgument) * NumArgs),
1939 TypeAlignment);
1940 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1941 CanonArgs.data(), NumArgs,
1942 QualType());
1943 Types.push_back(Spec);
1944 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1945 }
1946
1947 assert(Spec->isDependentType() &&
1948 "Non-dependent template-id type must have a canonical type");
1949 return QualType(Spec, 0);
1950}
1951
1952QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001953ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1954 NestedNameSpecifier *NNS,
1955 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001956 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001957 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001958
1959 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001960 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001961 if (T)
1962 return QualType(T, 0);
1963
Douglas Gregorc42075a2010-02-04 18:10:26 +00001964 QualType Canon = NamedType;
1965 if (!Canon.isCanonical()) {
1966 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001967 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1968 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001969 (void)CheckT;
1970 }
1971
Abramo Bagnara6150c882010-05-11 21:36:43 +00001972 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001973 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001974 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001975 return QualType(T, 0);
1976}
1977
Douglas Gregor02085352010-03-31 20:19:30 +00001978QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1979 NestedNameSpecifier *NNS,
1980 const IdentifierInfo *Name,
1981 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001982 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1983
1984 if (Canon.isNull()) {
1985 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001986 ElaboratedTypeKeyword CanonKeyword = Keyword;
1987 if (Keyword == ETK_None)
1988 CanonKeyword = ETK_Typename;
1989
1990 if (CanonNNS != NNS || CanonKeyword != Keyword)
1991 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001992 }
1993
1994 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001995 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001996
1997 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001998 DependentNameType *T
1999 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002000 if (T)
2001 return QualType(T, 0);
2002
Douglas Gregor02085352010-03-31 20:19:30 +00002003 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002004 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002005 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002006 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002007}
2008
Mike Stump11289f42009-09-09 15:08:12 +00002009QualType
John McCallc392f372010-06-11 00:33:02 +00002010ASTContext::getDependentTemplateSpecializationType(
2011 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002012 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002013 const IdentifierInfo *Name,
2014 const TemplateArgumentListInfo &Args) {
2015 // TODO: avoid this copy
2016 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2017 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2018 ArgCopy.push_back(Args[I].getArgument());
2019 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2020 ArgCopy.size(),
2021 ArgCopy.data());
2022}
2023
2024QualType
2025ASTContext::getDependentTemplateSpecializationType(
2026 ElaboratedTypeKeyword Keyword,
2027 NestedNameSpecifier *NNS,
2028 const IdentifierInfo *Name,
2029 unsigned NumArgs,
2030 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002031 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2032
Douglas Gregorc42075a2010-02-04 18:10:26 +00002033 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002034 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2035 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002036
2037 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002038 DependentTemplateSpecializationType *T
2039 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002040 if (T)
2041 return QualType(T, 0);
2042
John McCallc392f372010-06-11 00:33:02 +00002043 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002044
John McCallc392f372010-06-11 00:33:02 +00002045 ElaboratedTypeKeyword CanonKeyword = Keyword;
2046 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2047
2048 bool AnyNonCanonArgs = false;
2049 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2050 for (unsigned I = 0; I != NumArgs; ++I) {
2051 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2052 if (!CanonArgs[I].structurallyEquals(Args[I]))
2053 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002054 }
2055
John McCallc392f372010-06-11 00:33:02 +00002056 QualType Canon;
2057 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2058 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2059 Name, NumArgs,
2060 CanonArgs.data());
2061
2062 // Find the insert position again.
2063 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2064 }
2065
2066 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2067 sizeof(TemplateArgument) * NumArgs),
2068 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002069 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002070 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002071 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002072 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002073 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002074}
2075
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002076/// CmpProtocolNames - Comparison predicate for sorting protocols
2077/// alphabetically.
2078static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2079 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002080 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002081}
2082
John McCall8b07ec22010-05-15 11:32:37 +00002083static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002084 unsigned NumProtocols) {
2085 if (NumProtocols == 0) return true;
2086
2087 for (unsigned i = 1; i != NumProtocols; ++i)
2088 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2089 return false;
2090 return true;
2091}
2092
2093static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002094 unsigned &NumProtocols) {
2095 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002096
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002097 // Sort protocols, keyed by name.
2098 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2099
2100 // Remove duplicates.
2101 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2102 NumProtocols = ProtocolsEnd-Protocols;
2103}
2104
John McCall8b07ec22010-05-15 11:32:37 +00002105QualType ASTContext::getObjCObjectType(QualType BaseType,
2106 ObjCProtocolDecl * const *Protocols,
2107 unsigned NumProtocols) {
2108 // If the base type is an interface and there aren't any protocols
2109 // to add, then the interface type will do just fine.
2110 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2111 return BaseType;
2112
2113 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002114 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002115 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002116 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002117 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2118 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002119
John McCall8b07ec22010-05-15 11:32:37 +00002120 // Build the canonical type, which has the canonical base type and
2121 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002122 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002123 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2124 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2125 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002126 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2127 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002128 unsigned UniqueCount = NumProtocols;
2129
John McCallfc93cf92009-10-22 22:37:11 +00002130 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002131 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2132 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002133 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002134 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2135 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002136 }
2137
2138 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002139 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2140 }
2141
2142 unsigned Size = sizeof(ObjCObjectTypeImpl);
2143 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2144 void *Mem = Allocate(Size, TypeAlignment);
2145 ObjCObjectTypeImpl *T =
2146 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2147
2148 Types.push_back(T);
2149 ObjCObjectTypes.InsertNode(T, InsertPos);
2150 return QualType(T, 0);
2151}
2152
2153/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2154/// the given object type.
2155QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2156 llvm::FoldingSetNodeID ID;
2157 ObjCObjectPointerType::Profile(ID, ObjectT);
2158
2159 void *InsertPos = 0;
2160 if (ObjCObjectPointerType *QT =
2161 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2162 return QualType(QT, 0);
2163
2164 // Find the canonical object type.
2165 QualType Canonical;
2166 if (!ObjectT.isCanonical()) {
2167 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2168
2169 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002170 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2171 }
2172
Douglas Gregorf85bee62010-02-08 22:59:26 +00002173 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002174 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2175 ObjCObjectPointerType *QType =
2176 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002177
Steve Narofffb4330f2009-06-17 22:40:22 +00002178 Types.push_back(QType);
2179 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002180 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002181}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002182
Douglas Gregor1c283312010-08-11 12:19:30 +00002183/// getObjCInterfaceType - Return the unique reference to the type for the
2184/// specified ObjC interface decl. The list of protocols is optional.
2185QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2186 if (Decl->TypeForDecl)
2187 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Douglas Gregor1c283312010-08-11 12:19:30 +00002189 // FIXME: redeclarations?
2190 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2191 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2192 Decl->TypeForDecl = T;
2193 Types.push_back(T);
2194 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002195}
2196
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002197/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2198/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002199/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002200/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002201/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002202QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002203 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002204 if (tofExpr->isTypeDependent()) {
2205 llvm::FoldingSetNodeID ID;
2206 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002208 void *InsertPos = 0;
2209 DependentTypeOfExprType *Canon
2210 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2211 if (Canon) {
2212 // We already have a "canonical" version of an identical, dependent
2213 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002214 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002215 QualType((TypeOfExprType*)Canon, 0));
2216 }
2217 else {
2218 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002219 Canon
2220 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002221 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2222 toe = Canon;
2223 }
2224 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002225 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002226 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002227 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002228 Types.push_back(toe);
2229 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002230}
2231
Steve Naroffa773cd52007-08-01 18:02:17 +00002232/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2233/// TypeOfType AST's. The only motivation to unique these nodes would be
2234/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002235/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002236/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002237QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002238 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002239 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002240 Types.push_back(tot);
2241 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002242}
2243
Anders Carlssonad6bd352009-06-24 21:24:56 +00002244/// getDecltypeForExpr - Given an expr, will return the decltype for that
2245/// expression, according to the rules in C++0x [dcl.type.simple]p4
2246static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002247 if (e->isTypeDependent())
2248 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002249
Anders Carlssonad6bd352009-06-24 21:24:56 +00002250 // If e is an id expression or a class member access, decltype(e) is defined
2251 // as the type of the entity named by e.
2252 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2253 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2254 return VD->getType();
2255 }
2256 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2257 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2258 return FD->getType();
2259 }
2260 // If e is a function call or an invocation of an overloaded operator,
2261 // (parentheses around e are ignored), decltype(e) is defined as the
2262 // return type of that function.
2263 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2264 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002265
Anders Carlssonad6bd352009-06-24 21:24:56 +00002266 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002267
2268 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002269 // defined as T&, otherwise decltype(e) is defined as T.
2270 if (e->isLvalue(Context) == Expr::LV_Valid)
2271 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002272
Anders Carlssonad6bd352009-06-24 21:24:56 +00002273 return T;
2274}
2275
Anders Carlsson81df7b82009-06-24 19:06:50 +00002276/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2277/// DecltypeType AST's. The only motivation to unique these nodes would be
2278/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002279/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002280/// on canonical type's (which are always unique).
2281QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002282 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002283 if (e->isTypeDependent()) {
2284 llvm::FoldingSetNodeID ID;
2285 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002286
Douglas Gregora21f6c32009-07-30 23:36:40 +00002287 void *InsertPos = 0;
2288 DependentDecltypeType *Canon
2289 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2290 if (Canon) {
2291 // We already have a "canonical" version of an equivalent, dependent
2292 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002293 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002294 QualType((DecltypeType*)Canon, 0));
2295 }
2296 else {
2297 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002298 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002299 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2300 dt = Canon;
2301 }
2302 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002303 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002304 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002305 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002306 Types.push_back(dt);
2307 return QualType(dt, 0);
2308}
2309
Chris Lattnerfb072462007-01-23 05:45:31 +00002310/// getTagDeclType - Return the unique reference to the type for the
2311/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002312QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002313 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002314 // FIXME: What is the design on getTagDeclType when it requires casting
2315 // away const? mutable?
2316 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002317}
2318
Mike Stump11289f42009-09-09 15:08:12 +00002319/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2320/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2321/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002322CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002323 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002324}
Chris Lattnerfb072462007-01-23 05:45:31 +00002325
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002326/// getSignedWCharType - Return the type of "signed wchar_t".
2327/// Used when in C++, as a GCC extension.
2328QualType ASTContext::getSignedWCharType() const {
2329 // FIXME: derive from "Target" ?
2330 return WCharTy;
2331}
2332
2333/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2334/// Used when in C++, as a GCC extension.
2335QualType ASTContext::getUnsignedWCharType() const {
2336 // FIXME: derive from "Target" ?
2337 return UnsignedIntTy;
2338}
2339
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002340/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2341/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2342QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002343 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002344}
2345
Chris Lattnera21ad802008-04-02 05:18:44 +00002346//===----------------------------------------------------------------------===//
2347// Type Operators
2348//===----------------------------------------------------------------------===//
2349
John McCallfc93cf92009-10-22 22:37:11 +00002350CanQualType ASTContext::getCanonicalParamType(QualType T) {
2351 // Push qualifiers into arrays, and then discard any remaining
2352 // qualifiers.
2353 T = getCanonicalType(T);
2354 const Type *Ty = T.getTypePtr();
2355
2356 QualType Result;
2357 if (isa<ArrayType>(Ty)) {
2358 Result = getArrayDecayedType(QualType(Ty,0));
2359 } else if (isa<FunctionType>(Ty)) {
2360 Result = getPointerType(QualType(Ty, 0));
2361 } else {
2362 Result = QualType(Ty, 0);
2363 }
2364
2365 return CanQualType::CreateUnsafe(Result);
2366}
2367
Chris Lattnered0d0792008-04-06 22:41:35 +00002368/// getCanonicalType - Return the canonical (structural) type corresponding to
2369/// the specified potentially non-canonical type. The non-canonical version
2370/// of a type may have many "decorated" versions of types. Decorators can
2371/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2372/// to be free of any of these, allowing two canonical types to be compared
2373/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002374CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002375 QualifierCollector Quals;
2376 const Type *Ptr = Quals.strip(T);
2377 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002378
John McCall8ccfcb52009-09-24 19:53:00 +00002379 // The canonical internal type will be the canonical type *except*
2380 // that we push type qualifiers down through array types.
2381
2382 // If there are no new qualifiers to push down, stop here.
2383 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002384 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002385
John McCall8ccfcb52009-09-24 19:53:00 +00002386 // If the type qualifiers are on an array type, get the canonical
2387 // type of the array with the qualifiers applied to the element
2388 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002389 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2390 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002391 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002392
Chris Lattner7adf0762008-08-04 07:31:14 +00002393 // Get the canonical version of the element with the extra qualifiers on it.
2394 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002395 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002396 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002397
Chris Lattner7adf0762008-08-04 07:31:14 +00002398 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002399 return CanQualType::CreateUnsafe(
2400 getConstantArrayType(NewEltTy, CAT->getSize(),
2401 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002402 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002403 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002404 return CanQualType::CreateUnsafe(
2405 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002406 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002407
Douglas Gregor4619e432008-12-05 23:32:09 +00002408 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002409 return CanQualType::CreateUnsafe(
2410 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002411 DSAT->getSizeExpr() ?
2412 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002413 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002414 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002415 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002416
Chris Lattner7adf0762008-08-04 07:31:14 +00002417 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002418 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002419 VAT->getSizeExpr() ?
2420 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002421 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002422 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002423 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002424}
2425
Chandler Carruth607f38e2009-12-29 07:16:59 +00002426QualType ASTContext::getUnqualifiedArrayType(QualType T,
2427 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002428 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002429 const ArrayType *AT = getAsArrayType(T);
2430 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002431 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002432 }
2433
Chandler Carruth607f38e2009-12-29 07:16:59 +00002434 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002435 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002436 if (Elt == UnqualElt)
2437 return T;
2438
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002439 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002440 return getConstantArrayType(UnqualElt, CAT->getSize(),
2441 CAT->getSizeModifier(), 0);
2442 }
2443
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002444 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002445 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2446 }
2447
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002448 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2449 return getVariableArrayType(UnqualElt,
2450 VAT->getSizeExpr() ?
2451 VAT->getSizeExpr()->Retain() : 0,
2452 VAT->getSizeModifier(),
2453 VAT->getIndexTypeCVRQualifiers(),
2454 VAT->getBracketsRange());
2455 }
2456
2457 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002458 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2459 DSAT->getSizeModifier(), 0,
2460 SourceRange());
2461}
2462
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002463/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2464/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2465/// they point to and return true. If T1 and T2 aren't pointer types
2466/// or pointer-to-member types, or if they are not similar at this
2467/// level, returns false and leaves T1 and T2 unchanged. Top-level
2468/// qualifiers on T1 and T2 are ignored. This function will typically
2469/// be called in a loop that successively "unwraps" pointer and
2470/// pointer-to-member types to compare them at each level.
2471bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2472 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2473 *T2PtrType = T2->getAs<PointerType>();
2474 if (T1PtrType && T2PtrType) {
2475 T1 = T1PtrType->getPointeeType();
2476 T2 = T2PtrType->getPointeeType();
2477 return true;
2478 }
2479
2480 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2481 *T2MPType = T2->getAs<MemberPointerType>();
2482 if (T1MPType && T2MPType &&
2483 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2484 QualType(T2MPType->getClass(), 0))) {
2485 T1 = T1MPType->getPointeeType();
2486 T2 = T2MPType->getPointeeType();
2487 return true;
2488 }
2489
2490 if (getLangOptions().ObjC1) {
2491 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2492 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2493 if (T1OPType && T2OPType) {
2494 T1 = T1OPType->getPointeeType();
2495 T2 = T2OPType->getPointeeType();
2496 return true;
2497 }
2498 }
2499
2500 // FIXME: Block pointers, too?
2501
2502 return false;
2503}
2504
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002505DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2506 SourceLocation NameLoc) {
John McCall847e2a12009-11-24 18:42:40 +00002507 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002508 // DNInfo work in progress: CHECKME: what about DNLoc?
2509 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2510
John McCall847e2a12009-11-24 18:42:40 +00002511 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002512 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002513 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002514 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2515 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002516 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002517 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2518 // DNInfo work in progress: FIXME: source locations?
2519 DeclarationNameLoc DNLoc;
2520 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2521 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2522 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002523 }
2524 }
2525
John McCalld28ae272009-12-02 08:04:21 +00002526 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2527 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002528 // DNInfo work in progress: CHECKME: what about DNLoc?
2529 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002530}
2531
Douglas Gregor6bc50582009-05-07 06:41:52 +00002532TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002533 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2534 if (TemplateTemplateParmDecl *TTP
2535 = dyn_cast<TemplateTemplateParmDecl>(Template))
2536 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2537
2538 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002539 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002540 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002541
John McCalld28ae272009-12-02 08:04:21 +00002542 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002543
Douglas Gregor6bc50582009-05-07 06:41:52 +00002544 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2545 assert(DTN && "Non-dependent template names must refer to template decls.");
2546 return DTN->CanonicalTemplateName;
2547}
2548
Douglas Gregoradee3e32009-11-11 23:06:43 +00002549bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2550 X = getCanonicalTemplateName(X);
2551 Y = getCanonicalTemplateName(Y);
2552 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2553}
2554
Mike Stump11289f42009-09-09 15:08:12 +00002555TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002556ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2557 switch (Arg.getKind()) {
2558 case TemplateArgument::Null:
2559 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregora8e02e72009-07-28 23:00:59 +00002561 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002562 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002563
Douglas Gregora8e02e72009-07-28 23:00:59 +00002564 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002565 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002566
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002567 case TemplateArgument::Template:
2568 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2569
Douglas Gregora8e02e72009-07-28 23:00:59 +00002570 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002571 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002572 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002573
Douglas Gregora8e02e72009-07-28 23:00:59 +00002574 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002575 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002576
Douglas Gregora8e02e72009-07-28 23:00:59 +00002577 case TemplateArgument::Pack: {
2578 // FIXME: Allocate in ASTContext
2579 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2580 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002581 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002582 AEnd = Arg.pack_end();
2583 A != AEnd; (void)++A, ++Idx)
2584 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregora8e02e72009-07-28 23:00:59 +00002586 TemplateArgument Result;
2587 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2588 return Result;
2589 }
2590 }
2591
2592 // Silence GCC warning
2593 assert(false && "Unhandled template argument kind");
2594 return TemplateArgument();
2595}
2596
Douglas Gregor333489b2009-03-27 23:10:48 +00002597NestedNameSpecifier *
2598ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002599 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002600 return 0;
2601
2602 switch (NNS->getKind()) {
2603 case NestedNameSpecifier::Identifier:
2604 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002605 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002606 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2607 NNS->getAsIdentifier());
2608
2609 case NestedNameSpecifier::Namespace:
2610 // A namespace is canonical; build a nested-name-specifier with
2611 // this namespace and no prefix.
2612 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2613
2614 case NestedNameSpecifier::TypeSpec:
2615 case NestedNameSpecifier::TypeSpecWithTemplate: {
2616 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002617 return NestedNameSpecifier::Create(*this, 0,
2618 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002619 T.getTypePtr());
2620 }
2621
2622 case NestedNameSpecifier::Global:
2623 // The global specifier is canonical and unique.
2624 return NNS;
2625 }
2626
2627 // Required to silence a GCC warning
2628 return 0;
2629}
2630
Chris Lattner7adf0762008-08-04 07:31:14 +00002631
2632const ArrayType *ASTContext::getAsArrayType(QualType T) {
2633 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002634 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002635 // Handle the common positive case fast.
2636 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2637 return AT;
2638 }
Mike Stump11289f42009-09-09 15:08:12 +00002639
John McCall8ccfcb52009-09-24 19:53:00 +00002640 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002641 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002642 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002643 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002644
John McCall8ccfcb52009-09-24 19:53:00 +00002645 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002646 // implements C99 6.7.3p8: "If the specification of an array type includes
2647 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002648
Chris Lattner7adf0762008-08-04 07:31:14 +00002649 // If we get here, we either have type qualifiers on the type, or we have
2650 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002651 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002652
John McCall8ccfcb52009-09-24 19:53:00 +00002653 QualifierCollector Qs;
2654 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002655
Chris Lattner7adf0762008-08-04 07:31:14 +00002656 // If we have a simple case, just return now.
2657 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002658 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002659 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattner7adf0762008-08-04 07:31:14 +00002661 // Otherwise, we have an array and we have qualifiers on it. Push the
2662 // qualifiers into the array element type and return a new array type.
2663 // Get the canonical version of the element with the extra qualifiers on it.
2664 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002665 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002666
Chris Lattner7adf0762008-08-04 07:31:14 +00002667 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2668 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2669 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002670 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002671 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2672 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2673 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002674 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002675
Mike Stump11289f42009-09-09 15:08:12 +00002676 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002677 = dyn_cast<DependentSizedArrayType>(ATy))
2678 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002679 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002680 DSAT->getSizeExpr() ?
2681 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002682 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002683 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002684 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002685
Chris Lattner7adf0762008-08-04 07:31:14 +00002686 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002687 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002688 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002689 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002690 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002691 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002692 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002693}
2694
2695
Chris Lattnera21ad802008-04-02 05:18:44 +00002696/// getArrayDecayedType - Return the properly qualified result of decaying the
2697/// specified array type to a pointer. This operation is non-trivial when
2698/// handling typedefs etc. The canonical type of "T" must be an array type,
2699/// this returns a pointer to a properly qualified element of the array.
2700///
2701/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2702QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002703 // Get the element type with 'getAsArrayType' so that we don't lose any
2704 // typedefs in the element type of the array. This also handles propagation
2705 // of type qualifiers from the array type into the element type if present
2706 // (C99 6.7.3p8).
2707 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2708 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002709
Chris Lattner7adf0762008-08-04 07:31:14 +00002710 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002711
2712 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002713 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002714}
2715
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002716QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002717 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002718 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2719 QT = AT->getElementType();
2720 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002721}
2722
Anders Carlsson4bf82142009-09-25 01:23:32 +00002723QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2724 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002725
Anders Carlsson4bf82142009-09-25 01:23:32 +00002726 if (const ArrayType *AT = getAsArrayType(ElemTy))
2727 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002728
Anders Carlssone0808df2008-12-21 03:44:36 +00002729 return ElemTy;
2730}
2731
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002732/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002733uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002734ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2735 uint64_t ElementCount = 1;
2736 do {
2737 ElementCount *= CA->getSize().getZExtValue();
2738 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2739 } while (CA);
2740 return ElementCount;
2741}
2742
Steve Naroff0af91202007-04-27 21:51:21 +00002743/// getFloatingRank - Return a relative rank for floating point types.
2744/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002745static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002746 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002747 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002748
John McCall9dd450b2009-09-21 23:43:11 +00002749 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2750 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002751 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002752 case BuiltinType::Float: return FloatRank;
2753 case BuiltinType::Double: return DoubleRank;
2754 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002755 }
2756}
2757
Mike Stump11289f42009-09-09 15:08:12 +00002758/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2759/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002760/// 'typeDomain' is a real floating point or complex type.
2761/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002762QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2763 QualType Domain) const {
2764 FloatingRank EltRank = getFloatingRank(Size);
2765 if (Domain->isComplexType()) {
2766 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002767 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002768 case FloatRank: return FloatComplexTy;
2769 case DoubleRank: return DoubleComplexTy;
2770 case LongDoubleRank: return LongDoubleComplexTy;
2771 }
Steve Naroff0af91202007-04-27 21:51:21 +00002772 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002773
2774 assert(Domain->isRealFloatingType() && "Unknown domain!");
2775 switch (EltRank) {
2776 default: assert(0 && "getFloatingRank(): illegal value for rank");
2777 case FloatRank: return FloatTy;
2778 case DoubleRank: return DoubleTy;
2779 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002780 }
Steve Naroffe4718892007-04-27 18:30:00 +00002781}
2782
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002783/// getFloatingTypeOrder - Compare the rank of the two specified floating
2784/// point types, ignoring the domain of the type (i.e. 'double' ==
2785/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002786/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002787int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2788 FloatingRank LHSR = getFloatingRank(LHS);
2789 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002790
Chris Lattnerb90739d2008-04-06 23:38:49 +00002791 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002792 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002793 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002794 return 1;
2795 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002796}
2797
Chris Lattner76a00cf2008-04-06 22:59:24 +00002798/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2799/// routine will assert if passed a built-in type that isn't an integer or enum,
2800/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002801unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002802 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002803 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002804 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002805
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002806 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2807 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2808
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002809 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2810 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2811
2812 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2813 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2814
Chris Lattner76a00cf2008-04-06 22:59:24 +00002815 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002816 default: assert(0 && "getIntegerRank(): not a built-in integer");
2817 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002818 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002819 case BuiltinType::Char_S:
2820 case BuiltinType::Char_U:
2821 case BuiltinType::SChar:
2822 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002823 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002824 case BuiltinType::Short:
2825 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002826 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002827 case BuiltinType::Int:
2828 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002829 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002830 case BuiltinType::Long:
2831 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002832 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002833 case BuiltinType::LongLong:
2834 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002835 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002836 case BuiltinType::Int128:
2837 case BuiltinType::UInt128:
2838 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002839 }
2840}
2841
Eli Friedman629ffb92009-08-20 04:21:42 +00002842/// \brief Whether this is a promotable bitfield reference according
2843/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2844///
2845/// \returns the type this bit-field will promote to, or NULL if no
2846/// promotion occurs.
2847QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002848 if (E->isTypeDependent() || E->isValueDependent())
2849 return QualType();
2850
Eli Friedman629ffb92009-08-20 04:21:42 +00002851 FieldDecl *Field = E->getBitField();
2852 if (!Field)
2853 return QualType();
2854
2855 QualType FT = Field->getType();
2856
2857 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2858 uint64_t BitWidth = BitWidthAP.getZExtValue();
2859 uint64_t IntSize = getTypeSize(IntTy);
2860 // GCC extension compatibility: if the bit-field size is less than or equal
2861 // to the size of int, it gets promoted no matter what its type is.
2862 // For instance, unsigned long bf : 4 gets promoted to signed int.
2863 if (BitWidth < IntSize)
2864 return IntTy;
2865
2866 if (BitWidth == IntSize)
2867 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2868
2869 // Types bigger than int are not subject to promotions, and therefore act
2870 // like the base type.
2871 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2872 // is ridiculous.
2873 return QualType();
2874}
2875
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002876/// getPromotedIntegerType - Returns the type that Promotable will
2877/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2878/// integer type.
2879QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2880 assert(!Promotable.isNull());
2881 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002882 if (const EnumType *ET = Promotable->getAs<EnumType>())
2883 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002884 if (Promotable->isSignedIntegerType())
2885 return IntTy;
2886 uint64_t PromotableSize = getTypeSize(Promotable);
2887 uint64_t IntSize = getTypeSize(IntTy);
2888 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2889 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2890}
2891
Mike Stump11289f42009-09-09 15:08:12 +00002892/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002893/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002894/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002895int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002896 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2897 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002898 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002899
Chris Lattner76a00cf2008-04-06 22:59:24 +00002900 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2901 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002902
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002903 unsigned LHSRank = getIntegerRank(LHSC);
2904 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002905
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002906 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2907 if (LHSRank == RHSRank) return 0;
2908 return LHSRank > RHSRank ? 1 : -1;
2909 }
Mike Stump11289f42009-09-09 15:08:12 +00002910
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002911 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2912 if (LHSUnsigned) {
2913 // If the unsigned [LHS] type is larger, return it.
2914 if (LHSRank >= RHSRank)
2915 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002917 // If the signed type can represent all values of the unsigned type, it
2918 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002919 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002920 return -1;
2921 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002922
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002923 // If the unsigned [RHS] type is larger, return it.
2924 if (RHSRank >= LHSRank)
2925 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002927 // If the signed type can represent all values of the unsigned type, it
2928 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002929 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002930 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002931}
Anders Carlsson98f07902007-08-17 05:31:46 +00002932
Anders Carlsson6d417272009-11-14 21:45:58 +00002933static RecordDecl *
2934CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2935 SourceLocation L, IdentifierInfo *Id) {
2936 if (Ctx.getLangOptions().CPlusPlus)
2937 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2938 else
2939 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2940}
2941
Mike Stump11289f42009-09-09 15:08:12 +00002942// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002943QualType ASTContext::getCFConstantStringType() {
2944 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002945 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002946 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002947 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002948 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002949
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002950 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002951
Anders Carlsson98f07902007-08-17 05:31:46 +00002952 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002953 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002954 // int flags;
2955 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002956 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002957 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002958 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002959 FieldTypes[3] = LongTy;
2960
Anders Carlsson98f07902007-08-17 05:31:46 +00002961 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002962 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002963 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002964 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002965 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002966 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002967 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002968 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002969 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002970 }
2971
Douglas Gregord5058122010-02-11 01:19:42 +00002972 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002973 }
Mike Stump11289f42009-09-09 15:08:12 +00002974
Anders Carlsson98f07902007-08-17 05:31:46 +00002975 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002976}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002977
Douglas Gregor512b0772009-04-23 22:29:11 +00002978void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002979 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002980 assert(Rec && "Invalid CFConstantStringType");
2981 CFConstantStringTypeDecl = Rec->getDecl();
2982}
2983
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002984// getNSConstantStringType - Return the type used for constant NSStrings.
2985QualType ASTContext::getNSConstantStringType() {
2986 if (!NSConstantStringTypeDecl) {
2987 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002988 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002989 &Idents.get("__builtin_NSString"));
2990 NSConstantStringTypeDecl->startDefinition();
2991
2992 QualType FieldTypes[3];
2993
2994 // const int *isa;
2995 FieldTypes[0] = getPointerType(IntTy.withConst());
2996 // const char *str;
2997 FieldTypes[1] = getPointerType(CharTy.withConst());
2998 // unsigned int length;
2999 FieldTypes[2] = UnsignedIntTy;
3000
3001 // Create fields
3002 for (unsigned i = 0; i < 3; ++i) {
3003 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3004 SourceLocation(), 0,
3005 FieldTypes[i], /*TInfo=*/0,
3006 /*BitWidth=*/0,
3007 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003008 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003009 NSConstantStringTypeDecl->addDecl(Field);
3010 }
3011
3012 NSConstantStringTypeDecl->completeDefinition();
3013 }
3014
3015 return getTagDeclType(NSConstantStringTypeDecl);
3016}
3017
3018void ASTContext::setNSConstantStringType(QualType T) {
3019 const RecordType *Rec = T->getAs<RecordType>();
3020 assert(Rec && "Invalid NSConstantStringType");
3021 NSConstantStringTypeDecl = Rec->getDecl();
3022}
3023
Mike Stump11289f42009-09-09 15:08:12 +00003024QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003025 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003026 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003027 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003028 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003029 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003030
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003031 QualType FieldTypes[] = {
3032 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003033 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003034 getPointerType(UnsignedLongTy),
3035 getConstantArrayType(UnsignedLongTy,
3036 llvm::APInt(32, 5), ArrayType::Normal, 0)
3037 };
Mike Stump11289f42009-09-09 15:08:12 +00003038
Douglas Gregor91f84212008-12-11 16:49:14 +00003039 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003040 FieldDecl *Field = FieldDecl::Create(*this,
3041 ObjCFastEnumerationStateTypeDecl,
3042 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003043 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003044 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003045 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003046 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003047 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003048 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003049 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003050 if (CXXRecordDecl *CXXRD =
3051 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003052 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregord5058122010-02-11 01:19:42 +00003054 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003055 }
Mike Stump11289f42009-09-09 15:08:12 +00003056
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003057 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3058}
3059
Mike Stumpd0153282009-10-20 02:12:22 +00003060QualType ASTContext::getBlockDescriptorType() {
3061 if (BlockDescriptorType)
3062 return getTagDeclType(BlockDescriptorType);
3063
3064 RecordDecl *T;
3065 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003066 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003067 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003068 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003069
3070 QualType FieldTypes[] = {
3071 UnsignedLongTy,
3072 UnsignedLongTy,
3073 };
3074
3075 const char *FieldNames[] = {
3076 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003077 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003078 };
3079
3080 for (size_t i = 0; i < 2; ++i) {
3081 FieldDecl *Field = FieldDecl::Create(*this,
3082 T,
3083 SourceLocation(),
3084 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003085 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003086 /*BitWidth=*/0,
3087 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003088 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003089 T->addDecl(Field);
3090 }
3091
Douglas Gregord5058122010-02-11 01:19:42 +00003092 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003093
3094 BlockDescriptorType = T;
3095
3096 return getTagDeclType(BlockDescriptorType);
3097}
3098
3099void ASTContext::setBlockDescriptorType(QualType T) {
3100 const RecordType *Rec = T->getAs<RecordType>();
3101 assert(Rec && "Invalid BlockDescriptorType");
3102 BlockDescriptorType = Rec->getDecl();
3103}
3104
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003105QualType ASTContext::getBlockDescriptorExtendedType() {
3106 if (BlockDescriptorExtendedType)
3107 return getTagDeclType(BlockDescriptorExtendedType);
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_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003113 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003114
3115 QualType FieldTypes[] = {
3116 UnsignedLongTy,
3117 UnsignedLongTy,
3118 getPointerType(VoidPtrTy),
3119 getPointerType(VoidPtrTy)
3120 };
3121
3122 const char *FieldNames[] = {
3123 "reserved",
3124 "Size",
3125 "CopyFuncPtr",
3126 "DestroyFuncPtr"
3127 };
3128
3129 for (size_t i = 0; i < 4; ++i) {
3130 FieldDecl *Field = FieldDecl::Create(*this,
3131 T,
3132 SourceLocation(),
3133 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003134 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003135 /*BitWidth=*/0,
3136 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003137 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003138 T->addDecl(Field);
3139 }
3140
Douglas Gregord5058122010-02-11 01:19:42 +00003141 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003142
3143 BlockDescriptorExtendedType = T;
3144
3145 return getTagDeclType(BlockDescriptorExtendedType);
3146}
3147
3148void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3149 const RecordType *Rec = T->getAs<RecordType>();
3150 assert(Rec && "Invalid BlockDescriptorType");
3151 BlockDescriptorExtendedType = Rec->getDecl();
3152}
3153
Mike Stump94967902009-10-21 18:16:27 +00003154bool ASTContext::BlockRequiresCopying(QualType Ty) {
3155 if (Ty->isBlockPointerType())
3156 return true;
3157 if (isObjCNSObjectType(Ty))
3158 return true;
3159 if (Ty->isObjCObjectPointerType())
3160 return true;
3161 return false;
3162}
3163
Daniel Dunbar56df9772010-08-17 22:39:59 +00003164QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stump94967902009-10-21 18:16:27 +00003165 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003166 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003167 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003168 // unsigned int __flags;
3169 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003170 // void *__copy_helper; // as needed
3171 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003172 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003173 // } *
3174
Mike Stump94967902009-10-21 18:16:27 +00003175 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3176
3177 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003178 llvm::SmallString<36> Name;
3179 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3180 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003181 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003182 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003183 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003184 T->startDefinition();
3185 QualType Int32Ty = IntTy;
3186 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3187 QualType FieldTypes[] = {
3188 getPointerType(VoidPtrTy),
3189 getPointerType(getTagDeclType(T)),
3190 Int32Ty,
3191 Int32Ty,
3192 getPointerType(VoidPtrTy),
3193 getPointerType(VoidPtrTy),
3194 Ty
3195 };
3196
Daniel Dunbar56df9772010-08-17 22:39:59 +00003197 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003198 "__isa",
3199 "__forwarding",
3200 "__flags",
3201 "__size",
3202 "__copy_helper",
3203 "__destroy_helper",
3204 DeclName,
3205 };
3206
3207 for (size_t i = 0; i < 7; ++i) {
3208 if (!HasCopyAndDispose && i >=4 && i <= 5)
3209 continue;
3210 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3211 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003212 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003213 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003214 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003215 T->addDecl(Field);
3216 }
3217
Douglas Gregord5058122010-02-11 01:19:42 +00003218 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003219
3220 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003221}
3222
3223
3224QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003225 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003226 llvm::SmallVectorImpl<const Expr *> &Layout) {
3227
Mike Stumpd0153282009-10-20 02:12:22 +00003228 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003229 llvm::SmallString<36> Name;
3230 llvm::raw_svector_ostream(Name) << "__block_literal_"
3231 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003232 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003233 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003234 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003235 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003236 QualType FieldTypes[] = {
3237 getPointerType(VoidPtrTy),
3238 IntTy,
3239 IntTy,
3240 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003241 (BlockHasCopyDispose ?
3242 getPointerType(getBlockDescriptorExtendedType()) :
3243 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003244 };
3245
3246 const char *FieldNames[] = {
3247 "__isa",
3248 "__flags",
3249 "__reserved",
3250 "__FuncPtr",
3251 "__descriptor"
3252 };
3253
3254 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003255 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003256 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003257 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003258 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003259 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003260 T->addDecl(Field);
3261 }
3262
John McCall87fe5d52010-05-20 01:18:31 +00003263 for (unsigned i = 0; i < Layout.size(); ++i) {
3264 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003265
John McCall87fe5d52010-05-20 01:18:31 +00003266 QualType FieldType = E->getType();
3267 IdentifierInfo *FieldName = 0;
3268 if (isa<CXXThisExpr>(E)) {
3269 FieldName = &Idents.get("this");
3270 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3271 const ValueDecl *D = BDRE->getDecl();
3272 FieldName = D->getIdentifier();
3273 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003274 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003275 } else {
3276 // Padding.
3277 assert(isa<ConstantArrayType>(FieldType) &&
3278 isa<DeclRefExpr>(E) &&
3279 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3280 "doesn't match characteristics of padding decl");
3281 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003282
3283 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003284 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003285 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003286 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003287 T->addDecl(Field);
3288 }
3289
Douglas Gregord5058122010-02-11 01:19:42 +00003290 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003291
3292 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003293}
3294
Douglas Gregor512b0772009-04-23 22:29:11 +00003295void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003296 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003297 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3298 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3299}
3300
Anders Carlsson18acd442007-10-29 06:33:42 +00003301// This returns true if a type has been typedefed to BOOL:
3302// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003303static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003304 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003305 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3306 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003307
Anders Carlssond8499822007-10-29 05:01:08 +00003308 return false;
3309}
3310
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003311/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003312/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003313CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003314 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003315
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003316 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003317 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003318 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003319 // Treat arrays as pointers, since that's how they're passed in.
3320 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003321 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003322 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003323}
3324
3325static inline
3326std::string charUnitsToString(const CharUnits &CU) {
3327 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003328}
3329
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003330/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003331/// declaration.
3332void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3333 std::string& S) {
3334 const BlockDecl *Decl = Expr->getBlockDecl();
3335 QualType BlockTy =
3336 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3337 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003338 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003339 // Compute size of all parameters.
3340 // Start with computing size of a pointer in number of bytes.
3341 // FIXME: There might(should) be a better way of doing this computation!
3342 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003343 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3344 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003345 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003346 E = Decl->param_end(); PI != E; ++PI) {
3347 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003348 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003349 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003350 ParmOffset += sz;
3351 }
3352 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003353 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003354 // Block pointer and offset.
3355 S += "@?0";
3356 ParmOffset = PtrSize;
3357
3358 // Argument types.
3359 ParmOffset = PtrSize;
3360 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3361 Decl->param_end(); PI != E; ++PI) {
3362 ParmVarDecl *PVDecl = *PI;
3363 QualType PType = PVDecl->getOriginalType();
3364 if (const ArrayType *AT =
3365 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3366 // Use array's original type only if it has known number of
3367 // elements.
3368 if (!isa<ConstantArrayType>(AT))
3369 PType = PVDecl->getType();
3370 } else if (PType->isFunctionType())
3371 PType = PVDecl->getType();
3372 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003373 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003374 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003375 }
3376}
3377
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003378/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003379/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003380void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003381 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003382 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003383 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003384 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003385 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003386 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003387 // Compute size of all parameters.
3388 // Start with computing size of a pointer in number of bytes.
3389 // FIXME: There might(should) be a better way of doing this computation!
3390 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003391 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003392 // The first two arguments (self and _cmd) are pointers; account for
3393 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003394 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003395 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003396 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003397 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003398 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003399 assert (sz.isPositive() &&
3400 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003401 ParmOffset += sz;
3402 }
Ken Dyck40775002010-01-11 17:06:35 +00003403 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003404 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003405 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003406
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003407 // Argument types.
3408 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003409 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003410 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003411 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003412 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003413 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003414 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3415 // Use array's original type only if it has known number of
3416 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003417 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003418 PType = PVDecl->getType();
3419 } else if (PType->isFunctionType())
3420 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003421 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003422 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003423 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003424 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003425 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003426 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003427 }
3428}
3429
Daniel Dunbar4932b362008-08-28 04:38:10 +00003430/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003431/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003432/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3433/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003434/// Property attributes are stored as a comma-delimited C string. The simple
3435/// attributes readonly and bycopy are encoded as single characters. The
3436/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3437/// encoded as single characters, followed by an identifier. Property types
3438/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003439/// these attributes are defined by the following enumeration:
3440/// @code
3441/// enum PropertyAttributes {
3442/// kPropertyReadOnly = 'R', // property is read-only.
3443/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3444/// kPropertyByref = '&', // property is a reference to the value last assigned
3445/// kPropertyDynamic = 'D', // property is dynamic
3446/// kPropertyGetter = 'G', // followed by getter selector name
3447/// kPropertySetter = 'S', // followed by setter selector name
3448/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3449/// kPropertyType = 't' // followed by old-style type encoding.
3450/// kPropertyWeak = 'W' // 'weak' property
3451/// kPropertyStrong = 'P' // property GC'able
3452/// kPropertyNonAtomic = 'N' // property non-atomic
3453/// };
3454/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003455void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003456 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003457 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003458 // Collect information from the property implementation decl(s).
3459 bool Dynamic = false;
3460 ObjCPropertyImplDecl *SynthesizePID = 0;
3461
3462 // FIXME: Duplicated code due to poor abstraction.
3463 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003464 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003465 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3466 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003467 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003468 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003469 ObjCPropertyImplDecl *PID = *i;
3470 if (PID->getPropertyDecl() == PD) {
3471 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3472 Dynamic = true;
3473 } else {
3474 SynthesizePID = PID;
3475 }
3476 }
3477 }
3478 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003479 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003480 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003481 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003482 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003483 ObjCPropertyImplDecl *PID = *i;
3484 if (PID->getPropertyDecl() == PD) {
3485 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3486 Dynamic = true;
3487 } else {
3488 SynthesizePID = PID;
3489 }
3490 }
Mike Stump11289f42009-09-09 15:08:12 +00003491 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003492 }
3493 }
3494
3495 // FIXME: This is not very efficient.
3496 S = "T";
3497
3498 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003499 // GCC has some special rules regarding encoding of properties which
3500 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003501 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003502 true /* outermost type */,
3503 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003504
3505 if (PD->isReadOnly()) {
3506 S += ",R";
3507 } else {
3508 switch (PD->getSetterKind()) {
3509 case ObjCPropertyDecl::Assign: break;
3510 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003511 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003512 }
3513 }
3514
3515 // It really isn't clear at all what this means, since properties
3516 // are "dynamic by default".
3517 if (Dynamic)
3518 S += ",D";
3519
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003520 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3521 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003522
Daniel Dunbar4932b362008-08-28 04:38:10 +00003523 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3524 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003525 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003526 }
3527
3528 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3529 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003530 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003531 }
3532
3533 if (SynthesizePID) {
3534 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3535 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003536 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003537 }
3538
3539 // FIXME: OBJCGC: weak & strong
3540}
3541
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003542/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003543/// Another legacy compatibility encoding: 32-bit longs are encoded as
3544/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003545/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3546///
3547void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003548 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003549 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003550 if (BT->getKind() == BuiltinType::ULong &&
3551 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003552 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003553 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003554 if (BT->getKind() == BuiltinType::Long &&
3555 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003556 PointeeTy = IntTy;
3557 }
3558 }
3559}
3560
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003561void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003562 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003563 // We follow the behavior of gcc, expanding structures which are
3564 // directly pointed to, and expanding embedded structures. Note that
3565 // these rules are sufficient to prevent recursive encoding of the
3566 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003567 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003568 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003569}
3570
David Chisnallb190a2c2010-06-04 01:10:52 +00003571static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3572 switch (T->getAs<BuiltinType>()->getKind()) {
3573 default: assert(0 && "Unhandled builtin type kind");
3574 case BuiltinType::Void: return 'v';
3575 case BuiltinType::Bool: return 'B';
3576 case BuiltinType::Char_U:
3577 case BuiltinType::UChar: return 'C';
3578 case BuiltinType::UShort: return 'S';
3579 case BuiltinType::UInt: return 'I';
3580 case BuiltinType::ULong:
3581 return
3582 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3583 case BuiltinType::UInt128: return 'T';
3584 case BuiltinType::ULongLong: return 'Q';
3585 case BuiltinType::Char_S:
3586 case BuiltinType::SChar: return 'c';
3587 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003588 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003589 case BuiltinType::Int: return 'i';
3590 case BuiltinType::Long:
3591 return
3592 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3593 case BuiltinType::LongLong: return 'q';
3594 case BuiltinType::Int128: return 't';
3595 case BuiltinType::Float: return 'f';
3596 case BuiltinType::Double: return 'd';
3597 case BuiltinType::LongDouble: return 'd';
3598 }
3599}
3600
Mike Stump11289f42009-09-09 15:08:12 +00003601static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003602 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003603 const Expr *E = FD->getBitWidth();
3604 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3605 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003606 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003607 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3608 // The GNU runtime requires more information; bitfields are encoded as b,
3609 // then the offset (in bits) of the first element, then the type of the
3610 // bitfield, then the size in bits. For example, in this structure:
3611 //
3612 // struct
3613 // {
3614 // int integer;
3615 // int flags:2;
3616 // };
3617 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3618 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3619 // information is not especially sensible, but we're stuck with it for
3620 // compatibility with GCC, although providing it breaks anything that
3621 // actually uses runtime introspection and wants to work on both runtimes...
3622 if (!Ctx->getLangOptions().NeXTRuntime) {
3623 const RecordDecl *RD = FD->getParent();
3624 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3625 // FIXME: This same linear search is also used in ExprConstant - it might
3626 // be better if the FieldDecl stored its offset. We'd be increasing the
3627 // size of the object slightly, but saving some time every time it is used.
3628 unsigned i = 0;
3629 for (RecordDecl::field_iterator Field = RD->field_begin(),
3630 FieldEnd = RD->field_end();
3631 Field != FieldEnd; (void)++Field, ++i) {
3632 if (*Field == FD)
3633 break;
3634 }
3635 S += llvm::utostr(RL.getFieldOffset(i));
3636 S += ObjCEncodingForPrimitiveKind(Context, T);
3637 }
3638 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003639 S += llvm::utostr(N);
3640}
3641
Daniel Dunbar07d07852009-10-18 21:17:35 +00003642// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003643void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3644 bool ExpandPointedToStructures,
3645 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003646 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003647 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003648 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003649 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003650 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003651 return EncodeBitField(this, S, T, FD);
3652 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003653 return;
3654 }
Mike Stump11289f42009-09-09 15:08:12 +00003655
John McCall9dd450b2009-09-21 23:43:11 +00003656 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003657 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003658 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003659 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003660 return;
3661 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003662
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003663 // encoding for pointer or r3eference types.
3664 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003665 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003666 if (PT->isObjCSelType()) {
3667 S += ':';
3668 return;
3669 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003670 PointeeTy = PT->getPointeeType();
3671 }
3672 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3673 PointeeTy = RT->getPointeeType();
3674 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003675 bool isReadOnly = false;
3676 // For historical/compatibility reasons, the read-only qualifier of the
3677 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3678 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003679 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003680 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003681 if (OutermostType && T.isConstQualified()) {
3682 isReadOnly = true;
3683 S += 'r';
3684 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003685 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003686 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003687 while (P->getAs<PointerType>())
3688 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003689 if (P.isConstQualified()) {
3690 isReadOnly = true;
3691 S += 'r';
3692 }
3693 }
3694 if (isReadOnly) {
3695 // Another legacy compatibility encoding. Some ObjC qualifier and type
3696 // combinations need to be rearranged.
3697 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003698 if (llvm::StringRef(S).endswith("nr"))
3699 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
Anders Carlssond8499822007-10-29 05:01:08 +00003702 if (PointeeTy->isCharType()) {
3703 // char pointer types should be encoded as '*' unless it is a
3704 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003705 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003706 S += '*';
3707 return;
3708 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003709 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003710 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3711 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3712 S += '#';
3713 return;
3714 }
3715 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3716 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3717 S += '@';
3718 return;
3719 }
3720 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003721 }
Anders Carlssond8499822007-10-29 05:01:08 +00003722 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003723 getLegacyIntegralTypeEncoding(PointeeTy);
3724
Mike Stump11289f42009-09-09 15:08:12 +00003725 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003726 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003727 return;
3728 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003729
Chris Lattnere7cabb92009-07-13 00:10:46 +00003730 if (const ArrayType *AT =
3731 // Ignore type qualifiers etc.
3732 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003733 if (isa<IncompleteArrayType>(AT)) {
3734 // Incomplete arrays are encoded as a pointer to the array element.
3735 S += '^';
3736
Mike Stump11289f42009-09-09 15:08:12 +00003737 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003738 false, ExpandStructures, FD);
3739 } else {
3740 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003741
Anders Carlssond05f44b2009-02-22 01:38:57 +00003742 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3743 S += llvm::utostr(CAT->getSize().getZExtValue());
3744 else {
3745 //Variable length arrays are encoded as a regular array with 0 elements.
3746 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3747 S += '0';
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
3750 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003751 false, ExpandStructures, FD);
3752 S += ']';
3753 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003754 return;
3755 }
Mike Stump11289f42009-09-09 15:08:12 +00003756
John McCall9dd450b2009-09-21 23:43:11 +00003757 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003758 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003759 return;
3760 }
Mike Stump11289f42009-09-09 15:08:12 +00003761
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003762 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003763 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003764 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003765 // Anonymous structures print as '?'
3766 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3767 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003768 if (ClassTemplateSpecializationDecl *Spec
3769 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3770 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3771 std::string TemplateArgsStr
3772 = TemplateSpecializationType::PrintTemplateArgumentList(
3773 TemplateArgs.getFlatArgumentList(),
3774 TemplateArgs.flat_size(),
3775 (*this).PrintingPolicy);
3776
3777 S += TemplateArgsStr;
3778 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003779 } else {
3780 S += '?';
3781 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003782 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003783 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003784 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3785 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003786 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003787 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003788 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003789 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003790 S += '"';
3791 }
Mike Stump11289f42009-09-09 15:08:12 +00003792
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003793 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003794 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003795 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003796 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003797 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003798 QualType qt = Field->getType();
3799 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003800 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003801 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003802 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003803 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003804 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003805 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003806 return;
3807 }
Mike Stump11289f42009-09-09 15:08:12 +00003808
Chris Lattnere7cabb92009-07-13 00:10:46 +00003809 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003810 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003811 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003812 else
3813 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003814 return;
3815 }
Mike Stump11289f42009-09-09 15:08:12 +00003816
Chris Lattnere7cabb92009-07-13 00:10:46 +00003817 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003818 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003819 return;
3820 }
Mike Stump11289f42009-09-09 15:08:12 +00003821
John McCall8b07ec22010-05-15 11:32:37 +00003822 // Ignore protocol qualifiers when mangling at this level.
3823 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3824 T = OT->getBaseType();
3825
John McCall8ccfcb52009-09-24 19:53:00 +00003826 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003827 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003828 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003829 S += '{';
3830 const IdentifierInfo *II = OI->getIdentifier();
3831 S += II->getName();
3832 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003833 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3834 DeepCollectObjCIvars(OI, true, Ivars);
3835 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3836 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3837 if (Field->isBitField())
3838 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003839 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003840 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003841 }
3842 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003843 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003844 }
Mike Stump11289f42009-09-09 15:08:12 +00003845
John McCall9dd450b2009-09-21 23:43:11 +00003846 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003847 if (OPT->isObjCIdType()) {
3848 S += '@';
3849 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003850 }
Mike Stump11289f42009-09-09 15:08:12 +00003851
Steve Narofff0c86112009-10-28 22:03:49 +00003852 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3853 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3854 // Since this is a binary compatibility issue, need to consult with runtime
3855 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003856 S += '#';
3857 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003858 }
Mike Stump11289f42009-09-09 15:08:12 +00003859
Chris Lattnere7cabb92009-07-13 00:10:46 +00003860 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003861 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003862 ExpandPointedToStructures,
3863 ExpandStructures, FD);
3864 if (FD || EncodingProperty) {
3865 // Note that we do extended encoding of protocol qualifer list
3866 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003867 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003868 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3869 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003870 S += '<';
3871 S += (*I)->getNameAsString();
3872 S += '>';
3873 }
3874 S += '"';
3875 }
3876 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003877 }
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattnere7cabb92009-07-13 00:10:46 +00003879 QualType PointeeTy = OPT->getPointeeType();
3880 if (!EncodingProperty &&
3881 isa<TypedefType>(PointeeTy.getTypePtr())) {
3882 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003883 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003884 // {...};
3885 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003886 getObjCEncodingForTypeImpl(PointeeTy, S,
3887 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003888 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003889 return;
3890 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003891
3892 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003893 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003894 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003895 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003896 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3897 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003898 S += '<';
3899 S += (*I)->getNameAsString();
3900 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003901 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003902 S += '"';
3903 }
3904 return;
3905 }
Mike Stump11289f42009-09-09 15:08:12 +00003906
John McCalla9e6e8d2010-05-17 23:56:34 +00003907 // gcc just blithely ignores member pointers.
3908 // TODO: maybe there should be a mangling for these
3909 if (T->getAs<MemberPointerType>())
3910 return;
3911
Chris Lattnere7cabb92009-07-13 00:10:46 +00003912 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003913}
3914
Mike Stump11289f42009-09-09 15:08:12 +00003915void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003916 std::string& S) const {
3917 if (QT & Decl::OBJC_TQ_In)
3918 S += 'n';
3919 if (QT & Decl::OBJC_TQ_Inout)
3920 S += 'N';
3921 if (QT & Decl::OBJC_TQ_Out)
3922 S += 'o';
3923 if (QT & Decl::OBJC_TQ_Bycopy)
3924 S += 'O';
3925 if (QT & Decl::OBJC_TQ_Byref)
3926 S += 'R';
3927 if (QT & Decl::OBJC_TQ_Oneway)
3928 S += 'V';
3929}
3930
Chris Lattnere7cabb92009-07-13 00:10:46 +00003931void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003932 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003933
Anders Carlsson87c149b2007-10-11 01:00:40 +00003934 BuiltinVaListType = T;
3935}
3936
Chris Lattnere7cabb92009-07-13 00:10:46 +00003937void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003938 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003939}
3940
Chris Lattnere7cabb92009-07-13 00:10:46 +00003941void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003942 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003943}
3944
Chris Lattnere7cabb92009-07-13 00:10:46 +00003945void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003946 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003947}
3948
Chris Lattnere7cabb92009-07-13 00:10:46 +00003949void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003950 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003951}
3952
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003953void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003954 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003955 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003956
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003957 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003958}
3959
John McCalld28ae272009-12-02 08:04:21 +00003960/// \brief Retrieve the template name that corresponds to a non-empty
3961/// lookup.
John McCallad371252010-01-20 00:46:10 +00003962TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3963 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003964 unsigned size = End - Begin;
3965 assert(size > 1 && "set is not overloaded!");
3966
3967 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3968 size * sizeof(FunctionTemplateDecl*));
3969 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3970
3971 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003972 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003973 NamedDecl *D = *I;
3974 assert(isa<FunctionTemplateDecl>(D) ||
3975 (isa<UsingShadowDecl>(D) &&
3976 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3977 *Storage++ = D;
3978 }
3979
3980 return TemplateName(OT);
3981}
3982
Douglas Gregordc572a32009-03-30 22:58:21 +00003983/// \brief Retrieve the template name that represents a qualified
3984/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003985TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003986 bool TemplateKeyword,
3987 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003988 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003989 llvm::FoldingSetNodeID ID;
3990 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3991
3992 void *InsertPos = 0;
3993 QualifiedTemplateName *QTN =
3994 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3995 if (!QTN) {
3996 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3997 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3998 }
3999
4000 return TemplateName(QTN);
4001}
4002
4003/// \brief Retrieve the template name that represents a dependent
4004/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004005TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004006 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004007 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004008 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004009
4010 llvm::FoldingSetNodeID ID;
4011 DependentTemplateName::Profile(ID, NNS, Name);
4012
4013 void *InsertPos = 0;
4014 DependentTemplateName *QTN =
4015 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4016
4017 if (QTN)
4018 return TemplateName(QTN);
4019
4020 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4021 if (CanonNNS == NNS) {
4022 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4023 } else {
4024 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4025 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004026 DependentTemplateName *CheckQTN =
4027 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4028 assert(!CheckQTN && "Dependent type name canonicalization broken");
4029 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004030 }
4031
4032 DependentTemplateNames.InsertNode(QTN, InsertPos);
4033 return TemplateName(QTN);
4034}
4035
Douglas Gregor71395fa2009-11-04 00:56:37 +00004036/// \brief Retrieve the template name that represents a dependent
4037/// template name such as \c MetaFun::template operator+.
4038TemplateName
4039ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4040 OverloadedOperatorKind Operator) {
4041 assert((!NNS || NNS->isDependent()) &&
4042 "Nested name specifier must be dependent");
4043
4044 llvm::FoldingSetNodeID ID;
4045 DependentTemplateName::Profile(ID, NNS, Operator);
4046
4047 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004048 DependentTemplateName *QTN
4049 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004050
4051 if (QTN)
4052 return TemplateName(QTN);
4053
4054 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4055 if (CanonNNS == NNS) {
4056 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4057 } else {
4058 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4059 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004060
4061 DependentTemplateName *CheckQTN
4062 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4063 assert(!CheckQTN && "Dependent template name canonicalization broken");
4064 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004065 }
4066
4067 DependentTemplateNames.InsertNode(QTN, InsertPos);
4068 return TemplateName(QTN);
4069}
4070
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004071/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004072/// TargetInfo, produce the corresponding type. The unsigned @p Type
4073/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004074CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004075 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004076 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004077 case TargetInfo::SignedShort: return ShortTy;
4078 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4079 case TargetInfo::SignedInt: return IntTy;
4080 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4081 case TargetInfo::SignedLong: return LongTy;
4082 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4083 case TargetInfo::SignedLongLong: return LongLongTy;
4084 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4085 }
4086
4087 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004088 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004089}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004090
4091//===----------------------------------------------------------------------===//
4092// Type Predicates.
4093//===----------------------------------------------------------------------===//
4094
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004095/// isObjCNSObjectType - Return true if this is an NSObject object using
4096/// NSObject attribute on a c-style pointer type.
4097/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004098/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004099///
4100bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4101 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4102 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004103 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004104 return true;
4105 }
Mike Stump11289f42009-09-09 15:08:12 +00004106 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004107}
4108
Fariborz Jahanian96207692009-02-18 21:49:28 +00004109/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4110/// garbage collection attribute.
4111///
John McCall8ccfcb52009-09-24 19:53:00 +00004112Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4113 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004114 if (getLangOptions().ObjC1 &&
4115 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004116 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004117 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004118 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004119 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004120 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004121 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004122 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004123 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004124 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004125 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004126 // Non-pointers have none gc'able attribute regardless of the attribute
4127 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004128 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004129 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004130 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004131 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004132}
4133
Chris Lattner49af6a42008-04-07 06:51:04 +00004134//===----------------------------------------------------------------------===//
4135// Type Compatibility Testing
4136//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004137
Mike Stump11289f42009-09-09 15:08:12 +00004138/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004139/// compatible.
4140static bool areCompatVectorTypes(const VectorType *LHS,
4141 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004142 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004143 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004144 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004145}
4146
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004147bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4148 QualType SecondVec) {
4149 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4150 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4151
4152 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4153 return true;
4154
4155 // AltiVec vectors types are identical to equivalent GCC vector types
4156 const VectorType *First = FirstVec->getAs<VectorType>();
4157 const VectorType *Second = SecondVec->getAs<VectorType>();
4158 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4159 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4160 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4161 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4162 hasSameType(First->getElementType(), Second->getElementType()) &&
4163 (First->getNumElements() == Second->getNumElements()))
4164 return true;
4165
4166 return false;
4167}
4168
Steve Naroff8e6aee52009-07-23 01:01:38 +00004169//===----------------------------------------------------------------------===//
4170// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4171//===----------------------------------------------------------------------===//
4172
4173/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4174/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004175bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4176 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004177 if (lProto == rProto)
4178 return true;
4179 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4180 E = rProto->protocol_end(); PI != E; ++PI)
4181 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4182 return true;
4183 return false;
4184}
4185
Steve Naroff8e6aee52009-07-23 01:01:38 +00004186/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4187/// return true if lhs's protocols conform to rhs's protocol; false
4188/// otherwise.
4189bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4190 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4191 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4192 return false;
4193}
4194
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004195/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4196/// Class<p1, ...>.
4197bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4198 QualType rhs) {
4199 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4200 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4201 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4202
4203 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4204 E = lhsQID->qual_end(); I != E; ++I) {
4205 bool match = false;
4206 ObjCProtocolDecl *lhsProto = *I;
4207 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4208 E = rhsOPT->qual_end(); J != E; ++J) {
4209 ObjCProtocolDecl *rhsProto = *J;
4210 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4211 match = true;
4212 break;
4213 }
4214 }
4215 if (!match)
4216 return false;
4217 }
4218 return true;
4219}
4220
Steve Naroff8e6aee52009-07-23 01:01:38 +00004221/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4222/// ObjCQualifiedIDType.
4223bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4224 bool compare) {
4225 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004226 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004227 lhs->isObjCIdType() || lhs->isObjCClassType())
4228 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004229 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004230 rhs->isObjCIdType() || rhs->isObjCClassType())
4231 return true;
4232
4233 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004234 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004235
Steve Naroff8e6aee52009-07-23 01:01:38 +00004236 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004237
Steve Naroff8e6aee52009-07-23 01:01:38 +00004238 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004239 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004240 // make sure we check the class hierarchy.
4241 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4242 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4243 E = lhsQID->qual_end(); I != E; ++I) {
4244 // when comparing an id<P> on lhs with a static type on rhs,
4245 // see if static class implements all of id's protocols, directly or
4246 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004247 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004248 return false;
4249 }
4250 }
4251 // If there are no qualifiers and no interface, we have an 'id'.
4252 return true;
4253 }
Mike Stump11289f42009-09-09 15:08:12 +00004254 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004255 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4256 E = lhsQID->qual_end(); I != E; ++I) {
4257 ObjCProtocolDecl *lhsProto = *I;
4258 bool match = false;
4259
4260 // when comparing an id<P> on lhs with a static type on rhs,
4261 // see if static class implements all of id's protocols, directly or
4262 // through its super class and categories.
4263 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4264 E = rhsOPT->qual_end(); J != E; ++J) {
4265 ObjCProtocolDecl *rhsProto = *J;
4266 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4267 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4268 match = true;
4269 break;
4270 }
4271 }
Mike Stump11289f42009-09-09 15:08:12 +00004272 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004273 // make sure we check the class hierarchy.
4274 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4275 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4276 E = lhsQID->qual_end(); I != E; ++I) {
4277 // when comparing an id<P> on lhs with a static type on rhs,
4278 // see if static class implements all of id's protocols, directly or
4279 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004280 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004281 match = true;
4282 break;
4283 }
4284 }
4285 }
4286 if (!match)
4287 return false;
4288 }
Mike Stump11289f42009-09-09 15:08:12 +00004289
Steve Naroff8e6aee52009-07-23 01:01:38 +00004290 return true;
4291 }
Mike Stump11289f42009-09-09 15:08:12 +00004292
Steve Naroff8e6aee52009-07-23 01:01:38 +00004293 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4294 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4295
Mike Stump11289f42009-09-09 15:08:12 +00004296 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004297 lhs->getAsObjCInterfacePointerType()) {
4298 if (lhsOPT->qual_empty()) {
4299 bool match = false;
4300 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4301 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4302 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahanianec430222010-08-09 18:21:43 +00004303 // when comparing an id<P> on rhs with a static type on lhs,
4304 // static class must implement all of id's protocols directly or
4305 // indirectly through its super class.
Fariborz Jahanian753783a2010-08-12 20:46:12 +00004306 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004307 match = true;
4308 break;
4309 }
4310 }
4311 if (!match)
4312 return false;
4313 }
4314 return true;
4315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004317 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4318 E = lhsOPT->qual_end(); I != E; ++I) {
4319 ObjCProtocolDecl *lhsProto = *I;
4320 bool match = false;
4321
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.
4325 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4326 E = rhsQID->qual_end(); J != E; ++J) {
4327 ObjCProtocolDecl *rhsProto = *J;
4328 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4329 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4330 match = true;
4331 break;
4332 }
4333 }
4334 if (!match)
4335 return false;
4336 }
4337 return true;
4338 }
4339 return false;
4340}
4341
Eli Friedman47f77112008-08-22 00:56:42 +00004342/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004343/// compatible for assignment from RHS to LHS. This handles validation of any
4344/// protocol qualifiers on the LHS or RHS.
4345///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004346bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4347 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004348 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4349 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4350
Steve Naroff1329fa02009-07-15 18:40:39 +00004351 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004352 if (LHS->isObjCUnqualifiedIdOrClass() ||
4353 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004354 return true;
4355
John McCall8b07ec22010-05-15 11:32:37 +00004356 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004357 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4358 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004359 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004360
4361 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4362 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4363 QualType(RHSOPT,0));
4364
John McCall8b07ec22010-05-15 11:32:37 +00004365 // If we have 2 user-defined types, fall into that path.
4366 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004367 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004368
Steve Naroff8e6aee52009-07-23 01:01:38 +00004369 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004370}
4371
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004372/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4373/// for providing type-safty for objective-c pointers used to pass/return
4374/// arguments in block literals. When passed as arguments, passing 'A*' where
4375/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4376/// not OK. For the return type, the opposite is not OK.
4377bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4378 const ObjCObjectPointerType *LHSOPT,
4379 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004380 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004381 return true;
4382
4383 if (LHSOPT->isObjCBuiltinType()) {
4384 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4385 }
4386
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004387 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004388 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4389 QualType(RHSOPT,0),
4390 false);
4391
4392 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4393 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4394 if (LHS && RHS) { // We have 2 user-defined types.
4395 if (LHS != RHS) {
4396 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4397 return false;
4398 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4399 return true;
4400 }
4401 else
4402 return true;
4403 }
4404 return false;
4405}
4406
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004407/// getIntersectionOfProtocols - This routine finds the intersection of set
4408/// of protocols inherited from two distinct objective-c pointer objects.
4409/// It is used to build composite qualifier list of the composite type of
4410/// the conditional expression involving two objective-c pointer objects.
4411static
4412void getIntersectionOfProtocols(ASTContext &Context,
4413 const ObjCObjectPointerType *LHSOPT,
4414 const ObjCObjectPointerType *RHSOPT,
4415 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4416
John McCall8b07ec22010-05-15 11:32:37 +00004417 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4418 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4419 assert(LHS->getInterface() && "LHS must have an interface base");
4420 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004421
4422 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4423 unsigned LHSNumProtocols = LHS->getNumProtocols();
4424 if (LHSNumProtocols > 0)
4425 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4426 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004427 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004428 Context.CollectInheritedProtocols(LHS->getInterface(),
4429 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004430 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4431 LHSInheritedProtocols.end());
4432 }
4433
4434 unsigned RHSNumProtocols = RHS->getNumProtocols();
4435 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004436 ObjCProtocolDecl **RHSProtocols =
4437 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004438 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4439 if (InheritedProtocolSet.count(RHSProtocols[i]))
4440 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4441 }
4442 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004443 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004444 Context.CollectInheritedProtocols(RHS->getInterface(),
4445 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004446 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4447 RHSInheritedProtocols.begin(),
4448 E = RHSInheritedProtocols.end(); I != E; ++I)
4449 if (InheritedProtocolSet.count((*I)))
4450 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004451 }
4452}
4453
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004454/// areCommonBaseCompatible - Returns common base class of the two classes if
4455/// one found. Note that this is O'2 algorithm. But it will be called as the
4456/// last type comparison in a ?-exp of ObjC pointer types before a
4457/// warning is issued. So, its invokation is extremely rare.
4458QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004459 const ObjCObjectPointerType *Lptr,
4460 const ObjCObjectPointerType *Rptr) {
4461 const ObjCObjectType *LHS = Lptr->getObjectType();
4462 const ObjCObjectType *RHS = Rptr->getObjectType();
4463 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4464 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4465 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004466 return QualType();
4467
John McCall8b07ec22010-05-15 11:32:37 +00004468 while ((LDecl = LDecl->getSuperClass())) {
4469 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004470 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004471 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4472 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4473
4474 QualType Result = QualType(LHS, 0);
4475 if (!Protocols.empty())
4476 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4477 Result = getObjCObjectPointerType(Result);
4478 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004479 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004480 }
4481
4482 return QualType();
4483}
4484
John McCall8b07ec22010-05-15 11:32:37 +00004485bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4486 const ObjCObjectType *RHS) {
4487 assert(LHS->getInterface() && "LHS is not an interface type");
4488 assert(RHS->getInterface() && "RHS is not an interface type");
4489
Chris Lattner49af6a42008-04-07 06:51:04 +00004490 // Verify that the base decls are compatible: the RHS must be a subclass of
4491 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004492 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004493 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004494
Chris Lattner49af6a42008-04-07 06:51:04 +00004495 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4496 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004497 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004498 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004499
Chris Lattner49af6a42008-04-07 06:51:04 +00004500 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4501 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004502 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004503 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004504
John McCall8b07ec22010-05-15 11:32:37 +00004505 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4506 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004507 LHSPI != LHSPE; LHSPI++) {
4508 bool RHSImplementsProtocol = false;
4509
4510 // If the RHS doesn't implement the protocol on the left, the types
4511 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004512 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4513 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004514 RHSPI != RHSPE; RHSPI++) {
4515 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004516 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004517 break;
4518 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004519 }
4520 // FIXME: For better diagnostics, consider passing back the protocol name.
4521 if (!RHSImplementsProtocol)
4522 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004523 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004524 // The RHS implements all protocols listed on the LHS.
4525 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004526}
4527
Steve Naroffb7605152009-02-12 17:52:19 +00004528bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4529 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004530 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4531 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004532
Steve Naroff7cae42b2009-07-10 23:34:53 +00004533 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004534 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004535
4536 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4537 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004538}
4539
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004540bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4541 return canAssignObjCInterfaces(
4542 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4543 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4544}
4545
Mike Stump11289f42009-09-09 15:08:12 +00004546/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004547/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004548/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004549/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004550bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4551 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004552 if (getLangOptions().CPlusPlus)
4553 return hasSameType(LHS, RHS);
4554
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004555 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004556}
4557
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004558bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4559 return !mergeTypes(LHS, RHS, true).isNull();
4560}
4561
4562QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004563 bool OfBlockPointer,
4564 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004565 const FunctionType *lbase = lhs->getAs<FunctionType>();
4566 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004567 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4568 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004569 bool allLTypes = true;
4570 bool allRTypes = true;
4571
4572 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004573 QualType retType;
4574 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004575 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4576 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004577 else
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004578 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4579 false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004580 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004581
4582 if (Unqualified)
4583 retType = retType.getUnqualifiedType();
4584
4585 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4586 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4587 if (Unqualified) {
4588 LRetType = LRetType.getUnqualifiedType();
4589 RRetType = RRetType.getUnqualifiedType();
4590 }
4591
4592 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004593 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004594 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004595 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004596 // FIXME: double check this
4597 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4598 // rbase->getRegParmAttr() != 0 &&
4599 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004600 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4601 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004602 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4603 lbaseInfo.getRegParm();
4604 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4605 if (NoReturn != lbaseInfo.getNoReturn() ||
4606 RegParm != lbaseInfo.getRegParm())
4607 allLTypes = false;
4608 if (NoReturn != rbaseInfo.getNoReturn() ||
4609 RegParm != rbaseInfo.getRegParm())
4610 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004611 CallingConv lcc = lbaseInfo.getCC();
4612 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004613 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004614 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004615 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004616
Eli Friedman47f77112008-08-22 00:56:42 +00004617 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004618 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4619 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004620 unsigned lproto_nargs = lproto->getNumArgs();
4621 unsigned rproto_nargs = rproto->getNumArgs();
4622
4623 // Compatible functions must have the same number of arguments
4624 if (lproto_nargs != rproto_nargs)
4625 return QualType();
4626
4627 // Variadic and non-variadic functions aren't compatible
4628 if (lproto->isVariadic() != rproto->isVariadic())
4629 return QualType();
4630
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004631 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4632 return QualType();
4633
Eli Friedman47f77112008-08-22 00:56:42 +00004634 // Check argument compatibility
4635 llvm::SmallVector<QualType, 10> types;
4636 for (unsigned i = 0; i < lproto_nargs; i++) {
4637 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4638 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004639 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4640 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004641 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004642
4643 if (Unqualified)
4644 argtype = argtype.getUnqualifiedType();
4645
Eli Friedman47f77112008-08-22 00:56:42 +00004646 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004647 if (Unqualified) {
4648 largtype = largtype.getUnqualifiedType();
4649 rargtype = rargtype.getUnqualifiedType();
4650 }
4651
Chris Lattner465fa322008-10-05 17:34:18 +00004652 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4653 allLTypes = false;
4654 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4655 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004656 }
4657 if (allLTypes) return lhs;
4658 if (allRTypes) return rhs;
4659 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004660 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004661 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004662 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004663 }
4664
4665 if (lproto) allRTypes = false;
4666 if (rproto) allLTypes = false;
4667
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004668 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004669 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004670 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004671 if (proto->isVariadic()) return QualType();
4672 // Check that the types are compatible with the types that
4673 // would result from default argument promotions (C99 6.7.5.3p15).
4674 // The only types actually affected are promotable integer
4675 // types and floats, which would be passed as a different
4676 // type depending on whether the prototype is visible.
4677 unsigned proto_nargs = proto->getNumArgs();
4678 for (unsigned i = 0; i < proto_nargs; ++i) {
4679 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004680
4681 // Look at the promotion type of enum types, since that is the type used
4682 // to pass enum values.
4683 if (const EnumType *Enum = argTy->getAs<EnumType>())
4684 argTy = Enum->getDecl()->getPromotionType();
4685
Eli Friedman47f77112008-08-22 00:56:42 +00004686 if (argTy->isPromotableIntegerType() ||
4687 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4688 return QualType();
4689 }
4690
4691 if (allLTypes) return lhs;
4692 if (allRTypes) return rhs;
4693 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004694 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004695 proto->getTypeQuals(),
4696 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004697 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004698 }
4699
4700 if (allLTypes) return lhs;
4701 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004702 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004703 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004704}
4705
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004706QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004707 bool OfBlockPointer,
4708 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004709 // C++ [expr]: If an expression initially has the type "reference to T", the
4710 // type is adjusted to "T" prior to any further analysis, the expression
4711 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004712 // expression is an lvalue unless the reference is an rvalue reference and
4713 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004714 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4715 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004716
4717 if (Unqualified) {
4718 LHS = LHS.getUnqualifiedType();
4719 RHS = RHS.getUnqualifiedType();
4720 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00004721
Eli Friedman47f77112008-08-22 00:56:42 +00004722 QualType LHSCan = getCanonicalType(LHS),
4723 RHSCan = getCanonicalType(RHS);
4724
4725 // If two types are identical, they are compatible.
4726 if (LHSCan == RHSCan)
4727 return LHS;
4728
John McCall8ccfcb52009-09-24 19:53:00 +00004729 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004730 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4731 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004732 if (LQuals != RQuals) {
4733 // If any of these qualifiers are different, we have a type
4734 // mismatch.
4735 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4736 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4737 return QualType();
4738
4739 // Exactly one GC qualifier difference is allowed: __strong is
4740 // okay if the other type has no GC qualifier but is an Objective
4741 // C object pointer (i.e. implicitly strong by default). We fix
4742 // this by pretending that the unqualified type was actually
4743 // qualified __strong.
4744 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4745 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4746 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4747
4748 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4749 return QualType();
4750
4751 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4752 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4753 }
4754 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4755 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4756 }
Eli Friedman47f77112008-08-22 00:56:42 +00004757 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004758 }
4759
4760 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004761
Eli Friedmandcca6332009-06-01 01:22:52 +00004762 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4763 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004764
Chris Lattnerfd652912008-01-14 05:45:46 +00004765 // We want to consider the two function types to be the same for these
4766 // comparisons, just force one to the other.
4767 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4768 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004769
4770 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004771 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4772 LHSClass = Type::ConstantArray;
4773 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4774 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004775
John McCall8b07ec22010-05-15 11:32:37 +00004776 // ObjCInterfaces are just specialized ObjCObjects.
4777 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4778 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4779
Nate Begemance4d7fc2008-04-18 23:10:10 +00004780 // Canonicalize ExtVector -> Vector.
4781 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4782 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004783
Chris Lattner95554662008-04-07 05:43:21 +00004784 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004785 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004786 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004787 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004788 // Compatibility is based on the underlying type, not the promotion
4789 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004790 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004791 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4792 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004793 }
John McCall9dd450b2009-09-21 23:43:11 +00004794 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004795 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4796 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004797 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004798
Eli Friedman47f77112008-08-22 00:56:42 +00004799 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004800 }
Eli Friedman47f77112008-08-22 00:56:42 +00004801
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004802 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004803 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004804#define TYPE(Class, Base)
4805#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004806#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004807#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4808#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4809#include "clang/AST/TypeNodes.def"
4810 assert(false && "Non-canonical and dependent types shouldn't get here");
4811 return QualType();
4812
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004813 case Type::LValueReference:
4814 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004815 case Type::MemberPointer:
4816 assert(false && "C++ should never be in mergeTypes");
4817 return QualType();
4818
John McCall8b07ec22010-05-15 11:32:37 +00004819 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004820 case Type::IncompleteArray:
4821 case Type::VariableArray:
4822 case Type::FunctionProto:
4823 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004824 assert(false && "Types are eliminated above");
4825 return QualType();
4826
Chris Lattnerfd652912008-01-14 05:45:46 +00004827 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004828 {
4829 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004830 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4831 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004832 if (Unqualified) {
4833 LHSPointee = LHSPointee.getUnqualifiedType();
4834 RHSPointee = RHSPointee.getUnqualifiedType();
4835 }
4836 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4837 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004838 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004839 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004840 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004841 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004842 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004843 return getPointerType(ResultType);
4844 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004845 case Type::BlockPointer:
4846 {
4847 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004848 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4849 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004850 if (Unqualified) {
4851 LHSPointee = LHSPointee.getUnqualifiedType();
4852 RHSPointee = RHSPointee.getUnqualifiedType();
4853 }
4854 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4855 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00004856 if (ResultType.isNull()) return QualType();
4857 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4858 return LHS;
4859 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4860 return RHS;
4861 return getBlockPointerType(ResultType);
4862 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004863 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004864 {
4865 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4866 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4867 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4868 return QualType();
4869
4870 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4871 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004872 if (Unqualified) {
4873 LHSElem = LHSElem.getUnqualifiedType();
4874 RHSElem = RHSElem.getUnqualifiedType();
4875 }
4876
4877 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004878 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004879 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4880 return LHS;
4881 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4882 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004883 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4884 ArrayType::ArraySizeModifier(), 0);
4885 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4886 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004887 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4888 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004889 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4890 return LHS;
4891 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4892 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004893 if (LVAT) {
4894 // FIXME: This isn't correct! But tricky to implement because
4895 // the array's size has to be the size of LHS, but the type
4896 // has to be different.
4897 return LHS;
4898 }
4899 if (RVAT) {
4900 // FIXME: This isn't correct! But tricky to implement because
4901 // the array's size has to be the size of RHS, but the type
4902 // has to be different.
4903 return RHS;
4904 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004905 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4906 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004907 return getIncompleteArrayType(ResultType,
4908 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004909 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004910 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004911 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004912 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004913 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004914 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004915 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004916 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004917 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004918 case Type::Complex:
4919 // Distinct complex types are incompatible.
4920 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004921 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004922 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004923 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4924 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004925 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004926 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004927 case Type::ObjCObject: {
4928 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004929 // FIXME: This should be type compatibility, e.g. whether
4930 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004931 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4932 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4933 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004934 return LHS;
4935
Eli Friedman47f77112008-08-22 00:56:42 +00004936 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004937 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004938 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004939 if (OfBlockPointer) {
4940 if (canAssignObjCInterfacesInBlockPointer(
4941 LHS->getAs<ObjCObjectPointerType>(),
4942 RHS->getAs<ObjCObjectPointerType>()))
4943 return LHS;
4944 return QualType();
4945 }
John McCall9dd450b2009-09-21 23:43:11 +00004946 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4947 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004948 return LHS;
4949
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004950 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004951 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004952 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004953
4954 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004955}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004956
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004957/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4958/// 'RHS' attributes and returns the merged version; including for function
4959/// return types.
4960QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4961 QualType LHSCan = getCanonicalType(LHS),
4962 RHSCan = getCanonicalType(RHS);
4963 // If two types are identical, they are compatible.
4964 if (LHSCan == RHSCan)
4965 return LHS;
4966 if (RHSCan->isFunctionType()) {
4967 if (!LHSCan->isFunctionType())
4968 return QualType();
4969 QualType OldReturnType =
4970 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4971 QualType NewReturnType =
4972 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4973 QualType ResReturnType =
4974 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4975 if (ResReturnType.isNull())
4976 return QualType();
4977 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4978 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4979 // In either case, use OldReturnType to build the new function type.
4980 const FunctionType *F = LHS->getAs<FunctionType>();
4981 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4982 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4983 QualType ResultType
4984 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4985 FPT->getNumArgs(), FPT->isVariadic(),
4986 FPT->getTypeQuals(),
4987 FPT->hasExceptionSpec(),
4988 FPT->hasAnyExceptionSpec(),
4989 FPT->getNumExceptions(),
4990 FPT->exception_begin(),
4991 Info);
4992 return ResultType;
4993 }
4994 }
4995 return QualType();
4996 }
4997
4998 // If the qualifiers are different, the types can still be merged.
4999 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5000 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5001 if (LQuals != RQuals) {
5002 // If any of these qualifiers are different, we have a type mismatch.
5003 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5004 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5005 return QualType();
5006
5007 // Exactly one GC qualifier difference is allowed: __strong is
5008 // okay if the other type has no GC qualifier but is an Objective
5009 // C object pointer (i.e. implicitly strong by default). We fix
5010 // this by pretending that the unqualified type was actually
5011 // qualified __strong.
5012 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5013 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5014 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5015
5016 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5017 return QualType();
5018
5019 if (GC_L == Qualifiers::Strong)
5020 return LHS;
5021 if (GC_R == Qualifiers::Strong)
5022 return RHS;
5023 return QualType();
5024 }
5025
5026 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5027 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5028 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5029 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5030 if (ResQT == LHSBaseQT)
5031 return LHS;
5032 if (ResQT == RHSBaseQT)
5033 return RHS;
5034 }
5035 return QualType();
5036}
5037
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005038//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005039// Integer Predicates
5040//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005041
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005042unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00005043 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005044 return 1;
John McCall56774992009-12-09 09:09:27 +00005045 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005046 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00005047 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005048 return (unsigned)getTypeSize(T);
5049}
5050
5051QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005052 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005053
5054 // Turn <4 x signed int> -> <4 x unsigned int>
5055 if (const VectorType *VTy = T->getAs<VectorType>())
5056 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00005057 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005058
5059 // For enums, we return the unsigned version of the base type.
5060 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005061 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005062
5063 const BuiltinType *BTy = T->getAs<BuiltinType>();
5064 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005065 switch (BTy->getKind()) {
5066 case BuiltinType::Char_S:
5067 case BuiltinType::SChar:
5068 return UnsignedCharTy;
5069 case BuiltinType::Short:
5070 return UnsignedShortTy;
5071 case BuiltinType::Int:
5072 return UnsignedIntTy;
5073 case BuiltinType::Long:
5074 return UnsignedLongTy;
5075 case BuiltinType::LongLong:
5076 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005077 case BuiltinType::Int128:
5078 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005079 default:
5080 assert(0 && "Unexpected signed integer type");
5081 return QualType();
5082 }
5083}
5084
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005085ExternalASTSource::~ExternalASTSource() { }
5086
5087void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005088
5089
5090//===----------------------------------------------------------------------===//
5091// Builtin Type Computation
5092//===----------------------------------------------------------------------===//
5093
5094/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5095/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00005096static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005097 ASTContext::GetBuiltinTypeError &Error,
5098 bool AllowTypeModifiers = true) {
5099 // Modifiers.
5100 int HowLong = 0;
5101 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00005102
Chris Lattnerecd79c62009-06-14 00:45:47 +00005103 // Read the modifiers first.
5104 bool Done = false;
5105 while (!Done) {
5106 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005107 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005108 case 'S':
5109 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5110 assert(!Signed && "Can't use 'S' modifier multiple times!");
5111 Signed = true;
5112 break;
5113 case 'U':
5114 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5115 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5116 Unsigned = true;
5117 break;
5118 case 'L':
5119 assert(HowLong <= 2 && "Can't have LLLL modifier");
5120 ++HowLong;
5121 break;
5122 }
5123 }
5124
5125 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005126
Chris Lattnerecd79c62009-06-14 00:45:47 +00005127 // Read the base type.
5128 switch (*Str++) {
5129 default: assert(0 && "Unknown builtin type letter!");
5130 case 'v':
5131 assert(HowLong == 0 && !Signed && !Unsigned &&
5132 "Bad modifiers used with 'v'!");
5133 Type = Context.VoidTy;
5134 break;
5135 case 'f':
5136 assert(HowLong == 0 && !Signed && !Unsigned &&
5137 "Bad modifiers used with 'f'!");
5138 Type = Context.FloatTy;
5139 break;
5140 case 'd':
5141 assert(HowLong < 2 && !Signed && !Unsigned &&
5142 "Bad modifiers used with 'd'!");
5143 if (HowLong)
5144 Type = Context.LongDoubleTy;
5145 else
5146 Type = Context.DoubleTy;
5147 break;
5148 case 's':
5149 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5150 if (Unsigned)
5151 Type = Context.UnsignedShortTy;
5152 else
5153 Type = Context.ShortTy;
5154 break;
5155 case 'i':
5156 if (HowLong == 3)
5157 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5158 else if (HowLong == 2)
5159 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5160 else if (HowLong == 1)
5161 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5162 else
5163 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5164 break;
5165 case 'c':
5166 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5167 if (Signed)
5168 Type = Context.SignedCharTy;
5169 else if (Unsigned)
5170 Type = Context.UnsignedCharTy;
5171 else
5172 Type = Context.CharTy;
5173 break;
5174 case 'b': // boolean
5175 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5176 Type = Context.BoolTy;
5177 break;
5178 case 'z': // size_t.
5179 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5180 Type = Context.getSizeType();
5181 break;
5182 case 'F':
5183 Type = Context.getCFConstantStringType();
5184 break;
5185 case 'a':
5186 Type = Context.getBuiltinVaListType();
5187 assert(!Type.isNull() && "builtin va list type not initialized!");
5188 break;
5189 case 'A':
5190 // This is a "reference" to a va_list; however, what exactly
5191 // this means depends on how va_list is defined. There are two
5192 // different kinds of va_list: ones passed by value, and ones
5193 // passed by reference. An example of a by-value va_list is
5194 // x86, where va_list is a char*. An example of by-ref va_list
5195 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5196 // we want this argument to be a char*&; for x86-64, we want
5197 // it to be a __va_list_tag*.
5198 Type = Context.getBuiltinVaListType();
5199 assert(!Type.isNull() && "builtin va list type not initialized!");
5200 if (Type->isArrayType()) {
5201 Type = Context.getArrayDecayedType(Type);
5202 } else {
5203 Type = Context.getLValueReferenceType(Type);
5204 }
5205 break;
5206 case 'V': {
5207 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005208 unsigned NumElements = strtoul(Str, &End, 10);
5209 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005210
Chris Lattnerecd79c62009-06-14 00:45:47 +00005211 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005212
Chris Lattnerecd79c62009-06-14 00:45:47 +00005213 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005214 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005215 Type = Context.getVectorType(ElementType, NumElements,
5216 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005217 break;
5218 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005219 case 'X': {
5220 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5221 Type = Context.getComplexType(ElementType);
5222 break;
5223 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005224 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005225 Type = Context.getFILEType();
5226 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005227 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005228 return QualType();
5229 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005230 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005231 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005232 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005233 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005234 else
5235 Type = Context.getjmp_bufType();
5236
Mike Stump2adb4da2009-07-28 23:47:15 +00005237 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005238 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005239 return QualType();
5240 }
5241 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005242 }
Mike Stump11289f42009-09-09 15:08:12 +00005243
Chris Lattnerecd79c62009-06-14 00:45:47 +00005244 if (!AllowTypeModifiers)
5245 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005246
Chris Lattnerecd79c62009-06-14 00:45:47 +00005247 Done = false;
5248 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005249 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005250 default: Done = true; --Str; break;
5251 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005252 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005253 {
5254 // Both pointers and references can have their pointee types
5255 // qualified with an address space.
5256 char *End;
5257 unsigned AddrSpace = strtoul(Str, &End, 10);
5258 if (End != Str && AddrSpace != 0) {
5259 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5260 Str = End;
5261 }
5262 }
5263 if (c == '*')
5264 Type = Context.getPointerType(Type);
5265 else
5266 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005267 break;
5268 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5269 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005270 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005271 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005272 case 'D':
5273 Type = Context.getVolatileType(Type);
5274 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005275 }
5276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277
Chris Lattnerecd79c62009-06-14 00:45:47 +00005278 return Type;
5279}
5280
5281/// GetBuiltinType - Return the type for the specified builtin.
5282QualType ASTContext::GetBuiltinType(unsigned id,
5283 GetBuiltinTypeError &Error) {
5284 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005285
Chris Lattnerecd79c62009-06-14 00:45:47 +00005286 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005287
Chris Lattnerecd79c62009-06-14 00:45:47 +00005288 Error = GE_None;
5289 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5290 if (Error != GE_None)
5291 return QualType();
5292 while (TypeStr[0] && TypeStr[0] != '.') {
5293 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5294 if (Error != GE_None)
5295 return QualType();
5296
5297 // Do array -> pointer decay. The builtin should use the decayed type.
5298 if (Ty->isArrayType())
5299 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005300
Chris Lattnerecd79c62009-06-14 00:45:47 +00005301 ArgTypes.push_back(Ty);
5302 }
5303
5304 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5305 "'.' should only occur at end of builtin type list!");
5306
5307 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5308 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5309 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005310
5311 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005312 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005313 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005314 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005315}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005316
5317QualType
5318ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5319 // Perform the usual unary conversions. We do this early so that
5320 // integral promotions to "int" can allow us to exit early, in the
5321 // lhs == rhs check. Also, for conversion purposes, we ignore any
5322 // qualifiers. For example, "const float" and "float" are
5323 // equivalent.
5324 if (lhs->isPromotableIntegerType())
5325 lhs = getPromotedIntegerType(lhs);
5326 else
5327 lhs = lhs.getUnqualifiedType();
5328 if (rhs->isPromotableIntegerType())
5329 rhs = getPromotedIntegerType(rhs);
5330 else
5331 rhs = rhs.getUnqualifiedType();
5332
5333 // If both types are identical, no conversion is needed.
5334 if (lhs == rhs)
5335 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005336
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005337 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5338 // The caller can deal with this (e.g. pointer + int).
5339 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5340 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005341
5342 // At this point, we have two different arithmetic types.
5343
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005344 // Handle complex types first (C99 6.3.1.8p1).
5345 if (lhs->isComplexType() || rhs->isComplexType()) {
5346 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005347 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005348 // convert the rhs to the lhs complex type.
5349 return lhs;
5350 }
Mike Stump11289f42009-09-09 15:08:12 +00005351 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005352 // convert the lhs to the rhs complex type.
5353 return rhs;
5354 }
5355 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005356 // When both operands are complex, the shorter operand is converted to the
5357 // type of the longer, and that is the type of the result. This corresponds
5358 // to what is done when combining two real floating-point operands.
5359 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005360 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005361 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005362 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005363 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005364 // "double _Complex" is promoted to "long double _Complex".
5365 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005366
5367 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005368 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005369 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005370 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005371 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005372 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5373 // domains match. This is a requirement for our implementation, C99
5374 // does not require this promotion.
5375 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5376 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5377 return rhs;
5378 } else { // handle "_Complex double, double".
5379 return lhs;
5380 }
5381 }
5382 return lhs; // The domain/size match exactly.
5383 }
5384 // Now handle "real" floating types (i.e. float, double, long double).
5385 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5386 // if we have an integer operand, the result is the real floating type.
5387 if (rhs->isIntegerType()) {
5388 // convert rhs to the lhs floating point type.
5389 return lhs;
5390 }
5391 if (rhs->isComplexIntegerType()) {
5392 // convert rhs to the complex floating point type.
5393 return getComplexType(lhs);
5394 }
5395 if (lhs->isIntegerType()) {
5396 // convert lhs to the rhs floating point type.
5397 return rhs;
5398 }
Mike Stump11289f42009-09-09 15:08:12 +00005399 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005400 // convert lhs to the complex floating point type.
5401 return getComplexType(rhs);
5402 }
5403 // We have two real floating types, float/complex combos were handled above.
5404 // Convert the smaller operand to the bigger result.
5405 int result = getFloatingTypeOrder(lhs, rhs);
5406 if (result > 0) // convert the rhs
5407 return lhs;
5408 assert(result < 0 && "illegal float comparison");
5409 return rhs; // convert the lhs
5410 }
5411 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5412 // Handle GCC complex int extension.
5413 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5414 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5415
5416 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005417 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005418 rhsComplexInt->getElementType()) >= 0)
5419 return lhs; // convert the rhs
5420 return rhs;
5421 } else if (lhsComplexInt && rhs->isIntegerType()) {
5422 // convert the rhs to the lhs complex type.
5423 return lhs;
5424 } else if (rhsComplexInt && lhs->isIntegerType()) {
5425 // convert the lhs to the rhs complex type.
5426 return rhs;
5427 }
5428 }
5429 // Finally, we have two differing integer types.
5430 // The rules for this case are in C99 6.3.1.8
5431 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005432 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5433 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005434 QualType destType;
5435 if (lhsSigned == rhsSigned) {
5436 // Same signedness; use the higher-ranked type
5437 destType = compare >= 0 ? lhs : rhs;
5438 } else if (compare != (lhsSigned ? 1 : -1)) {
5439 // The unsigned type has greater than or equal rank to the
5440 // signed type, so use the unsigned type
5441 destType = lhsSigned ? rhs : lhs;
5442 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5443 // The two types are different widths; if we are here, that
5444 // means the signed type is larger than the unsigned type, so
5445 // use the signed type.
5446 destType = lhsSigned ? lhs : rhs;
5447 } else {
5448 // The signed type is higher-ranked than the unsigned type,
5449 // but isn't actually any bigger (like unsigned int and long
5450 // on most 32-bit systems). Use the unsigned type corresponding
5451 // to the signed type.
5452 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5453 }
5454 return destType;
5455}
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005456
5457GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5458 GVALinkage External = GVA_StrongExternal;
5459
5460 Linkage L = FD->getLinkage();
5461 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5462 FD->getType()->getLinkage() == UniqueExternalLinkage)
5463 L = UniqueExternalLinkage;
5464
5465 switch (L) {
5466 case NoLinkage:
5467 case InternalLinkage:
5468 case UniqueExternalLinkage:
5469 return GVA_Internal;
5470
5471 case ExternalLinkage:
5472 switch (FD->getTemplateSpecializationKind()) {
5473 case TSK_Undeclared:
5474 case TSK_ExplicitSpecialization:
5475 External = GVA_StrongExternal;
5476 break;
5477
5478 case TSK_ExplicitInstantiationDefinition:
5479 return GVA_ExplicitTemplateInstantiation;
5480
5481 case TSK_ExplicitInstantiationDeclaration:
5482 case TSK_ImplicitInstantiation:
5483 External = GVA_TemplateInstantiation;
5484 break;
5485 }
5486 }
5487
5488 if (!FD->isInlined())
5489 return External;
5490
5491 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5492 // GNU or C99 inline semantics. Determine whether this symbol should be
5493 // externally visible.
5494 if (FD->isInlineDefinitionExternallyVisible())
5495 return External;
5496
5497 // C99 inline semantics, where the symbol is not externally visible.
5498 return GVA_C99Inline;
5499 }
5500
5501 // C++0x [temp.explicit]p9:
5502 // [ Note: The intent is that an inline function that is the subject of
5503 // an explicit instantiation declaration will still be implicitly
5504 // instantiated when used so that the body can be considered for
5505 // inlining, but that no out-of-line copy of the inline function would be
5506 // generated in the translation unit. -- end note ]
5507 if (FD->getTemplateSpecializationKind()
5508 == TSK_ExplicitInstantiationDeclaration)
5509 return GVA_C99Inline;
5510
5511 return GVA_CXXInline;
5512}
5513
5514GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5515 // If this is a static data member, compute the kind of template
5516 // specialization. Otherwise, this variable is not part of a
5517 // template.
5518 TemplateSpecializationKind TSK = TSK_Undeclared;
5519 if (VD->isStaticDataMember())
5520 TSK = VD->getTemplateSpecializationKind();
5521
5522 Linkage L = VD->getLinkage();
5523 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5524 VD->getType()->getLinkage() == UniqueExternalLinkage)
5525 L = UniqueExternalLinkage;
5526
5527 switch (L) {
5528 case NoLinkage:
5529 case InternalLinkage:
5530 case UniqueExternalLinkage:
5531 return GVA_Internal;
5532
5533 case ExternalLinkage:
5534 switch (TSK) {
5535 case TSK_Undeclared:
5536 case TSK_ExplicitSpecialization:
5537 return GVA_StrongExternal;
5538
5539 case TSK_ExplicitInstantiationDeclaration:
5540 llvm_unreachable("Variable should not be instantiated");
5541 // Fall through to treat this like any other instantiation.
5542
5543 case TSK_ExplicitInstantiationDefinition:
5544 return GVA_ExplicitTemplateInstantiation;
5545
5546 case TSK_ImplicitInstantiation:
5547 return GVA_TemplateInstantiation;
5548 }
5549 }
5550
5551 return GVA_StrongExternal;
5552}
5553
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005554bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005555 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5556 if (!VD->isFileVarDecl())
5557 return false;
5558 } else if (!isa<FunctionDecl>(D))
5559 return false;
5560
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005561 // Weak references don't produce any output by themselves.
5562 if (D->hasAttr<WeakRefAttr>())
5563 return false;
5564
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005565 // Aliases and used decls are required.
5566 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5567 return true;
5568
5569 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5570 // Forward declarations aren't required.
5571 if (!FD->isThisDeclarationADefinition())
5572 return false;
5573
5574 // Constructors and destructors are required.
5575 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5576 return true;
5577
5578 // The key function for a class is required.
5579 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5580 const CXXRecordDecl *RD = MD->getParent();
5581 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5582 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5583 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5584 return true;
5585 }
5586 }
5587
5588 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5589
5590 // static, static inline, always_inline, and extern inline functions can
5591 // always be deferred. Normal inline functions can be deferred in C99/C++.
5592 // Implicit template instantiations can also be deferred in C++.
5593 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5594 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5595 return false;
5596 return true;
5597 }
5598
5599 const VarDecl *VD = cast<VarDecl>(D);
5600 assert(VD->isFileVarDecl() && "Expected file scoped var");
5601
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005602 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5603 return false;
5604
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005605 // Structs that have non-trivial constructors or destructors are required.
5606
5607 // FIXME: Handle references.
5608 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5609 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005610 if (RD->hasDefinition() &&
5611 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005612 return true;
5613 }
5614 }
5615
5616 GVALinkage L = GetGVALinkageForVariable(VD);
5617 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5618 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5619 return false;
5620 }
5621
5622 return true;
5623}
Charles Davis53c59df2010-08-16 03:33:14 +00005624
5625CXXABI::~CXXABI() {}