blob: 604cf2b5cfd6a7cf0d12598cca4c1317bdd9bb51 [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"
Anders Carlssona4267a62009-07-18 21:19:52 +000031
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Douglas Gregor7dbfb462010-06-16 21:09:37 +000038void
39ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
40 TemplateTemplateParmDecl *Parm) {
41 ID.AddInteger(Parm->getDepth());
42 ID.AddInteger(Parm->getPosition());
43 // FIXME: Parameter pack
44
45 TemplateParameterList *Params = Parm->getTemplateParameters();
46 ID.AddInteger(Params->size());
47 for (TemplateParameterList::const_iterator P = Params->begin(),
48 PEnd = Params->end();
49 P != PEnd; ++P) {
50 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
51 ID.AddInteger(0);
52 ID.AddBoolean(TTP->isParameterPack());
53 continue;
54 }
55
56 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
57 ID.AddInteger(1);
58 // FIXME: Parameter pack
59 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
60 continue;
61 }
62
63 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
64 ID.AddInteger(2);
65 Profile(ID, TTP);
66 }
67}
68
69TemplateTemplateParmDecl *
70ASTContext::getCanonicalTemplateTemplateParmDecl(
71 TemplateTemplateParmDecl *TTP) {
72 // Check if we already have a canonical template template parameter.
73 llvm::FoldingSetNodeID ID;
74 CanonicalTemplateTemplateParm::Profile(ID, TTP);
75 void *InsertPos = 0;
76 CanonicalTemplateTemplateParm *Canonical
77 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
78 if (Canonical)
79 return Canonical->getParam();
80
81 // Build a canonical template parameter list.
82 TemplateParameterList *Params = TTP->getTemplateParameters();
83 llvm::SmallVector<NamedDecl *, 4> CanonParams;
84 CanonParams.reserve(Params->size());
85 for (TemplateParameterList::const_iterator P = Params->begin(),
86 PEnd = Params->end();
87 P != PEnd; ++P) {
88 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
89 CanonParams.push_back(
90 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
91 SourceLocation(), TTP->getDepth(),
92 TTP->getIndex(), 0, false,
93 TTP->isParameterPack()));
94 else if (NonTypeTemplateParmDecl *NTTP
95 = dyn_cast<NonTypeTemplateParmDecl>(*P))
96 CanonParams.push_back(
97 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
98 SourceLocation(), NTTP->getDepth(),
99 NTTP->getPosition(), 0,
100 getCanonicalType(NTTP->getType()),
101 0));
102 else
103 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
104 cast<TemplateTemplateParmDecl>(*P)));
105 }
106
107 TemplateTemplateParmDecl *CanonTTP
108 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
109 SourceLocation(), TTP->getDepth(),
110 TTP->getPosition(), 0,
111 TemplateParameterList::Create(*this, SourceLocation(),
112 SourceLocation(),
113 CanonParams.data(),
114 CanonParams.size(),
115 SourceLocation()));
116
117 // Get the new insert position for the node we care about.
118 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
119 assert(Canonical == 0 && "Shouldn't be in the map!");
120 (void)Canonical;
121
122 // Create the canonical template template parameter entry.
123 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
124 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
125 return CanonTTP;
126}
127
Chris Lattner465fa322008-10-05 17:34:18 +0000128ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000129 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000130 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000131 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +0000132 bool FreeMem, unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000133 TemplateSpecializationTypes(this_()),
134 DependentTemplateSpecializationTypes(this_()),
Mike Stump11289f42009-09-09 15:08:12 +0000135 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +0000136 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000137 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000138 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000139 NullTypeSourceInfo(QualType()),
Douglas Gregor9507d462010-03-19 22:13:20 +0000140 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000141 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000142 BuiltinInfo(builtins),
143 DeclarationNames(*this),
144 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000145 LastSDM(0, 0),
146 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000147 ObjCIdRedefinitionType = QualType();
148 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000149 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000150 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000151 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000152 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000153}
154
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000155ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000156 // Release the DenseMaps associated with DeclContext objects.
157 // FIXME: Is this the ideal solution?
158 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000159
Douglas Gregor1a809332010-05-23 18:26:36 +0000160 if (!FreeMemory) {
161 // Call all of the deallocation functions.
162 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
163 Deallocations[I].first(Deallocations[I].second);
164 }
165
Douglas Gregor832940b2010-03-02 23:58:15 +0000166 // Release all of the memory associated with overridden C++ methods.
167 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
168 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
169 OM != OMEnd; ++OM)
170 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000171
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000172 if (FreeMemory) {
173 // Deallocate all the types.
174 while (!Types.empty()) {
175 Types.back()->Destroy(*this);
176 Types.pop_back();
177 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000178
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000179 for (llvm::FoldingSet<ExtQuals>::iterator
180 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
181 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +0000182 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +0000183 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000184
Ted Kremenekc3015a92010-03-08 20:56:29 +0000185 for (llvm::DenseMap<const ObjCContainerDecl*,
186 const ASTRecordLayout*>::iterator
187 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
188 // Increment in loop to prevent using deallocated memory.
189 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
190 R->Destroy(*this);
191 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000192 }
193
Ted Kremenek076baeb2010-06-08 23:00:58 +0000194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
195 // even when using the BumpPtrAllocator because they can contain
196 // DenseMaps.
197 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
198 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202 }
203
Douglas Gregorf21eb492009-03-26 23:50:42 +0000204 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000205 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
206 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000207 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000208 NNS != NNSEnd; ) {
209 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000210 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000211 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000212
213 if (GlobalNestedNameSpecifier)
214 GlobalNestedNameSpecifier->Destroy(*this);
215
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000216 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000217}
218
Douglas Gregor1a809332010-05-23 18:26:36 +0000219void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
220 Deallocations.push_back(std::make_pair(Callback, Data));
221}
222
Mike Stump11289f42009-09-09 15:08:12 +0000223void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000224ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
225 ExternalSource.reset(Source.take());
226}
227
Chris Lattner4eb445d2007-01-26 01:27:23 +0000228void ASTContext::PrintStats() const {
229 fprintf(stderr, "*** AST Context Stats:\n");
230 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000231
Douglas Gregora30d0462009-05-26 14:40:08 +0000232 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000233#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000234#define ABSTRACT_TYPE(Name, Parent)
235#include "clang/AST/TypeNodes.def"
236 0 // Extra
237 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000238
Chris Lattner4eb445d2007-01-26 01:27:23 +0000239 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
240 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000241 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000242 }
243
Douglas Gregora30d0462009-05-26 14:40:08 +0000244 unsigned Idx = 0;
245 unsigned TotalBytes = 0;
246#define TYPE(Name, Parent) \
247 if (counts[Idx]) \
248 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
249 TotalBytes += counts[Idx] * sizeof(Name##Type); \
250 ++Idx;
251#define ABSTRACT_TYPE(Name, Parent)
252#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000253
Douglas Gregora30d0462009-05-26 14:40:08 +0000254 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000255
256 if (ExternalSource.get()) {
257 fprintf(stderr, "\n");
258 ExternalSource->PrintStats();
259 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000260}
261
262
John McCall48f2d582009-10-23 23:03:21 +0000263void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000264 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000265 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000266 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000267}
268
Chris Lattner970e54e2006-11-12 00:37:36 +0000269void ASTContext::InitBuiltinTypes() {
270 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner970e54e2006-11-12 00:37:36 +0000272 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000273 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner970e54e2006-11-12 00:37:36 +0000275 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000276 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000277 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000278 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000279 InitBuiltinType(CharTy, BuiltinType::Char_S);
280 else
281 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000282 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000283 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
284 InitBuiltinType(ShortTy, BuiltinType::Short);
285 InitBuiltinType(IntTy, BuiltinType::Int);
286 InitBuiltinType(LongTy, BuiltinType::Long);
287 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
291 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
292 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
293 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
294 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner970e54e2006-11-12 00:37:36 +0000296 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000297 InitBuiltinType(FloatTy, BuiltinType::Float);
298 InitBuiltinType(DoubleTy, BuiltinType::Double);
299 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000300
Chris Lattnerf122cef2009-04-30 02:43:43 +0000301 // GNU extension, 128-bit integers.
302 InitBuiltinType(Int128Ty, BuiltinType::Int128);
303 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
304
Chris Lattner007cb022009-02-26 23:43:47 +0000305 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
306 InitBuiltinType(WCharTy, BuiltinType::WChar);
307 else // C99
308 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000309
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000310 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
311 InitBuiltinType(Char16Ty, BuiltinType::Char16);
312 else // C99
313 Char16Ty = getFromTargetType(Target.getChar16Type());
314
315 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
316 InitBuiltinType(Char32Ty, BuiltinType::Char32);
317 else // C99
318 Char32Ty = getFromTargetType(Target.getChar32Type());
319
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000320 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000321 InitBuiltinType(OverloadTy, BuiltinType::Overload);
322
323 // Placeholder type for type-dependent expressions whose type is
324 // completely unknown. No code should ever check a type against
325 // DependentTy and users should never see it; however, it is here to
326 // help diagnose failures to properly check for type-dependent
327 // expressions.
328 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329
Mike Stump11289f42009-09-09 15:08:12 +0000330 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000331 // not yet been deduced.
332 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000333
Chris Lattner970e54e2006-11-12 00:37:36 +0000334 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000335 FloatComplexTy = getComplexType(FloatTy);
336 DoubleComplexTy = getComplexType(DoubleTy);
337 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000338
Steve Naroff66e9f332007-10-15 14:41:52 +0000339 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000340
Steve Naroff1329fa02009-07-15 18:40:39 +0000341 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
342 ObjCIdTypedefType = QualType();
343 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000344 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000345
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000346 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000347 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
348 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000349 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000350
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000351 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000353 // void * type
354 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000355
356 // nullptr type (C++0x 2.14.7)
357 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000358}
359
Douglas Gregor86d142a2009-10-08 07:24:58 +0000360MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000361ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000362 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000363 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000364 = InstantiatedFromStaticDataMember.find(Var);
365 if (Pos == InstantiatedFromStaticDataMember.end())
366 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000368 return Pos->second;
369}
370
Mike Stump11289f42009-09-09 15:08:12 +0000371void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000372ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
373 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000374 assert(Inst->isStaticDataMember() && "Not a static data member");
375 assert(Tmpl->isStaticDataMember() && "Not a static data member");
376 assert(!InstantiatedFromStaticDataMember[Inst] &&
377 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000378 InstantiatedFromStaticDataMember[Inst]
379 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000380}
381
John McCalle61f2ba2009-11-18 02:36:19 +0000382NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000383ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000384 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000385 = InstantiatedFromUsingDecl.find(UUD);
386 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000387 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000389 return Pos->second;
390}
391
392void
John McCallb96ec562009-12-04 22:46:56 +0000393ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
394 assert((isa<UsingDecl>(Pattern) ||
395 isa<UnresolvedUsingValueDecl>(Pattern) ||
396 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
397 "pattern decl is not a using decl");
398 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
399 InstantiatedFromUsingDecl[Inst] = Pattern;
400}
401
402UsingShadowDecl *
403ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
404 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
405 = InstantiatedFromUsingShadowDecl.find(Inst);
406 if (Pos == InstantiatedFromUsingShadowDecl.end())
407 return 0;
408
409 return Pos->second;
410}
411
412void
413ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
414 UsingShadowDecl *Pattern) {
415 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
416 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000417}
418
Anders Carlsson5da84842009-09-01 04:26:58 +0000419FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
420 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
421 = InstantiatedFromUnnamedFieldDecl.find(Field);
422 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
423 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Anders Carlsson5da84842009-09-01 04:26:58 +0000425 return Pos->second;
426}
427
428void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
429 FieldDecl *Tmpl) {
430 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
431 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
432 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
433 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000434
Anders Carlsson5da84842009-09-01 04:26:58 +0000435 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
436}
437
Douglas Gregor832940b2010-03-02 23:58:15 +0000438ASTContext::overridden_cxx_method_iterator
439ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
440 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
441 = OverriddenMethods.find(Method);
442 if (Pos == OverriddenMethods.end())
443 return 0;
444
445 return Pos->second.begin();
446}
447
448ASTContext::overridden_cxx_method_iterator
449ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
450 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
451 = OverriddenMethods.find(Method);
452 if (Pos == OverriddenMethods.end())
453 return 0;
454
455 return Pos->second.end();
456}
457
458void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
459 const CXXMethodDecl *Overridden) {
460 OverriddenMethods[Method].push_back(Overridden);
461}
462
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000463namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000464 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000465 : std::binary_function<SourceRange, SourceRange, bool> {
466 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 public:
469 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000471 bool operator()(SourceRange X, SourceRange Y) {
472 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
473 }
474 };
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
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000502 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000503 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000504
Chris Lattner68061312009-01-24 21:53:27 +0000505 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
506 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000507 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000508 if (RefAsPointee)
509 T = RT->getPointeeType();
510 else
511 T = getPointerType(RT->getPointeeType());
512 }
513 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000514 unsigned MinWidth = Target.getLargeArrayMinWidth();
515 unsigned ArrayAlign = Target.getLargeArrayAlign();
516 if (isa<VariableArrayType>(T) && MinWidth != 0)
517 Align = std::max(Align, ArrayAlign);
518 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
519 unsigned Size = getTypeSize(CT);
520 if (MinWidth != 0 && MinWidth <= Size)
521 Align = std::max(Align, ArrayAlign);
522 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000523 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000524 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
525 T = cast<ArrayType>(T)->getElementType();
526
527 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
528 }
Charles Davis3fc51072010-02-23 04:52:00 +0000529 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
530 // In the case of a field in a packed struct, we want the minimum
531 // of the alignment of the field and the alignment of the struct.
532 Align = std::min(Align,
533 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
534 }
Chris Lattner68061312009-01-24 21:53:27 +0000535 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000536
Ken Dyck160146e2010-01-27 17:10:57 +0000537 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000538}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000539
John McCall87fe5d52010-05-20 01:18:31 +0000540std::pair<CharUnits, CharUnits>
541ASTContext::getTypeInfoInChars(const Type *T) {
542 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
543 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
544 CharUnits::fromQuantity(Info.second / getCharWidth()));
545}
546
547std::pair<CharUnits, CharUnits>
548ASTContext::getTypeInfoInChars(QualType T) {
549 return getTypeInfoInChars(T.getTypePtr());
550}
551
Chris Lattner983a8bb2007-07-13 22:13:22 +0000552/// getTypeSize - Return the size of the specified type, in bits. This method
553/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000554///
555/// FIXME: Pointers into different addr spaces could have different sizes and
556/// alignment requirements: getPointerInfo should take an AddrSpace, this
557/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000558std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000559ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000560 uint64_t Width=0;
561 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000562 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000563#define TYPE(Class, Base)
564#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000565#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000566#define DEPENDENT_TYPE(Class, Base) case Type::Class:
567#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000568 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000569 break;
570
Chris Lattner355332d2007-07-13 22:27:08 +0000571 case Type::FunctionNoProto:
572 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000573 // GCC extension: alignof(function) = 32 bits
574 Width = 0;
575 Align = 32;
576 break;
577
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000578 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000579 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000580 Width = 0;
581 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
582 break;
583
Steve Naroff5c131802007-08-30 01:06:46 +0000584 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000585 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner37e05872008-03-05 18:54:05 +0000587 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000588 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000589 Align = EltInfo.second;
590 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000591 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000592 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000593 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000594 const VectorType *VT = cast<VectorType>(T);
595 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
596 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000597 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000598 // If the alignment is not a power of 2, round up to the next power of 2.
599 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000600 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000601 Align = llvm::NextPowerOf2(Align);
602 Width = llvm::RoundUpToAlignment(Width, Align);
603 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000604 break;
605 }
Chris Lattner647fb222007-07-18 18:26:58 +0000606
Chris Lattner7570e9c2008-03-08 08:52:55 +0000607 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000608 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000609 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000610 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000611 // GCC extension: alignof(void) = 8 bits.
612 Width = 0;
613 Align = 8;
614 break;
615
Chris Lattner6a4f7452007-12-19 19:23:28 +0000616 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000617 Width = Target.getBoolWidth();
618 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000619 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000620 case BuiltinType::Char_S:
621 case BuiltinType::Char_U:
622 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000623 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000624 Width = Target.getCharWidth();
625 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000626 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000627 case BuiltinType::WChar:
628 Width = Target.getWCharWidth();
629 Align = Target.getWCharAlign();
630 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000631 case BuiltinType::Char16:
632 Width = Target.getChar16Width();
633 Align = Target.getChar16Align();
634 break;
635 case BuiltinType::Char32:
636 Width = Target.getChar32Width();
637 Align = Target.getChar32Align();
638 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000639 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000640 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000641 Width = Target.getShortWidth();
642 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000643 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000644 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000645 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = Target.getIntWidth();
647 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000649 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000650 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000651 Width = Target.getLongWidth();
652 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000653 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000654 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000655 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000656 Width = Target.getLongLongWidth();
657 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000659 case BuiltinType::Int128:
660 case BuiltinType::UInt128:
661 Width = 128;
662 Align = 128; // int128_t is 128-bit aligned on all targets.
663 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000664 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 Width = Target.getFloatWidth();
666 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 break;
668 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000669 Width = Target.getDoubleWidth();
670 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000671 break;
672 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000673 Width = Target.getLongDoubleWidth();
674 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000675 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000676 case BuiltinType::NullPtr:
677 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
678 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000679 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000680 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000681 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000682 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000683 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000684 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000685 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000686 case Type::BlockPointer: {
687 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
688 Width = Target.getPointerWidth(AS);
689 Align = Target.getPointerAlign(AS);
690 break;
691 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000692 case Type::LValueReference:
693 case Type::RValueReference: {
694 // alignof and sizeof should never enter this code path here, so we go
695 // the pointer route.
696 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
697 Width = Target.getPointerWidth(AS);
698 Align = Target.getPointerAlign(AS);
699 break;
700 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000701 case Type::Pointer: {
702 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000703 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000707 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000708 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000709 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000710 getTypeInfo(getPointerDiffType());
711 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000712 if (Pointee->isFunctionType())
713 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000714 Align = PtrDiffInfo.second;
715 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000716 }
Chris Lattner647fb222007-07-18 18:26:58 +0000717 case Type::Complex: {
718 // Complex types have the same alignment as their elements, but twice the
719 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000720 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000721 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000723 Align = EltInfo.second;
724 break;
725 }
John McCall8b07ec22010-05-15 11:32:37 +0000726 case Type::ObjCObject:
727 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000728 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000729 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000730 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
731 Width = Layout.getSize();
732 Align = Layout.getAlignment();
733 break;
734 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000735 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000736 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000737 const TagType *TT = cast<TagType>(T);
738
739 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000740 Width = 1;
741 Align = 1;
742 break;
743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000745 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000746 return getTypeInfo(ET->getDecl()->getIntegerType());
747
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000748 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000749 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
750 Width = Layout.getSize();
751 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000752 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000753 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000754
Chris Lattner63d2b362009-10-22 05:17:15 +0000755 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000756 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
757 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000758
Douglas Gregoref462e62009-04-30 17:32:17 +0000759 case Type::Typedef: {
760 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000761 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000762 Align = std::max(Aligned->getMaxAlignment(),
763 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000764 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
765 } else
766 return getTypeInfo(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
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000832static void CollectLocalObjCIvars(ASTContext *Ctx,
833 const ObjCInterfaceDecl *OI,
834 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000835 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000837 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000838 if (!IVDecl->isInvalidDecl())
839 Fields.push_back(cast<FieldDecl>(IVDecl));
840 }
841}
842
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000843void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
844 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
845 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
846 CollectObjCIvars(SuperClass, Fields);
847 CollectLocalObjCIvars(this, OI, Fields);
848}
849
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000850/// ShallowCollectObjCIvars -
851/// Collect all ivars, including those synthesized, in the current class.
852///
853void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000854 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000855 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
856 E = OI->ivar_end(); I != E; ++I) {
857 Ivars.push_back(*I);
858 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000859
860 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000861}
862
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000863/// CollectNonClassIvars -
864/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000865/// This includes synthesized ivars (via @synthesize) and those in
866// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000867///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000868void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000869 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000870 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000871 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
872 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000873 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
874 E = CDecl->ivar_end(); I != E; ++I) {
875 Ivars.push_back(*I);
876 }
877 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000878
Ted Kremenek86838aa2010-03-11 19:44:54 +0000879 // Also add any ivar defined in this class's implementation. This
880 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000881 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
882 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
883 E = ImplDecl->ivar_end(); I != E; ++I)
884 Ivars.push_back(*I);
885 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000886}
887
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000888/// CollectInheritedProtocols - Collect all protocols in current class and
889/// those inherited by it.
890void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000891 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000892 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
893 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
894 PE = OI->protocol_end(); P != PE; ++P) {
895 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000896 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000897 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000898 PE = Proto->protocol_end(); P != PE; ++P) {
899 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000900 CollectInheritedProtocols(*P, Protocols);
901 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000902 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000903
904 // Categories of this Interface.
905 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
906 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
907 CollectInheritedProtocols(CDeclChain, Protocols);
908 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
909 while (SD) {
910 CollectInheritedProtocols(SD, Protocols);
911 SD = SD->getSuperClass();
912 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000913 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000914 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
915 PE = OC->protocol_end(); P != PE; ++P) {
916 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000917 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000918 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
919 PE = Proto->protocol_end(); P != PE; ++P)
920 CollectInheritedProtocols(*P, Protocols);
921 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000922 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000923 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
924 PE = OP->protocol_end(); P != PE; ++P) {
925 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000926 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000927 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
928 PE = Proto->protocol_end(); P != PE; ++P)
929 CollectInheritedProtocols(*P, Protocols);
930 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000931 }
932}
933
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000934unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
935 unsigned count = 0;
936 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000937 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
938 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000939 count += CDecl->ivar_size();
940
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000941 // Count ivar defined in this class's implementation. This
942 // includes synthesized ivars.
943 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000944 count += ImplDecl->ivar_size();
945
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000946 return count;
947}
948
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000949/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
950ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
951 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
952 I = ObjCImpls.find(D);
953 if (I != ObjCImpls.end())
954 return cast<ObjCImplementationDecl>(I->second);
955 return 0;
956}
957/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
958ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
959 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
960 I = ObjCImpls.find(D);
961 if (I != ObjCImpls.end())
962 return cast<ObjCCategoryImplDecl>(I->second);
963 return 0;
964}
965
966/// \brief Set the implementation of ObjCInterfaceDecl.
967void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
968 ObjCImplementationDecl *ImplD) {
969 assert(IFaceD && ImplD && "Passed null params");
970 ObjCImpls[IFaceD] = ImplD;
971}
972/// \brief Set the implementation of ObjCCategoryDecl.
973void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
974 ObjCCategoryImplDecl *ImplD) {
975 assert(CatD && ImplD && "Passed null params");
976 ObjCImpls[CatD] = ImplD;
977}
978
John McCallbcd03502009-12-07 02:54:59 +0000979/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000980///
John McCallbcd03502009-12-07 02:54:59 +0000981/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000982/// the TypeLoc wrappers.
983///
984/// \param T the type that will be the basis for type source info. This type
985/// should refer to how the declarator was written in source code, not to
986/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000987TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000988 unsigned DataSize) {
989 if (!DataSize)
990 DataSize = TypeLoc::getFullDataSizeForType(T);
991 else
992 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000993 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000994
John McCallbcd03502009-12-07 02:54:59 +0000995 TypeSourceInfo *TInfo =
996 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
997 new (TInfo) TypeSourceInfo(T);
998 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000999}
1000
John McCallbcd03502009-12-07 02:54:59 +00001001TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001002 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001003 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001004 DI->getTypeLoc().initialize(L);
1005 return DI;
1006}
1007
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001008const ASTRecordLayout &
1009ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1010 return getObjCLayout(D, 0);
1011}
1012
1013const ASTRecordLayout &
1014ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1015 return getObjCLayout(D->getClassInterface(), D);
1016}
1017
Chris Lattner983a8bb2007-07-13 22:13:22 +00001018//===----------------------------------------------------------------------===//
1019// Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
John McCall8ccfcb52009-09-24 19:53:00 +00001022QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1023 unsigned Fast = Quals.getFastQualifiers();
1024 Quals.removeFastQualifiers();
1025
1026 // Check if we've already instantiated this type.
1027 llvm::FoldingSetNodeID ID;
1028 ExtQuals::Profile(ID, TypeNode, Quals);
1029 void *InsertPos = 0;
1030 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1031 assert(EQ->getQualifiers() == Quals);
1032 QualType T = QualType(EQ, Fast);
1033 return T;
1034 }
1035
John McCall90d1c2d2009-09-24 23:30:46 +00001036 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001037 ExtQualNodes.InsertNode(New, InsertPos);
1038 QualType T = QualType(New, Fast);
1039 return T;
1040}
1041
1042QualType ASTContext::getVolatileType(QualType T) {
1043 QualType CanT = getCanonicalType(T);
1044 if (CanT.isVolatileQualified()) return T;
1045
1046 QualifierCollector Quals;
1047 const Type *TypeNode = Quals.strip(T);
1048 Quals.addVolatile();
1049
1050 return getExtQualType(TypeNode, Quals);
1051}
1052
Fariborz Jahanianece85822009-02-17 18:27:45 +00001053QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001054 QualType CanT = getCanonicalType(T);
1055 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001056 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001057
John McCall8ccfcb52009-09-24 19:53:00 +00001058 // If we are composing extended qualifiers together, merge together
1059 // into one ExtQuals node.
1060 QualifierCollector Quals;
1061 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCall8ccfcb52009-09-24 19:53:00 +00001063 // If this type already has an address space specified, it cannot get
1064 // another one.
1065 assert(!Quals.hasAddressSpace() &&
1066 "Type cannot be in multiple addr spaces!");
1067 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001068
John McCall8ccfcb52009-09-24 19:53:00 +00001069 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001070}
1071
Chris Lattnerd60183d2009-02-18 22:53:11 +00001072QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001073 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001074 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001075 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001076 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001077
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001078 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001079 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001080 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001081 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1082 return getPointerType(ResultType);
1083 }
1084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCall8ccfcb52009-09-24 19:53:00 +00001086 // If we are composing extended qualifiers together, merge together
1087 // into one ExtQuals node.
1088 QualifierCollector Quals;
1089 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001090
John McCall8ccfcb52009-09-24 19:53:00 +00001091 // If this type already has an ObjCGC specified, it cannot get
1092 // another one.
1093 assert(!Quals.hasObjCGCAttr() &&
1094 "Type cannot have multiple ObjCGCs!");
1095 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001096
John McCall8ccfcb52009-09-24 19:53:00 +00001097 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001098}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001099
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001100static QualType getExtFunctionType(ASTContext& Context, QualType T,
1101 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001102 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001103 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1104 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001105 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001106 if (ResultType == Pointee)
1107 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001108
1109 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001110 } else if (const BlockPointerType *BlockPointer
1111 = T->getAs<BlockPointerType>()) {
1112 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001113 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001114 if (ResultType == Pointee)
1115 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001116
1117 ResultType = Context.getBlockPointerType(ResultType);
1118 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001119 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001120 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001121
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001122 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001123 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001124 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001125 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001126 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001127 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001128 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1129 FPT->getNumArgs(), FPT->isVariadic(),
1130 FPT->getTypeQuals(),
1131 FPT->hasExceptionSpec(),
1132 FPT->hasAnyExceptionSpec(),
1133 FPT->getNumExceptions(),
1134 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001135 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001136 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001137 } else
1138 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001139
1140 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1141}
1142
1143QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001144 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001145 return getExtFunctionType(*this, T,
1146 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001147}
1148
1149QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001150 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001151 return getExtFunctionType(*this, T,
1152 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001153}
1154
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001155QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1156 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1157 return getExtFunctionType(*this, T,
1158 Info.withRegParm(RegParm));
1159}
1160
Chris Lattnerc6395932007-06-22 20:56:16 +00001161/// getComplexType - Return the uniqued reference to the type for a complex
1162/// number with the specified element type.
1163QualType ASTContext::getComplexType(QualType T) {
1164 // Unique pointers, to guarantee there is only one pointer of a particular
1165 // structure.
1166 llvm::FoldingSetNodeID ID;
1167 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerc6395932007-06-22 20:56:16 +00001169 void *InsertPos = 0;
1170 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1171 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattnerc6395932007-06-22 20:56:16 +00001173 // If the pointee type isn't canonical, this won't be a canonical type either,
1174 // so fill in the canonical type field.
1175 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001176 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001177 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattnerc6395932007-06-22 20:56:16 +00001179 // Get the new insert position for the node we care about.
1180 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001181 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001182 }
John McCall90d1c2d2009-09-24 23:30:46 +00001183 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001184 Types.push_back(New);
1185 ComplexTypes.InsertNode(New, InsertPos);
1186 return QualType(New, 0);
1187}
1188
Chris Lattner970e54e2006-11-12 00:37:36 +00001189/// getPointerType - Return the uniqued reference to the type for a pointer to
1190/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001191QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001192 // Unique pointers, to guarantee there is only one pointer of a particular
1193 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001194 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001195 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner67521df2007-01-27 01:29:36 +00001197 void *InsertPos = 0;
1198 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001199 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattner7ccecb92006-11-12 08:50:50 +00001201 // If the pointee type isn't canonical, this won't be a canonical type either,
1202 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001203 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001204 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001205 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattner67521df2007-01-27 01:29:36 +00001207 // Get the new insert position for the node we care about.
1208 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001209 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001210 }
John McCall90d1c2d2009-09-24 23:30:46 +00001211 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001212 Types.push_back(New);
1213 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001214 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001215}
1216
Mike Stump11289f42009-09-09 15:08:12 +00001217/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001218/// a pointer to the specified block.
1219QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001220 assert(T->isFunctionType() && "block of function types only");
1221 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001222 // structure.
1223 llvm::FoldingSetNodeID ID;
1224 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001225
Steve Naroffec33ed92008-08-27 16:04:49 +00001226 void *InsertPos = 0;
1227 if (BlockPointerType *PT =
1228 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1229 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001230
1231 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001232 // type either so fill in the canonical type field.
1233 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001234 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001235 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001236
Steve Naroffec33ed92008-08-27 16:04:49 +00001237 // Get the new insert position for the node we care about.
1238 BlockPointerType *NewIP =
1239 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001240 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001241 }
John McCall90d1c2d2009-09-24 23:30:46 +00001242 BlockPointerType *New
1243 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 Types.push_back(New);
1245 BlockPointerTypes.InsertNode(New, InsertPos);
1246 return QualType(New, 0);
1247}
1248
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001249/// getLValueReferenceType - Return the uniqued reference to the type for an
1250/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001251QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001252 // Unique pointers, to guarantee there is only one pointer of a particular
1253 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001254 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001255 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001256
1257 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001258 if (LValueReferenceType *RT =
1259 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001260 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001261
John McCallfc93cf92009-10-22 22:37:11 +00001262 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1263
Bill Wendling3708c182007-05-27 10:15:43 +00001264 // If the referencee type isn't canonical, this won't be a canonical type
1265 // either, so fill in the canonical type field.
1266 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001267 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1268 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1269 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270
Bill Wendling3708c182007-05-27 10:15:43 +00001271 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001272 LValueReferenceType *NewIP =
1273 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001274 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001275 }
1276
John McCall90d1c2d2009-09-24 23:30:46 +00001277 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001278 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1279 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001280 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001281 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001282
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001283 return QualType(New, 0);
1284}
1285
1286/// getRValueReferenceType - Return the uniqued reference to the type for an
1287/// rvalue reference to the specified type.
1288QualType ASTContext::getRValueReferenceType(QualType T) {
1289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001292 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001293
1294 void *InsertPos = 0;
1295 if (RValueReferenceType *RT =
1296 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1297 return QualType(RT, 0);
1298
John McCallfc93cf92009-10-22 22:37:11 +00001299 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1300
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001301 // If the referencee type isn't canonical, this won't be a canonical type
1302 // either, so fill in the canonical type field.
1303 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001304 if (InnerRef || !T.isCanonical()) {
1305 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1306 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001307
1308 // Get the new insert position for the node we care about.
1309 RValueReferenceType *NewIP =
1310 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1311 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1312 }
1313
John McCall90d1c2d2009-09-24 23:30:46 +00001314 RValueReferenceType *New
1315 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001316 Types.push_back(New);
1317 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001318 return QualType(New, 0);
1319}
1320
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001321/// getMemberPointerType - Return the uniqued reference to the type for a
1322/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001323QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001324 // Unique pointers, to guarantee there is only one pointer of a particular
1325 // structure.
1326 llvm::FoldingSetNodeID ID;
1327 MemberPointerType::Profile(ID, T, Cls);
1328
1329 void *InsertPos = 0;
1330 if (MemberPointerType *PT =
1331 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1332 return QualType(PT, 0);
1333
1334 // If the pointee or class type isn't canonical, this won't be a canonical
1335 // type either, so fill in the canonical type field.
1336 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001337 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1339
1340 // Get the new insert position for the node we care about.
1341 MemberPointerType *NewIP =
1342 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1343 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1344 }
John McCall90d1c2d2009-09-24 23:30:46 +00001345 MemberPointerType *New
1346 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001347 Types.push_back(New);
1348 MemberPointerTypes.InsertNode(New, InsertPos);
1349 return QualType(New, 0);
1350}
1351
Mike Stump11289f42009-09-09 15:08:12 +00001352/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001353/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001354QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001355 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001356 ArrayType::ArraySizeModifier ASM,
1357 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001358 assert((EltTy->isDependentType() ||
1359 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001360 "Constant array of VLAs is illegal!");
1361
Chris Lattnere2df3f92009-05-13 04:12:56 +00001362 // Convert the array size into a canonical width matching the pointer size for
1363 // the target.
1364 llvm::APInt ArySize(ArySizeIn);
1365 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattner23b7eb62007-06-15 23:05:46 +00001367 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001368 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattner36f8e652007-01-27 08:31:04 +00001370 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001371 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001372 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001373 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner7ccecb92006-11-12 08:50:50 +00001375 // If the element type isn't canonical, this won't be a canonical type either,
1376 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001377 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001378 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001379 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001380 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001381 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001382 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001383 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001384 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCall90d1c2d2009-09-24 23:30:46 +00001387 ConstantArrayType *New = new(*this,TypeAlignment)
1388 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001389 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001390 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001392}
1393
Steve Naroffcadebd02007-08-30 18:14:25 +00001394/// getVariableArrayType - Returns a non-unique reference to the type for a
1395/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001396QualType ASTContext::getVariableArrayType(QualType EltTy,
1397 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001398 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001399 unsigned EltTypeQuals,
1400 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001401 // Since we don't unique expressions, it isn't possible to unique VLA's
1402 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001403 QualType CanonType;
1404
1405 if (!EltTy.isCanonical()) {
1406 if (NumElts)
1407 NumElts->Retain();
1408 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1409 EltTypeQuals, Brackets);
1410 }
1411
John McCall90d1c2d2009-09-24 23:30:46 +00001412 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001413 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001414
1415 VariableArrayTypes.push_back(New);
1416 Types.push_back(New);
1417 return QualType(New, 0);
1418}
1419
Douglas Gregor4619e432008-12-05 23:32:09 +00001420/// getDependentSizedArrayType - Returns a non-unique reference to
1421/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001422/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001423QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1424 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001425 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001426 unsigned EltTypeQuals,
1427 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001428 assert((!NumElts || NumElts->isTypeDependent() ||
1429 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001430 "Size must be type- or value-dependent!");
1431
Douglas Gregorf3f95522009-07-31 00:23:35 +00001432 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001433 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001434 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001435
1436 if (NumElts) {
1437 // Dependently-sized array types that do not have a specified
1438 // number of elements will have their sizes deduced from an
1439 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001440 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1441 EltTypeQuals, NumElts);
1442
1443 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1444 }
1445
Douglas Gregorf3f95522009-07-31 00:23:35 +00001446 DependentSizedArrayType *New;
1447 if (Canon) {
1448 // We already have a canonical version of this array type; use it as
1449 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001450 New = new (*this, TypeAlignment)
1451 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1452 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001453 } else {
1454 QualType CanonEltTy = getCanonicalType(EltTy);
1455 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001456 New = new (*this, TypeAlignment)
1457 DependentSizedArrayType(*this, EltTy, QualType(),
1458 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001459
Douglas Gregorc42075a2010-02-04 18:10:26 +00001460 if (NumElts) {
1461 DependentSizedArrayType *CanonCheck
1462 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1463 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1464 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001465 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001466 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001467 } else {
1468 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1469 ASM, EltTypeQuals,
1470 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001471 New = new (*this, TypeAlignment)
1472 DependentSizedArrayType(*this, EltTy, Canon,
1473 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001474 }
1475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Douglas Gregor4619e432008-12-05 23:32:09 +00001477 Types.push_back(New);
1478 return QualType(New, 0);
1479}
1480
Eli Friedmanbd258282008-02-15 18:16:39 +00001481QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1482 ArrayType::ArraySizeModifier ASM,
1483 unsigned EltTypeQuals) {
1484 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001485 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001486
1487 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001489 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(ATP, 0);
1491
1492 // If the element type isn't canonical, this won't be a canonical type
1493 // either, so fill in the canonical type field.
1494 QualType Canonical;
1495
John McCallb692a092009-10-22 20:10:53 +00001496 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001497 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001498 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001499
1500 // Get the new insert position for the node we care about.
1501 IncompleteArrayType *NewIP =
1502 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001504 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001505
John McCall90d1c2d2009-09-24 23:30:46 +00001506 IncompleteArrayType *New = new (*this, TypeAlignment)
1507 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001508
1509 IncompleteArrayTypes.InsertNode(New, InsertPos);
1510 Types.push_back(New);
1511 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001512}
1513
Steve Naroff91fcddb2007-07-18 18:00:27 +00001514/// getVectorType - Return the unique reference to a vector type of
1515/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001516QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001517 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001518 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattner76a00cf2008-04-06 22:59:24 +00001520 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001521 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001522
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001523 // Check if we've already instantiated a vector of this type.
1524 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001525 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1526
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001527 void *InsertPos = 0;
1528 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1529 return QualType(VTP, 0);
1530
1531 // If the element type isn't canonical, this won't be a canonical type either,
1532 // so fill in the canonical type field.
1533 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001534 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1535 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1536 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1537 // the equivalent GCC vector types
1538 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1539 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001541 // Get the new insert position for the node we care about.
1542 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001543 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001544 }
John McCall90d1c2d2009-09-24 23:30:46 +00001545 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001546 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001547 VectorTypes.InsertNode(New, InsertPos);
1548 Types.push_back(New);
1549 return QualType(New, 0);
1550}
1551
Nate Begemance4d7fc2008-04-18 23:10:10 +00001552/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001553/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001554QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001555 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattner76a00cf2008-04-06 22:59:24 +00001557 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001558 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001559
Steve Naroff91fcddb2007-07-18 18:00:27 +00001560 // Check if we've already instantiated a vector of this type.
1561 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001562 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1563 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001564 void *InsertPos = 0;
1565 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1566 return QualType(VTP, 0);
1567
1568 // If the element type isn't canonical, this won't be a canonical type either,
1569 // so fill in the canonical type field.
1570 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001571 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001572 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Steve Naroff91fcddb2007-07-18 18:00:27 +00001574 // Get the new insert position for the node we care about.
1575 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001576 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001577 }
John McCall90d1c2d2009-09-24 23:30:46 +00001578 ExtVectorType *New = new (*this, TypeAlignment)
1579 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001580 VectorTypes.InsertNode(New, InsertPos);
1581 Types.push_back(New);
1582 return QualType(New, 0);
1583}
1584
Mike Stump11289f42009-09-09 15:08:12 +00001585QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001586 Expr *SizeExpr,
1587 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001588 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001589 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001590 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Douglas Gregor352169a2009-07-31 03:54:25 +00001592 void *InsertPos = 0;
1593 DependentSizedExtVectorType *Canon
1594 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1595 DependentSizedExtVectorType *New;
1596 if (Canon) {
1597 // We already have a canonical version of this array type; use it as
1598 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001599 New = new (*this, TypeAlignment)
1600 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1601 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001602 } else {
1603 QualType CanonVecTy = getCanonicalType(vecType);
1604 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001605 New = new (*this, TypeAlignment)
1606 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1607 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001608
1609 DependentSizedExtVectorType *CanonCheck
1610 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1611 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1612 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001613 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1614 } else {
1615 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1616 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001617 New = new (*this, TypeAlignment)
1618 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001619 }
1620 }
Mike Stump11289f42009-09-09 15:08:12 +00001621
Douglas Gregor758a8692009-06-17 21:51:59 +00001622 Types.push_back(New);
1623 return QualType(New, 0);
1624}
1625
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001626/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001627///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001628QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1629 const FunctionType::ExtInfo &Info) {
1630 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001631 // Unique functions, to guarantee there is only one function of a particular
1632 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001633 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001634 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattner47955de2007-01-27 08:37:20 +00001636 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001637 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001638 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001639 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001641 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001642 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001643 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001644 Canonical =
1645 getFunctionNoProtoType(getCanonicalType(ResultTy),
1646 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001647
Chris Lattner47955de2007-01-27 08:37:20 +00001648 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001649 FunctionNoProtoType *NewIP =
1650 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001651 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
John McCall90d1c2d2009-09-24 23:30:46 +00001654 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001655 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001656 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001657 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001658 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001659}
1660
1661/// getFunctionType - Return a normal function type with a typed argument
1662/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001663QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001664 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001665 unsigned TypeQuals, bool hasExceptionSpec,
1666 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001667 const QualType *ExArray,
1668 const FunctionType::ExtInfo &Info) {
1669 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001670 // Unique functions, to guarantee there is only one function of a particular
1671 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001672 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001673 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001674 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001675 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001676
1677 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001678 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001679 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001680 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001681
1682 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001683 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001684 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001685 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001686 isCanonical = false;
1687
1688 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001689 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001690 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001691 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001692 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001693 CanonicalArgs.reserve(NumArgs);
1694 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001695 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001696
Chris Lattner76a00cf2008-04-06 22:59:24 +00001697 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001698 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001699 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001700 false, 0, 0,
1701 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001702
Chris Lattnerfd4de792007-01-27 01:15:32 +00001703 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001704 FunctionProtoType *NewIP =
1705 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001706 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001707 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001708
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001709 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001710 // for two variable size arrays (for parameter and exception types) at the
1711 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001712 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001713 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1714 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001715 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001716 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001717 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001718 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001719 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001720 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001721 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001722}
Chris Lattneref51c202006-11-10 07:17:23 +00001723
John McCalle78aac42010-03-10 03:28:59 +00001724#ifndef NDEBUG
1725static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1726 if (!isa<CXXRecordDecl>(D)) return false;
1727 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1728 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1729 return true;
1730 if (RD->getDescribedClassTemplate() &&
1731 !isa<ClassTemplateSpecializationDecl>(RD))
1732 return true;
1733 return false;
1734}
1735#endif
1736
1737/// getInjectedClassNameType - Return the unique reference to the
1738/// injected class name type for the specified templated declaration.
1739QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1740 QualType TST) {
1741 assert(NeedsInjectedClassNameType(Decl));
1742 if (Decl->TypeForDecl) {
1743 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1744 } else if (CXXRecordDecl *PrevDecl
1745 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1746 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1747 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1748 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1749 } else {
John McCall2408e322010-04-27 00:57:59 +00001750 Decl->TypeForDecl =
1751 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001752 Types.push_back(Decl->TypeForDecl);
1753 }
1754 return QualType(Decl->TypeForDecl, 0);
1755}
1756
Douglas Gregor83a586e2008-04-13 21:07:44 +00001757/// getTypeDeclType - Return the unique reference to the type for the
1758/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001759QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001760 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001761 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001762
John McCall81e38502010-02-16 03:57:14 +00001763 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001764 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001765
John McCall96f0b5f2010-03-10 06:48:02 +00001766 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1767 "Template type parameter types are always available.");
1768
John McCall81e38502010-02-16 03:57:14 +00001769 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001770 assert(!Record->getPreviousDeclaration() &&
1771 "struct/union has previous declaration");
1772 assert(!NeedsInjectedClassNameType(Record));
1773 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001774 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001775 assert(!Enum->getPreviousDeclaration() &&
1776 "enum has previous declaration");
1777 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001778 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001779 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1780 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001781 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001782 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001783
John McCall96f0b5f2010-03-10 06:48:02 +00001784 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001785 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001786}
1787
Chris Lattner32d920b2007-01-26 02:01:53 +00001788/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001789/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001790QualType
1791ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001792 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001793
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001794 if (Canonical.isNull())
1795 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001796 Decl->TypeForDecl = new(*this, TypeAlignment)
1797 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001798 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001799 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001800}
1801
John McCallcebee162009-10-18 09:09:24 +00001802/// \brief Retrieve a substitution-result type.
1803QualType
1804ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1805 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001806 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001807 && "replacement types must always be canonical");
1808
1809 llvm::FoldingSetNodeID ID;
1810 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1811 void *InsertPos = 0;
1812 SubstTemplateTypeParmType *SubstParm
1813 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1814
1815 if (!SubstParm) {
1816 SubstParm = new (*this, TypeAlignment)
1817 SubstTemplateTypeParmType(Parm, Replacement);
1818 Types.push_back(SubstParm);
1819 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1820 }
1821
1822 return QualType(SubstParm, 0);
1823}
1824
Douglas Gregoreff93e02009-02-05 23:33:38 +00001825/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001826/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001827/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001828QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001829 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001830 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001831 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001832 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001833 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001834 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001835 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1836
1837 if (TypeParm)
1838 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001839
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001840 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001841 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001842 TypeParm = new (*this, TypeAlignment)
1843 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001844
1845 TemplateTypeParmType *TypeCheck
1846 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1847 assert(!TypeCheck && "Template type parameter canonical type broken");
1848 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001849 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001850 TypeParm = new (*this, TypeAlignment)
1851 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001852
1853 Types.push_back(TypeParm);
1854 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1855
1856 return QualType(TypeParm, 0);
1857}
1858
John McCalle78aac42010-03-10 03:28:59 +00001859TypeSourceInfo *
1860ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1861 SourceLocation NameLoc,
1862 const TemplateArgumentListInfo &Args,
1863 QualType CanonType) {
1864 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1865
1866 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1867 TemplateSpecializationTypeLoc TL
1868 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1869 TL.setTemplateNameLoc(NameLoc);
1870 TL.setLAngleLoc(Args.getLAngleLoc());
1871 TL.setRAngleLoc(Args.getRAngleLoc());
1872 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1873 TL.setArgLocInfo(i, Args[i].getLocInfo());
1874 return DI;
1875}
1876
Mike Stump11289f42009-09-09 15:08:12 +00001877QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001878ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001879 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001880 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001881 unsigned NumArgs = Args.size();
1882
John McCall0ad16662009-10-29 08:12:44 +00001883 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1884 ArgVec.reserve(NumArgs);
1885 for (unsigned i = 0; i != NumArgs; ++i)
1886 ArgVec.push_back(Args[i].getArgument());
1887
John McCall2408e322010-04-27 00:57:59 +00001888 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001889 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001890}
1891
1892QualType
1893ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001894 const TemplateArgument *Args,
1895 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001896 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001897 if (!Canon.isNull())
1898 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001899 else
1900 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001901
Douglas Gregora8e02e72009-07-28 23:00:59 +00001902 // Allocate the (non-canonical) template specialization type, but don't
1903 // try to unique it: these types typically have location information that
1904 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001905 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001906 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001907 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001908 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001909 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001910 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001911 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregor8bf42052009-02-09 18:46:07 +00001913 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001914 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001915}
1916
Mike Stump11289f42009-09-09 15:08:12 +00001917QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001918ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1919 const TemplateArgument *Args,
1920 unsigned NumArgs) {
1921 // Build the canonical template specialization type.
1922 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1923 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1924 CanonArgs.reserve(NumArgs);
1925 for (unsigned I = 0; I != NumArgs; ++I)
1926 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1927
1928 // Determine whether this canonical template specialization type already
1929 // exists.
1930 llvm::FoldingSetNodeID ID;
1931 TemplateSpecializationType::Profile(ID, CanonTemplate,
1932 CanonArgs.data(), NumArgs, *this);
1933
1934 void *InsertPos = 0;
1935 TemplateSpecializationType *Spec
1936 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1937
1938 if (!Spec) {
1939 // Allocate a new canonical template specialization type.
1940 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1941 sizeof(TemplateArgument) * NumArgs),
1942 TypeAlignment);
1943 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1944 CanonArgs.data(), NumArgs,
1945 QualType());
1946 Types.push_back(Spec);
1947 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1948 }
1949
1950 assert(Spec->isDependentType() &&
1951 "Non-dependent template-id type must have a canonical type");
1952 return QualType(Spec, 0);
1953}
1954
1955QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001956ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1957 NestedNameSpecifier *NNS,
1958 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001959 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001960 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001961
1962 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001963 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001964 if (T)
1965 return QualType(T, 0);
1966
Douglas Gregorc42075a2010-02-04 18:10:26 +00001967 QualType Canon = NamedType;
1968 if (!Canon.isCanonical()) {
1969 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001970 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1971 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001972 (void)CheckT;
1973 }
1974
Abramo Bagnara6150c882010-05-11 21:36:43 +00001975 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001976 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001977 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001978 return QualType(T, 0);
1979}
1980
Douglas Gregor02085352010-03-31 20:19:30 +00001981QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1982 NestedNameSpecifier *NNS,
1983 const IdentifierInfo *Name,
1984 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001985 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1986
1987 if (Canon.isNull()) {
1988 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001989 ElaboratedTypeKeyword CanonKeyword = Keyword;
1990 if (Keyword == ETK_None)
1991 CanonKeyword = ETK_Typename;
1992
1993 if (CanonNNS != NNS || CanonKeyword != Keyword)
1994 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001995 }
1996
1997 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001998 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001999
2000 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002001 DependentNameType *T
2002 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002003 if (T)
2004 return QualType(T, 0);
2005
Douglas Gregor02085352010-03-31 20:19:30 +00002006 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002007 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002008 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002009 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002010}
2011
Mike Stump11289f42009-09-09 15:08:12 +00002012QualType
John McCallc392f372010-06-11 00:33:02 +00002013ASTContext::getDependentTemplateSpecializationType(
2014 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002015 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002016 const IdentifierInfo *Name,
2017 const TemplateArgumentListInfo &Args) {
2018 // TODO: avoid this copy
2019 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2020 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2021 ArgCopy.push_back(Args[I].getArgument());
2022 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2023 ArgCopy.size(),
2024 ArgCopy.data());
2025}
2026
2027QualType
2028ASTContext::getDependentTemplateSpecializationType(
2029 ElaboratedTypeKeyword Keyword,
2030 NestedNameSpecifier *NNS,
2031 const IdentifierInfo *Name,
2032 unsigned NumArgs,
2033 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002034 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2035
Douglas Gregorc42075a2010-02-04 18:10:26 +00002036 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002037 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2038 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002039
2040 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002041 DependentTemplateSpecializationType *T
2042 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002043 if (T)
2044 return QualType(T, 0);
2045
John McCallc392f372010-06-11 00:33:02 +00002046 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002047
John McCallc392f372010-06-11 00:33:02 +00002048 ElaboratedTypeKeyword CanonKeyword = Keyword;
2049 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2050
2051 bool AnyNonCanonArgs = false;
2052 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2053 for (unsigned I = 0; I != NumArgs; ++I) {
2054 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2055 if (!CanonArgs[I].structurallyEquals(Args[I]))
2056 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002057 }
2058
John McCallc392f372010-06-11 00:33:02 +00002059 QualType Canon;
2060 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2061 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2062 Name, NumArgs,
2063 CanonArgs.data());
2064
2065 // Find the insert position again.
2066 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2067 }
2068
2069 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2070 sizeof(TemplateArgument) * NumArgs),
2071 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002072 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002073 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002074 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002075 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002076 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002077}
2078
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002079/// CmpProtocolNames - Comparison predicate for sorting protocols
2080/// alphabetically.
2081static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2082 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002083 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002084}
2085
John McCall8b07ec22010-05-15 11:32:37 +00002086static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002087 unsigned NumProtocols) {
2088 if (NumProtocols == 0) return true;
2089
2090 for (unsigned i = 1; i != NumProtocols; ++i)
2091 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2092 return false;
2093 return true;
2094}
2095
2096static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002097 unsigned &NumProtocols) {
2098 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002099
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002100 // Sort protocols, keyed by name.
2101 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2102
2103 // Remove duplicates.
2104 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2105 NumProtocols = ProtocolsEnd-Protocols;
2106}
2107
John McCall8b07ec22010-05-15 11:32:37 +00002108QualType ASTContext::getObjCObjectType(QualType BaseType,
2109 ObjCProtocolDecl * const *Protocols,
2110 unsigned NumProtocols) {
2111 // If the base type is an interface and there aren't any protocols
2112 // to add, then the interface type will do just fine.
2113 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2114 return BaseType;
2115
2116 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002117 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002118 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002119 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002120 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2121 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002122
John McCall8b07ec22010-05-15 11:32:37 +00002123 // Build the canonical type, which has the canonical base type and
2124 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002125 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002126 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2127 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2128 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002129 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2130 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002131 unsigned UniqueCount = NumProtocols;
2132
John McCallfc93cf92009-10-22 22:37:11 +00002133 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002134 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2135 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002136 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002137 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2138 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002139 }
2140
2141 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002142 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2143 }
2144
2145 unsigned Size = sizeof(ObjCObjectTypeImpl);
2146 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2147 void *Mem = Allocate(Size, TypeAlignment);
2148 ObjCObjectTypeImpl *T =
2149 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2150
2151 Types.push_back(T);
2152 ObjCObjectTypes.InsertNode(T, InsertPos);
2153 return QualType(T, 0);
2154}
2155
2156/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2157/// the given object type.
2158QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2159 llvm::FoldingSetNodeID ID;
2160 ObjCObjectPointerType::Profile(ID, ObjectT);
2161
2162 void *InsertPos = 0;
2163 if (ObjCObjectPointerType *QT =
2164 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2165 return QualType(QT, 0);
2166
2167 // Find the canonical object type.
2168 QualType Canonical;
2169 if (!ObjectT.isCanonical()) {
2170 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2171
2172 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002173 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2174 }
2175
Douglas Gregorf85bee62010-02-08 22:59:26 +00002176 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002177 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2178 ObjCObjectPointerType *QType =
2179 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002180
Steve Narofffb4330f2009-06-17 22:40:22 +00002181 Types.push_back(QType);
2182 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002183 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002184}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002185
Steve Naroffc277ad12009-07-18 15:33:26 +00002186/// getObjCInterfaceType - Return the unique reference to the type for the
2187/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002188QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2189 if (Decl->TypeForDecl)
2190 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002191
John McCall8b07ec22010-05-15 11:32:37 +00002192 // FIXME: redeclarations?
2193 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2194 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2195 Decl->TypeForDecl = T;
2196 Types.push_back(T);
2197 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002198}
2199
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002200/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2201/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002202/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002203/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002204/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002205QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002206 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002207 if (tofExpr->isTypeDependent()) {
2208 llvm::FoldingSetNodeID ID;
2209 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002211 void *InsertPos = 0;
2212 DependentTypeOfExprType *Canon
2213 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2214 if (Canon) {
2215 // We already have a "canonical" version of an identical, dependent
2216 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002217 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002218 QualType((TypeOfExprType*)Canon, 0));
2219 }
2220 else {
2221 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002222 Canon
2223 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002224 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2225 toe = Canon;
2226 }
2227 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002228 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002229 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002230 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002231 Types.push_back(toe);
2232 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002233}
2234
Steve Naroffa773cd52007-08-01 18:02:17 +00002235/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2236/// TypeOfType AST's. The only motivation to unique these nodes would be
2237/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002238/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002239/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002240QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002241 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002242 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002243 Types.push_back(tot);
2244 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002245}
2246
Anders Carlssonad6bd352009-06-24 21:24:56 +00002247/// getDecltypeForExpr - Given an expr, will return the decltype for that
2248/// expression, according to the rules in C++0x [dcl.type.simple]p4
2249static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002250 if (e->isTypeDependent())
2251 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002252
Anders Carlssonad6bd352009-06-24 21:24:56 +00002253 // If e is an id expression or a class member access, decltype(e) is defined
2254 // as the type of the entity named by e.
2255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2256 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2257 return VD->getType();
2258 }
2259 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2260 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2261 return FD->getType();
2262 }
2263 // If e is a function call or an invocation of an overloaded operator,
2264 // (parentheses around e are ignored), decltype(e) is defined as the
2265 // return type of that function.
2266 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2267 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002268
Anders Carlssonad6bd352009-06-24 21:24:56 +00002269 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002270
2271 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002272 // defined as T&, otherwise decltype(e) is defined as T.
2273 if (e->isLvalue(Context) == Expr::LV_Valid)
2274 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002275
Anders Carlssonad6bd352009-06-24 21:24:56 +00002276 return T;
2277}
2278
Anders Carlsson81df7b82009-06-24 19:06:50 +00002279/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2280/// DecltypeType AST's. The only motivation to unique these nodes would be
2281/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002282/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002283/// on canonical type's (which are always unique).
2284QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002285 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002286 if (e->isTypeDependent()) {
2287 llvm::FoldingSetNodeID ID;
2288 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002289
Douglas Gregora21f6c32009-07-30 23:36:40 +00002290 void *InsertPos = 0;
2291 DependentDecltypeType *Canon
2292 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2293 if (Canon) {
2294 // We already have a "canonical" version of an equivalent, dependent
2295 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002296 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002297 QualType((DecltypeType*)Canon, 0));
2298 }
2299 else {
2300 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002301 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002302 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2303 dt = Canon;
2304 }
2305 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002306 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002307 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002308 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002309 Types.push_back(dt);
2310 return QualType(dt, 0);
2311}
2312
Chris Lattnerfb072462007-01-23 05:45:31 +00002313/// getTagDeclType - Return the unique reference to the type for the
2314/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002315QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002316 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002317 // FIXME: What is the design on getTagDeclType when it requires casting
2318 // away const? mutable?
2319 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002320}
2321
Mike Stump11289f42009-09-09 15:08:12 +00002322/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2323/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2324/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002325CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002326 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002327}
Chris Lattnerfb072462007-01-23 05:45:31 +00002328
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002329/// getSignedWCharType - Return the type of "signed wchar_t".
2330/// Used when in C++, as a GCC extension.
2331QualType ASTContext::getSignedWCharType() const {
2332 // FIXME: derive from "Target" ?
2333 return WCharTy;
2334}
2335
2336/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2337/// Used when in C++, as a GCC extension.
2338QualType ASTContext::getUnsignedWCharType() const {
2339 // FIXME: derive from "Target" ?
2340 return UnsignedIntTy;
2341}
2342
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002343/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2344/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2345QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002346 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002347}
2348
Chris Lattnera21ad802008-04-02 05:18:44 +00002349//===----------------------------------------------------------------------===//
2350// Type Operators
2351//===----------------------------------------------------------------------===//
2352
John McCallfc93cf92009-10-22 22:37:11 +00002353CanQualType ASTContext::getCanonicalParamType(QualType T) {
2354 // Push qualifiers into arrays, and then discard any remaining
2355 // qualifiers.
2356 T = getCanonicalType(T);
2357 const Type *Ty = T.getTypePtr();
2358
2359 QualType Result;
2360 if (isa<ArrayType>(Ty)) {
2361 Result = getArrayDecayedType(QualType(Ty,0));
2362 } else if (isa<FunctionType>(Ty)) {
2363 Result = getPointerType(QualType(Ty, 0));
2364 } else {
2365 Result = QualType(Ty, 0);
2366 }
2367
2368 return CanQualType::CreateUnsafe(Result);
2369}
2370
Chris Lattnered0d0792008-04-06 22:41:35 +00002371/// getCanonicalType - Return the canonical (structural) type corresponding to
2372/// the specified potentially non-canonical type. The non-canonical version
2373/// of a type may have many "decorated" versions of types. Decorators can
2374/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2375/// to be free of any of these, allowing two canonical types to be compared
2376/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002377CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002378 QualifierCollector Quals;
2379 const Type *Ptr = Quals.strip(T);
2380 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002381
John McCall8ccfcb52009-09-24 19:53:00 +00002382 // The canonical internal type will be the canonical type *except*
2383 // that we push type qualifiers down through array types.
2384
2385 // If there are no new qualifiers to push down, stop here.
2386 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002387 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002388
John McCall8ccfcb52009-09-24 19:53:00 +00002389 // If the type qualifiers are on an array type, get the canonical
2390 // type of the array with the qualifiers applied to the element
2391 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002392 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2393 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002394 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002395
Chris Lattner7adf0762008-08-04 07:31:14 +00002396 // Get the canonical version of the element with the extra qualifiers on it.
2397 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002398 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002399 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002400
Chris Lattner7adf0762008-08-04 07:31:14 +00002401 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002402 return CanQualType::CreateUnsafe(
2403 getConstantArrayType(NewEltTy, CAT->getSize(),
2404 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002405 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002406 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002407 return CanQualType::CreateUnsafe(
2408 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002409 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002410
Douglas Gregor4619e432008-12-05 23:32:09 +00002411 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002412 return CanQualType::CreateUnsafe(
2413 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002414 DSAT->getSizeExpr() ?
2415 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002416 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002417 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002418 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002419
Chris Lattner7adf0762008-08-04 07:31:14 +00002420 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002421 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002422 VAT->getSizeExpr() ?
2423 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002424 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002425 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002426 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002427}
2428
Chandler Carruth607f38e2009-12-29 07:16:59 +00002429QualType ASTContext::getUnqualifiedArrayType(QualType T,
2430 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002431 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002432 const ArrayType *AT = getAsArrayType(T);
2433 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002434 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002435 }
2436
Chandler Carruth607f38e2009-12-29 07:16:59 +00002437 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002438 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002439 if (Elt == UnqualElt)
2440 return T;
2441
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002442 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002443 return getConstantArrayType(UnqualElt, CAT->getSize(),
2444 CAT->getSizeModifier(), 0);
2445 }
2446
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002447 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002448 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2449 }
2450
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002451 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2452 return getVariableArrayType(UnqualElt,
2453 VAT->getSizeExpr() ?
2454 VAT->getSizeExpr()->Retain() : 0,
2455 VAT->getSizeModifier(),
2456 VAT->getIndexTypeCVRQualifiers(),
2457 VAT->getBracketsRange());
2458 }
2459
2460 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002461 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2462 DSAT->getSizeModifier(), 0,
2463 SourceRange());
2464}
2465
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002466/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2467/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2468/// they point to and return true. If T1 and T2 aren't pointer types
2469/// or pointer-to-member types, or if they are not similar at this
2470/// level, returns false and leaves T1 and T2 unchanged. Top-level
2471/// qualifiers on T1 and T2 are ignored. This function will typically
2472/// be called in a loop that successively "unwraps" pointer and
2473/// pointer-to-member types to compare them at each level.
2474bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2475 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2476 *T2PtrType = T2->getAs<PointerType>();
2477 if (T1PtrType && T2PtrType) {
2478 T1 = T1PtrType->getPointeeType();
2479 T2 = T2PtrType->getPointeeType();
2480 return true;
2481 }
2482
2483 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2484 *T2MPType = T2->getAs<MemberPointerType>();
2485 if (T1MPType && T2MPType &&
2486 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2487 QualType(T2MPType->getClass(), 0))) {
2488 T1 = T1MPType->getPointeeType();
2489 T2 = T2MPType->getPointeeType();
2490 return true;
2491 }
2492
2493 if (getLangOptions().ObjC1) {
2494 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2495 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2496 if (T1OPType && T2OPType) {
2497 T1 = T1OPType->getPointeeType();
2498 T2 = T2OPType->getPointeeType();
2499 return true;
2500 }
2501 }
2502
2503 // FIXME: Block pointers, too?
2504
2505 return false;
2506}
2507
John McCall847e2a12009-11-24 18:42:40 +00002508DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2509 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2510 return TD->getDeclName();
2511
2512 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2513 if (DTN->isIdentifier()) {
2514 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2515 } else {
2516 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2517 }
2518 }
2519
John McCalld28ae272009-12-02 08:04:21 +00002520 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2521 assert(Storage);
2522 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002523}
2524
Douglas Gregor6bc50582009-05-07 06:41:52 +00002525TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002526 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2527 if (TemplateTemplateParmDecl *TTP
2528 = dyn_cast<TemplateTemplateParmDecl>(Template))
2529 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2530
2531 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002532 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002533 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002534
John McCalld28ae272009-12-02 08:04:21 +00002535 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002536
Douglas Gregor6bc50582009-05-07 06:41:52 +00002537 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2538 assert(DTN && "Non-dependent template names must refer to template decls.");
2539 return DTN->CanonicalTemplateName;
2540}
2541
Douglas Gregoradee3e32009-11-11 23:06:43 +00002542bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2543 X = getCanonicalTemplateName(X);
2544 Y = getCanonicalTemplateName(Y);
2545 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2546}
2547
Mike Stump11289f42009-09-09 15:08:12 +00002548TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002549ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2550 switch (Arg.getKind()) {
2551 case TemplateArgument::Null:
2552 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002553
Douglas Gregora8e02e72009-07-28 23:00:59 +00002554 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002555 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Douglas Gregora8e02e72009-07-28 23:00:59 +00002557 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002558 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002560 case TemplateArgument::Template:
2561 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2562
Douglas Gregora8e02e72009-07-28 23:00:59 +00002563 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002564 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002565 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002566
Douglas Gregora8e02e72009-07-28 23:00:59 +00002567 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002568 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002569
Douglas Gregora8e02e72009-07-28 23:00:59 +00002570 case TemplateArgument::Pack: {
2571 // FIXME: Allocate in ASTContext
2572 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2573 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002574 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002575 AEnd = Arg.pack_end();
2576 A != AEnd; (void)++A, ++Idx)
2577 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregora8e02e72009-07-28 23:00:59 +00002579 TemplateArgument Result;
2580 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2581 return Result;
2582 }
2583 }
2584
2585 // Silence GCC warning
2586 assert(false && "Unhandled template argument kind");
2587 return TemplateArgument();
2588}
2589
Douglas Gregor333489b2009-03-27 23:10:48 +00002590NestedNameSpecifier *
2591ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002592 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002593 return 0;
2594
2595 switch (NNS->getKind()) {
2596 case NestedNameSpecifier::Identifier:
2597 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002598 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002599 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2600 NNS->getAsIdentifier());
2601
2602 case NestedNameSpecifier::Namespace:
2603 // A namespace is canonical; build a nested-name-specifier with
2604 // this namespace and no prefix.
2605 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2606
2607 case NestedNameSpecifier::TypeSpec:
2608 case NestedNameSpecifier::TypeSpecWithTemplate: {
2609 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002610 return NestedNameSpecifier::Create(*this, 0,
2611 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002612 T.getTypePtr());
2613 }
2614
2615 case NestedNameSpecifier::Global:
2616 // The global specifier is canonical and unique.
2617 return NNS;
2618 }
2619
2620 // Required to silence a GCC warning
2621 return 0;
2622}
2623
Chris Lattner7adf0762008-08-04 07:31:14 +00002624
2625const ArrayType *ASTContext::getAsArrayType(QualType T) {
2626 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002627 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002628 // Handle the common positive case fast.
2629 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2630 return AT;
2631 }
Mike Stump11289f42009-09-09 15:08:12 +00002632
John McCall8ccfcb52009-09-24 19:53:00 +00002633 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002634 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002635 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002636 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002637
John McCall8ccfcb52009-09-24 19:53:00 +00002638 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002639 // implements C99 6.7.3p8: "If the specification of an array type includes
2640 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002641
Chris Lattner7adf0762008-08-04 07:31:14 +00002642 // If we get here, we either have type qualifiers on the type, or we have
2643 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002644 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002645
John McCall8ccfcb52009-09-24 19:53:00 +00002646 QualifierCollector Qs;
2647 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002648
Chris Lattner7adf0762008-08-04 07:31:14 +00002649 // If we have a simple case, just return now.
2650 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002651 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002652 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002653
Chris Lattner7adf0762008-08-04 07:31:14 +00002654 // Otherwise, we have an array and we have qualifiers on it. Push the
2655 // qualifiers into the array element type and return a new array type.
2656 // Get the canonical version of the element with the extra qualifiers on it.
2657 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002658 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002659
Chris Lattner7adf0762008-08-04 07:31:14 +00002660 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2661 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2662 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002663 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002664 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2665 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2666 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002667 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002668
Mike Stump11289f42009-09-09 15:08:12 +00002669 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002670 = dyn_cast<DependentSizedArrayType>(ATy))
2671 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002672 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002673 DSAT->getSizeExpr() ?
2674 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002675 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002676 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002677 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002678
Chris Lattner7adf0762008-08-04 07:31:14 +00002679 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002680 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002681 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002682 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002683 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002684 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002685 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002686}
2687
2688
Chris Lattnera21ad802008-04-02 05:18:44 +00002689/// getArrayDecayedType - Return the properly qualified result of decaying the
2690/// specified array type to a pointer. This operation is non-trivial when
2691/// handling typedefs etc. The canonical type of "T" must be an array type,
2692/// this returns a pointer to a properly qualified element of the array.
2693///
2694/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2695QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002696 // Get the element type with 'getAsArrayType' so that we don't lose any
2697 // typedefs in the element type of the array. This also handles propagation
2698 // of type qualifiers from the array type into the element type if present
2699 // (C99 6.7.3p8).
2700 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2701 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002702
Chris Lattner7adf0762008-08-04 07:31:14 +00002703 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002704
2705 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002706 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002707}
2708
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002709QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002710 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002711 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2712 QT = AT->getElementType();
2713 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002714}
2715
Anders Carlsson4bf82142009-09-25 01:23:32 +00002716QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2717 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002718
Anders Carlsson4bf82142009-09-25 01:23:32 +00002719 if (const ArrayType *AT = getAsArrayType(ElemTy))
2720 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002721
Anders Carlssone0808df2008-12-21 03:44:36 +00002722 return ElemTy;
2723}
2724
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002725/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002726uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002727ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2728 uint64_t ElementCount = 1;
2729 do {
2730 ElementCount *= CA->getSize().getZExtValue();
2731 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2732 } while (CA);
2733 return ElementCount;
2734}
2735
Steve Naroff0af91202007-04-27 21:51:21 +00002736/// getFloatingRank - Return a relative rank for floating point types.
2737/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002738static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002739 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002740 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002741
John McCall9dd450b2009-09-21 23:43:11 +00002742 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2743 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002744 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002745 case BuiltinType::Float: return FloatRank;
2746 case BuiltinType::Double: return DoubleRank;
2747 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002748 }
2749}
2750
Mike Stump11289f42009-09-09 15:08:12 +00002751/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2752/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002753/// 'typeDomain' is a real floating point or complex type.
2754/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002755QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2756 QualType Domain) const {
2757 FloatingRank EltRank = getFloatingRank(Size);
2758 if (Domain->isComplexType()) {
2759 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002760 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002761 case FloatRank: return FloatComplexTy;
2762 case DoubleRank: return DoubleComplexTy;
2763 case LongDoubleRank: return LongDoubleComplexTy;
2764 }
Steve Naroff0af91202007-04-27 21:51:21 +00002765 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002766
2767 assert(Domain->isRealFloatingType() && "Unknown domain!");
2768 switch (EltRank) {
2769 default: assert(0 && "getFloatingRank(): illegal value for rank");
2770 case FloatRank: return FloatTy;
2771 case DoubleRank: return DoubleTy;
2772 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002773 }
Steve Naroffe4718892007-04-27 18:30:00 +00002774}
2775
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002776/// getFloatingTypeOrder - Compare the rank of the two specified floating
2777/// point types, ignoring the domain of the type (i.e. 'double' ==
2778/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002779/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002780int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2781 FloatingRank LHSR = getFloatingRank(LHS);
2782 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002783
Chris Lattnerb90739d2008-04-06 23:38:49 +00002784 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002785 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002786 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002787 return 1;
2788 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002789}
2790
Chris Lattner76a00cf2008-04-06 22:59:24 +00002791/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2792/// routine will assert if passed a built-in type that isn't an integer or enum,
2793/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002794unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002795 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002796 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002797 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002798
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002799 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2800 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2801
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002802 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2803 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2804
2805 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2806 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2807
Chris Lattner76a00cf2008-04-06 22:59:24 +00002808 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002809 default: assert(0 && "getIntegerRank(): not a built-in integer");
2810 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002811 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002812 case BuiltinType::Char_S:
2813 case BuiltinType::Char_U:
2814 case BuiltinType::SChar:
2815 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002816 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002817 case BuiltinType::Short:
2818 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002819 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002820 case BuiltinType::Int:
2821 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002822 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002823 case BuiltinType::Long:
2824 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002825 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002826 case BuiltinType::LongLong:
2827 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002828 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002829 case BuiltinType::Int128:
2830 case BuiltinType::UInt128:
2831 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002832 }
2833}
2834
Eli Friedman629ffb92009-08-20 04:21:42 +00002835/// \brief Whether this is a promotable bitfield reference according
2836/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2837///
2838/// \returns the type this bit-field will promote to, or NULL if no
2839/// promotion occurs.
2840QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002841 if (E->isTypeDependent() || E->isValueDependent())
2842 return QualType();
2843
Eli Friedman629ffb92009-08-20 04:21:42 +00002844 FieldDecl *Field = E->getBitField();
2845 if (!Field)
2846 return QualType();
2847
2848 QualType FT = Field->getType();
2849
2850 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2851 uint64_t BitWidth = BitWidthAP.getZExtValue();
2852 uint64_t IntSize = getTypeSize(IntTy);
2853 // GCC extension compatibility: if the bit-field size is less than or equal
2854 // to the size of int, it gets promoted no matter what its type is.
2855 // For instance, unsigned long bf : 4 gets promoted to signed int.
2856 if (BitWidth < IntSize)
2857 return IntTy;
2858
2859 if (BitWidth == IntSize)
2860 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2861
2862 // Types bigger than int are not subject to promotions, and therefore act
2863 // like the base type.
2864 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2865 // is ridiculous.
2866 return QualType();
2867}
2868
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002869/// getPromotedIntegerType - Returns the type that Promotable will
2870/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2871/// integer type.
2872QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2873 assert(!Promotable.isNull());
2874 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002875 if (const EnumType *ET = Promotable->getAs<EnumType>())
2876 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002877 if (Promotable->isSignedIntegerType())
2878 return IntTy;
2879 uint64_t PromotableSize = getTypeSize(Promotable);
2880 uint64_t IntSize = getTypeSize(IntTy);
2881 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2882 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2883}
2884
Mike Stump11289f42009-09-09 15:08:12 +00002885/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002886/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002887/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002888int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002889 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2890 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002891 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002892
Chris Lattner76a00cf2008-04-06 22:59:24 +00002893 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2894 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002895
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002896 unsigned LHSRank = getIntegerRank(LHSC);
2897 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002899 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2900 if (LHSRank == RHSRank) return 0;
2901 return LHSRank > RHSRank ? 1 : -1;
2902 }
Mike Stump11289f42009-09-09 15:08:12 +00002903
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002904 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2905 if (LHSUnsigned) {
2906 // If the unsigned [LHS] type is larger, return it.
2907 if (LHSRank >= RHSRank)
2908 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002909
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002910 // If the signed type can represent all values of the unsigned type, it
2911 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002912 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002913 return -1;
2914 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002915
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002916 // If the unsigned [RHS] type is larger, return it.
2917 if (RHSRank >= LHSRank)
2918 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002919
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002920 // If the signed type can represent all values of the unsigned type, it
2921 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002922 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002923 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002924}
Anders Carlsson98f07902007-08-17 05:31:46 +00002925
Anders Carlsson6d417272009-11-14 21:45:58 +00002926static RecordDecl *
2927CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2928 SourceLocation L, IdentifierInfo *Id) {
2929 if (Ctx.getLangOptions().CPlusPlus)
2930 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2931 else
2932 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2933}
2934
Mike Stump11289f42009-09-09 15:08:12 +00002935// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002936QualType ASTContext::getCFConstantStringType() {
2937 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002938 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002939 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002940 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002941 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002942
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002943 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002944
Anders Carlsson98f07902007-08-17 05:31:46 +00002945 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002946 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002947 // int flags;
2948 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002949 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002950 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002951 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002952 FieldTypes[3] = LongTy;
2953
Anders Carlsson98f07902007-08-17 05:31:46 +00002954 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002955 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002956 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002957 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002958 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002959 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002960 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002961 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002962 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002963 }
2964
Douglas Gregord5058122010-02-11 01:19:42 +00002965 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002966 }
Mike Stump11289f42009-09-09 15:08:12 +00002967
Anders Carlsson98f07902007-08-17 05:31:46 +00002968 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002969}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002970
Douglas Gregor512b0772009-04-23 22:29:11 +00002971void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002972 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002973 assert(Rec && "Invalid CFConstantStringType");
2974 CFConstantStringTypeDecl = Rec->getDecl();
2975}
2976
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002977// getNSConstantStringType - Return the type used for constant NSStrings.
2978QualType ASTContext::getNSConstantStringType() {
2979 if (!NSConstantStringTypeDecl) {
2980 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002981 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002982 &Idents.get("__builtin_NSString"));
2983 NSConstantStringTypeDecl->startDefinition();
2984
2985 QualType FieldTypes[3];
2986
2987 // const int *isa;
2988 FieldTypes[0] = getPointerType(IntTy.withConst());
2989 // const char *str;
2990 FieldTypes[1] = getPointerType(CharTy.withConst());
2991 // unsigned int length;
2992 FieldTypes[2] = UnsignedIntTy;
2993
2994 // Create fields
2995 for (unsigned i = 0; i < 3; ++i) {
2996 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2997 SourceLocation(), 0,
2998 FieldTypes[i], /*TInfo=*/0,
2999 /*BitWidth=*/0,
3000 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003001 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003002 NSConstantStringTypeDecl->addDecl(Field);
3003 }
3004
3005 NSConstantStringTypeDecl->completeDefinition();
3006 }
3007
3008 return getTagDeclType(NSConstantStringTypeDecl);
3009}
3010
3011void ASTContext::setNSConstantStringType(QualType T) {
3012 const RecordType *Rec = T->getAs<RecordType>();
3013 assert(Rec && "Invalid NSConstantStringType");
3014 NSConstantStringTypeDecl = Rec->getDecl();
3015}
3016
Mike Stump11289f42009-09-09 15:08:12 +00003017QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003018 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003019 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003020 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003021 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003022 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003023
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003024 QualType FieldTypes[] = {
3025 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003026 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003027 getPointerType(UnsignedLongTy),
3028 getConstantArrayType(UnsignedLongTy,
3029 llvm::APInt(32, 5), ArrayType::Normal, 0)
3030 };
Mike Stump11289f42009-09-09 15:08:12 +00003031
Douglas Gregor91f84212008-12-11 16:49:14 +00003032 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003033 FieldDecl *Field = FieldDecl::Create(*this,
3034 ObjCFastEnumerationStateTypeDecl,
3035 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003036 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003037 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003038 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003039 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003040 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003041 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003042 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003043 if (CXXRecordDecl *CXXRD =
3044 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003045 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003046
Douglas Gregord5058122010-02-11 01:19:42 +00003047 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003048 }
Mike Stump11289f42009-09-09 15:08:12 +00003049
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003050 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3051}
3052
Mike Stumpd0153282009-10-20 02:12:22 +00003053QualType ASTContext::getBlockDescriptorType() {
3054 if (BlockDescriptorType)
3055 return getTagDeclType(BlockDescriptorType);
3056
3057 RecordDecl *T;
3058 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003059 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003060 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003061 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003062
3063 QualType FieldTypes[] = {
3064 UnsignedLongTy,
3065 UnsignedLongTy,
3066 };
3067
3068 const char *FieldNames[] = {
3069 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003070 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003071 };
3072
3073 for (size_t i = 0; i < 2; ++i) {
3074 FieldDecl *Field = FieldDecl::Create(*this,
3075 T,
3076 SourceLocation(),
3077 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003078 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003079 /*BitWidth=*/0,
3080 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003081 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003082 T->addDecl(Field);
3083 }
3084
Douglas Gregord5058122010-02-11 01:19:42 +00003085 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003086
3087 BlockDescriptorType = T;
3088
3089 return getTagDeclType(BlockDescriptorType);
3090}
3091
3092void ASTContext::setBlockDescriptorType(QualType T) {
3093 const RecordType *Rec = T->getAs<RecordType>();
3094 assert(Rec && "Invalid BlockDescriptorType");
3095 BlockDescriptorType = Rec->getDecl();
3096}
3097
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003098QualType ASTContext::getBlockDescriptorExtendedType() {
3099 if (BlockDescriptorExtendedType)
3100 return getTagDeclType(BlockDescriptorExtendedType);
3101
3102 RecordDecl *T;
3103 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003104 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003105 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003106 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003107
3108 QualType FieldTypes[] = {
3109 UnsignedLongTy,
3110 UnsignedLongTy,
3111 getPointerType(VoidPtrTy),
3112 getPointerType(VoidPtrTy)
3113 };
3114
3115 const char *FieldNames[] = {
3116 "reserved",
3117 "Size",
3118 "CopyFuncPtr",
3119 "DestroyFuncPtr"
3120 };
3121
3122 for (size_t i = 0; i < 4; ++i) {
3123 FieldDecl *Field = FieldDecl::Create(*this,
3124 T,
3125 SourceLocation(),
3126 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003127 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003128 /*BitWidth=*/0,
3129 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003130 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003131 T->addDecl(Field);
3132 }
3133
Douglas Gregord5058122010-02-11 01:19:42 +00003134 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003135
3136 BlockDescriptorExtendedType = T;
3137
3138 return getTagDeclType(BlockDescriptorExtendedType);
3139}
3140
3141void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3142 const RecordType *Rec = T->getAs<RecordType>();
3143 assert(Rec && "Invalid BlockDescriptorType");
3144 BlockDescriptorExtendedType = Rec->getDecl();
3145}
3146
Mike Stump94967902009-10-21 18:16:27 +00003147bool ASTContext::BlockRequiresCopying(QualType Ty) {
3148 if (Ty->isBlockPointerType())
3149 return true;
3150 if (isObjCNSObjectType(Ty))
3151 return true;
3152 if (Ty->isObjCObjectPointerType())
3153 return true;
3154 return false;
3155}
3156
3157QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3158 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003159 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003160 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003161 // unsigned int __flags;
3162 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003163 // void *__copy_helper; // as needed
3164 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003165 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003166 // } *
3167
Mike Stump94967902009-10-21 18:16:27 +00003168 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3169
3170 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003171 llvm::SmallString<36> Name;
3172 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3173 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003174 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003175 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003176 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003177 T->startDefinition();
3178 QualType Int32Ty = IntTy;
3179 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3180 QualType FieldTypes[] = {
3181 getPointerType(VoidPtrTy),
3182 getPointerType(getTagDeclType(T)),
3183 Int32Ty,
3184 Int32Ty,
3185 getPointerType(VoidPtrTy),
3186 getPointerType(VoidPtrTy),
3187 Ty
3188 };
3189
3190 const char *FieldNames[] = {
3191 "__isa",
3192 "__forwarding",
3193 "__flags",
3194 "__size",
3195 "__copy_helper",
3196 "__destroy_helper",
3197 DeclName,
3198 };
3199
3200 for (size_t i = 0; i < 7; ++i) {
3201 if (!HasCopyAndDispose && i >=4 && i <= 5)
3202 continue;
3203 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3204 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003205 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003206 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003207 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003208 T->addDecl(Field);
3209 }
3210
Douglas Gregord5058122010-02-11 01:19:42 +00003211 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003212
3213 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003214}
3215
3216
3217QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003218 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003219 llvm::SmallVectorImpl<const Expr *> &Layout) {
3220
Mike Stumpd0153282009-10-20 02:12:22 +00003221 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003222 llvm::SmallString<36> Name;
3223 llvm::raw_svector_ostream(Name) << "__block_literal_"
3224 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003225 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003226 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003227 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003228 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003229 QualType FieldTypes[] = {
3230 getPointerType(VoidPtrTy),
3231 IntTy,
3232 IntTy,
3233 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003234 (BlockHasCopyDispose ?
3235 getPointerType(getBlockDescriptorExtendedType()) :
3236 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003237 };
3238
3239 const char *FieldNames[] = {
3240 "__isa",
3241 "__flags",
3242 "__reserved",
3243 "__FuncPtr",
3244 "__descriptor"
3245 };
3246
3247 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003248 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003249 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003250 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003251 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003252 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003253 T->addDecl(Field);
3254 }
3255
John McCall87fe5d52010-05-20 01:18:31 +00003256 for (unsigned i = 0; i < Layout.size(); ++i) {
3257 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003258
John McCall87fe5d52010-05-20 01:18:31 +00003259 QualType FieldType = E->getType();
3260 IdentifierInfo *FieldName = 0;
3261 if (isa<CXXThisExpr>(E)) {
3262 FieldName = &Idents.get("this");
3263 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3264 const ValueDecl *D = BDRE->getDecl();
3265 FieldName = D->getIdentifier();
3266 if (BDRE->isByRef())
3267 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3268 } else {
3269 // Padding.
3270 assert(isa<ConstantArrayType>(FieldType) &&
3271 isa<DeclRefExpr>(E) &&
3272 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3273 "doesn't match characteristics of padding decl");
3274 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003275
3276 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003277 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003278 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003279 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003280 T->addDecl(Field);
3281 }
3282
Douglas Gregord5058122010-02-11 01:19:42 +00003283 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003284
3285 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003286}
3287
Douglas Gregor512b0772009-04-23 22:29:11 +00003288void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003289 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003290 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3291 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3292}
3293
Anders Carlsson18acd442007-10-29 06:33:42 +00003294// This returns true if a type has been typedefed to BOOL:
3295// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003296static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003297 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003298 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3299 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003300
Anders Carlssond8499822007-10-29 05:01:08 +00003301 return false;
3302}
3303
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003304/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003305/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003306CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003307 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003308
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003309 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003310 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003311 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003312 // Treat arrays as pointers, since that's how they're passed in.
3313 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003314 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003315 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003316}
3317
3318static inline
3319std::string charUnitsToString(const CharUnits &CU) {
3320 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003321}
3322
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003323/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003324/// declaration.
3325void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3326 std::string& S) {
3327 const BlockDecl *Decl = Expr->getBlockDecl();
3328 QualType BlockTy =
3329 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3330 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003331 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003332 // Compute size of all parameters.
3333 // Start with computing size of a pointer in number of bytes.
3334 // FIXME: There might(should) be a better way of doing this computation!
3335 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003336 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3337 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003338 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003339 E = Decl->param_end(); PI != E; ++PI) {
3340 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003341 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003342 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003343 ParmOffset += sz;
3344 }
3345 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003346 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003347 // Block pointer and offset.
3348 S += "@?0";
3349 ParmOffset = PtrSize;
3350
3351 // Argument types.
3352 ParmOffset = PtrSize;
3353 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3354 Decl->param_end(); PI != E; ++PI) {
3355 ParmVarDecl *PVDecl = *PI;
3356 QualType PType = PVDecl->getOriginalType();
3357 if (const ArrayType *AT =
3358 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3359 // Use array's original type only if it has known number of
3360 // elements.
3361 if (!isa<ConstantArrayType>(AT))
3362 PType = PVDecl->getType();
3363 } else if (PType->isFunctionType())
3364 PType = PVDecl->getType();
3365 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003366 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003367 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003368 }
3369}
3370
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003371/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003372/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003373void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003374 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003375 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003376 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003377 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003378 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003379 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003380 // Compute size of all parameters.
3381 // Start with computing size of a pointer in number of bytes.
3382 // FIXME: There might(should) be a better way of doing this computation!
3383 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003384 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003385 // The first two arguments (self and _cmd) are pointers; account for
3386 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003387 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003388 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003389 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003390 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003391 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003392 assert (sz.isPositive() &&
3393 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003394 ParmOffset += sz;
3395 }
Ken Dyck40775002010-01-11 17:06:35 +00003396 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003397 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003398 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003399
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003400 // Argument types.
3401 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003402 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003403 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003404 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003405 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003406 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003407 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3408 // Use array's original type only if it has known number of
3409 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003410 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003411 PType = PVDecl->getType();
3412 } else if (PType->isFunctionType())
3413 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003414 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003415 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003416 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003417 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003418 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003419 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003420 }
3421}
3422
Daniel Dunbar4932b362008-08-28 04:38:10 +00003423/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003424/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003425/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3426/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003427/// Property attributes are stored as a comma-delimited C string. The simple
3428/// attributes readonly and bycopy are encoded as single characters. The
3429/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3430/// encoded as single characters, followed by an identifier. Property types
3431/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003432/// these attributes are defined by the following enumeration:
3433/// @code
3434/// enum PropertyAttributes {
3435/// kPropertyReadOnly = 'R', // property is read-only.
3436/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3437/// kPropertyByref = '&', // property is a reference to the value last assigned
3438/// kPropertyDynamic = 'D', // property is dynamic
3439/// kPropertyGetter = 'G', // followed by getter selector name
3440/// kPropertySetter = 'S', // followed by setter selector name
3441/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3442/// kPropertyType = 't' // followed by old-style type encoding.
3443/// kPropertyWeak = 'W' // 'weak' property
3444/// kPropertyStrong = 'P' // property GC'able
3445/// kPropertyNonAtomic = 'N' // property non-atomic
3446/// };
3447/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003448void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003449 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003450 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003451 // Collect information from the property implementation decl(s).
3452 bool Dynamic = false;
3453 ObjCPropertyImplDecl *SynthesizePID = 0;
3454
3455 // FIXME: Duplicated code due to poor abstraction.
3456 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003457 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003458 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3459 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003460 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003461 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003462 ObjCPropertyImplDecl *PID = *i;
3463 if (PID->getPropertyDecl() == PD) {
3464 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3465 Dynamic = true;
3466 } else {
3467 SynthesizePID = PID;
3468 }
3469 }
3470 }
3471 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003472 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003473 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003474 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003475 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003476 ObjCPropertyImplDecl *PID = *i;
3477 if (PID->getPropertyDecl() == PD) {
3478 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3479 Dynamic = true;
3480 } else {
3481 SynthesizePID = PID;
3482 }
3483 }
Mike Stump11289f42009-09-09 15:08:12 +00003484 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003485 }
3486 }
3487
3488 // FIXME: This is not very efficient.
3489 S = "T";
3490
3491 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003492 // GCC has some special rules regarding encoding of properties which
3493 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003494 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003495 true /* outermost type */,
3496 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003497
3498 if (PD->isReadOnly()) {
3499 S += ",R";
3500 } else {
3501 switch (PD->getSetterKind()) {
3502 case ObjCPropertyDecl::Assign: break;
3503 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003504 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003505 }
3506 }
3507
3508 // It really isn't clear at all what this means, since properties
3509 // are "dynamic by default".
3510 if (Dynamic)
3511 S += ",D";
3512
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003513 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3514 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003515
Daniel Dunbar4932b362008-08-28 04:38:10 +00003516 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3517 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003518 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003519 }
3520
3521 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3522 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003523 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003524 }
3525
3526 if (SynthesizePID) {
3527 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3528 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003529 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003530 }
3531
3532 // FIXME: OBJCGC: weak & strong
3533}
3534
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003535/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003536/// Another legacy compatibility encoding: 32-bit longs are encoded as
3537/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003538/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3539///
3540void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003541 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003542 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003543 if (BT->getKind() == BuiltinType::ULong &&
3544 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003545 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003546 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003547 if (BT->getKind() == BuiltinType::Long &&
3548 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003549 PointeeTy = IntTy;
3550 }
3551 }
3552}
3553
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003554void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003555 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003556 // We follow the behavior of gcc, expanding structures which are
3557 // directly pointed to, and expanding embedded structures. Note that
3558 // these rules are sufficient to prevent recursive encoding of the
3559 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003560 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003561 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003562}
3563
David Chisnallb190a2c2010-06-04 01:10:52 +00003564static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3565 switch (T->getAs<BuiltinType>()->getKind()) {
3566 default: assert(0 && "Unhandled builtin type kind");
3567 case BuiltinType::Void: return 'v';
3568 case BuiltinType::Bool: return 'B';
3569 case BuiltinType::Char_U:
3570 case BuiltinType::UChar: return 'C';
3571 case BuiltinType::UShort: return 'S';
3572 case BuiltinType::UInt: return 'I';
3573 case BuiltinType::ULong:
3574 return
3575 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3576 case BuiltinType::UInt128: return 'T';
3577 case BuiltinType::ULongLong: return 'Q';
3578 case BuiltinType::Char_S:
3579 case BuiltinType::SChar: return 'c';
3580 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003581 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003582 case BuiltinType::Int: return 'i';
3583 case BuiltinType::Long:
3584 return
3585 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3586 case BuiltinType::LongLong: return 'q';
3587 case BuiltinType::Int128: return 't';
3588 case BuiltinType::Float: return 'f';
3589 case BuiltinType::Double: return 'd';
3590 case BuiltinType::LongDouble: return 'd';
3591 }
3592}
3593
Mike Stump11289f42009-09-09 15:08:12 +00003594static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003595 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003596 const Expr *E = FD->getBitWidth();
3597 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3598 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003599 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003600 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3601 // The GNU runtime requires more information; bitfields are encoded as b,
3602 // then the offset (in bits) of the first element, then the type of the
3603 // bitfield, then the size in bits. For example, in this structure:
3604 //
3605 // struct
3606 // {
3607 // int integer;
3608 // int flags:2;
3609 // };
3610 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3611 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3612 // information is not especially sensible, but we're stuck with it for
3613 // compatibility with GCC, although providing it breaks anything that
3614 // actually uses runtime introspection and wants to work on both runtimes...
3615 if (!Ctx->getLangOptions().NeXTRuntime) {
3616 const RecordDecl *RD = FD->getParent();
3617 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3618 // FIXME: This same linear search is also used in ExprConstant - it might
3619 // be better if the FieldDecl stored its offset. We'd be increasing the
3620 // size of the object slightly, but saving some time every time it is used.
3621 unsigned i = 0;
3622 for (RecordDecl::field_iterator Field = RD->field_begin(),
3623 FieldEnd = RD->field_end();
3624 Field != FieldEnd; (void)++Field, ++i) {
3625 if (*Field == FD)
3626 break;
3627 }
3628 S += llvm::utostr(RL.getFieldOffset(i));
3629 S += ObjCEncodingForPrimitiveKind(Context, T);
3630 }
3631 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003632 S += llvm::utostr(N);
3633}
3634
Daniel Dunbar07d07852009-10-18 21:17:35 +00003635// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003636void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3637 bool ExpandPointedToStructures,
3638 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003639 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003640 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003641 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003642 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003643 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003644 return EncodeBitField(this, S, T, FD);
3645 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003646 return;
3647 }
Mike Stump11289f42009-09-09 15:08:12 +00003648
John McCall9dd450b2009-09-21 23:43:11 +00003649 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003650 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003651 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003652 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003653 return;
3654 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003655
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003656 // encoding for pointer or r3eference types.
3657 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003658 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003659 if (PT->isObjCSelType()) {
3660 S += ':';
3661 return;
3662 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003663 PointeeTy = PT->getPointeeType();
3664 }
3665 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3666 PointeeTy = RT->getPointeeType();
3667 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003668 bool isReadOnly = false;
3669 // For historical/compatibility reasons, the read-only qualifier of the
3670 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3671 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003672 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003673 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003674 if (OutermostType && T.isConstQualified()) {
3675 isReadOnly = true;
3676 S += 'r';
3677 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003678 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003679 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003680 while (P->getAs<PointerType>())
3681 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003682 if (P.isConstQualified()) {
3683 isReadOnly = true;
3684 S += 'r';
3685 }
3686 }
3687 if (isReadOnly) {
3688 // Another legacy compatibility encoding. Some ObjC qualifier and type
3689 // combinations need to be rearranged.
3690 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003691 if (llvm::StringRef(S).endswith("nr"))
3692 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003693 }
Mike Stump11289f42009-09-09 15:08:12 +00003694
Anders Carlssond8499822007-10-29 05:01:08 +00003695 if (PointeeTy->isCharType()) {
3696 // char pointer types should be encoded as '*' unless it is a
3697 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003698 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003699 S += '*';
3700 return;
3701 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003702 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003703 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3704 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3705 S += '#';
3706 return;
3707 }
3708 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3709 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3710 S += '@';
3711 return;
3712 }
3713 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003714 }
Anders Carlssond8499822007-10-29 05:01:08 +00003715 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003716 getLegacyIntegralTypeEncoding(PointeeTy);
3717
Mike Stump11289f42009-09-09 15:08:12 +00003718 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003719 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003720 return;
3721 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003722
Chris Lattnere7cabb92009-07-13 00:10:46 +00003723 if (const ArrayType *AT =
3724 // Ignore type qualifiers etc.
3725 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003726 if (isa<IncompleteArrayType>(AT)) {
3727 // Incomplete arrays are encoded as a pointer to the array element.
3728 S += '^';
3729
Mike Stump11289f42009-09-09 15:08:12 +00003730 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003731 false, ExpandStructures, FD);
3732 } else {
3733 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003734
Anders Carlssond05f44b2009-02-22 01:38:57 +00003735 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3736 S += llvm::utostr(CAT->getSize().getZExtValue());
3737 else {
3738 //Variable length arrays are encoded as a regular array with 0 elements.
3739 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3740 S += '0';
3741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
3743 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003744 false, ExpandStructures, FD);
3745 S += ']';
3746 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003747 return;
3748 }
Mike Stump11289f42009-09-09 15:08:12 +00003749
John McCall9dd450b2009-09-21 23:43:11 +00003750 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003751 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003752 return;
3753 }
Mike Stump11289f42009-09-09 15:08:12 +00003754
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003755 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003756 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003757 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003758 // Anonymous structures print as '?'
3759 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3760 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003761 if (ClassTemplateSpecializationDecl *Spec
3762 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3763 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3764 std::string TemplateArgsStr
3765 = TemplateSpecializationType::PrintTemplateArgumentList(
3766 TemplateArgs.getFlatArgumentList(),
3767 TemplateArgs.flat_size(),
3768 (*this).PrintingPolicy);
3769
3770 S += TemplateArgsStr;
3771 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003772 } else {
3773 S += '?';
3774 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003775 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003776 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003777 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3778 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003779 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003780 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003781 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003782 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003783 S += '"';
3784 }
Mike Stump11289f42009-09-09 15:08:12 +00003785
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003786 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003787 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003788 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003789 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003790 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003791 QualType qt = Field->getType();
3792 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003793 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003794 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003795 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003796 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003797 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003798 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003799 return;
3800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Chris Lattnere7cabb92009-07-13 00:10:46 +00003802 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003803 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003804 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003805 else
3806 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003807 return;
3808 }
Mike Stump11289f42009-09-09 15:08:12 +00003809
Chris Lattnere7cabb92009-07-13 00:10:46 +00003810 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003811 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003812 return;
3813 }
Mike Stump11289f42009-09-09 15:08:12 +00003814
John McCall8b07ec22010-05-15 11:32:37 +00003815 // Ignore protocol qualifiers when mangling at this level.
3816 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3817 T = OT->getBaseType();
3818
John McCall8ccfcb52009-09-24 19:53:00 +00003819 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003820 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003821 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003822 S += '{';
3823 const IdentifierInfo *II = OI->getIdentifier();
3824 S += II->getName();
3825 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003826 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003827 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003828 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003829 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003830 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003831 RecFields[i]);
3832 else
Mike Stump11289f42009-09-09 15:08:12 +00003833 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003834 FD);
3835 }
3836 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003837 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003838 }
Mike Stump11289f42009-09-09 15:08:12 +00003839
John McCall9dd450b2009-09-21 23:43:11 +00003840 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003841 if (OPT->isObjCIdType()) {
3842 S += '@';
3843 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003844 }
Mike Stump11289f42009-09-09 15:08:12 +00003845
Steve Narofff0c86112009-10-28 22:03:49 +00003846 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3847 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3848 // Since this is a binary compatibility issue, need to consult with runtime
3849 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003850 S += '#';
3851 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003852 }
Mike Stump11289f42009-09-09 15:08:12 +00003853
Chris Lattnere7cabb92009-07-13 00:10:46 +00003854 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003855 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003856 ExpandPointedToStructures,
3857 ExpandStructures, FD);
3858 if (FD || EncodingProperty) {
3859 // Note that we do extended encoding of protocol qualifer list
3860 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003861 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003862 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3863 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003864 S += '<';
3865 S += (*I)->getNameAsString();
3866 S += '>';
3867 }
3868 S += '"';
3869 }
3870 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003871 }
Mike Stump11289f42009-09-09 15:08:12 +00003872
Chris Lattnere7cabb92009-07-13 00:10:46 +00003873 QualType PointeeTy = OPT->getPointeeType();
3874 if (!EncodingProperty &&
3875 isa<TypedefType>(PointeeTy.getTypePtr())) {
3876 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003877 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003878 // {...};
3879 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003880 getObjCEncodingForTypeImpl(PointeeTy, S,
3881 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003882 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003883 return;
3884 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003885
3886 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003887 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003888 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003889 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003890 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3891 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003892 S += '<';
3893 S += (*I)->getNameAsString();
3894 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003895 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003896 S += '"';
3897 }
3898 return;
3899 }
Mike Stump11289f42009-09-09 15:08:12 +00003900
John McCalla9e6e8d2010-05-17 23:56:34 +00003901 // gcc just blithely ignores member pointers.
3902 // TODO: maybe there should be a mangling for these
3903 if (T->getAs<MemberPointerType>())
3904 return;
3905
Chris Lattnere7cabb92009-07-13 00:10:46 +00003906 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003907}
3908
Mike Stump11289f42009-09-09 15:08:12 +00003909void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003910 std::string& S) const {
3911 if (QT & Decl::OBJC_TQ_In)
3912 S += 'n';
3913 if (QT & Decl::OBJC_TQ_Inout)
3914 S += 'N';
3915 if (QT & Decl::OBJC_TQ_Out)
3916 S += 'o';
3917 if (QT & Decl::OBJC_TQ_Bycopy)
3918 S += 'O';
3919 if (QT & Decl::OBJC_TQ_Byref)
3920 S += 'R';
3921 if (QT & Decl::OBJC_TQ_Oneway)
3922 S += 'V';
3923}
3924
Chris Lattnere7cabb92009-07-13 00:10:46 +00003925void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003926 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003927
Anders Carlsson87c149b2007-10-11 01:00:40 +00003928 BuiltinVaListType = T;
3929}
3930
Chris Lattnere7cabb92009-07-13 00:10:46 +00003931void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003932 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003933}
3934
Chris Lattnere7cabb92009-07-13 00:10:46 +00003935void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003936 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003937}
3938
Chris Lattnere7cabb92009-07-13 00:10:46 +00003939void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003940 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003941}
3942
Chris Lattnere7cabb92009-07-13 00:10:46 +00003943void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003944 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003945}
3946
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003947void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003948 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003949 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003950
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003951 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003952}
3953
John McCalld28ae272009-12-02 08:04:21 +00003954/// \brief Retrieve the template name that corresponds to a non-empty
3955/// lookup.
John McCallad371252010-01-20 00:46:10 +00003956TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3957 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003958 unsigned size = End - Begin;
3959 assert(size > 1 && "set is not overloaded!");
3960
3961 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3962 size * sizeof(FunctionTemplateDecl*));
3963 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3964
3965 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003966 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003967 NamedDecl *D = *I;
3968 assert(isa<FunctionTemplateDecl>(D) ||
3969 (isa<UsingShadowDecl>(D) &&
3970 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3971 *Storage++ = D;
3972 }
3973
3974 return TemplateName(OT);
3975}
3976
Douglas Gregordc572a32009-03-30 22:58:21 +00003977/// \brief Retrieve the template name that represents a qualified
3978/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003979TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003980 bool TemplateKeyword,
3981 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003982 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003983 llvm::FoldingSetNodeID ID;
3984 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3985
3986 void *InsertPos = 0;
3987 QualifiedTemplateName *QTN =
3988 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3989 if (!QTN) {
3990 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3991 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3992 }
3993
3994 return TemplateName(QTN);
3995}
3996
3997/// \brief Retrieve the template name that represents a dependent
3998/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003999TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004000 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004001 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004002 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004003
4004 llvm::FoldingSetNodeID ID;
4005 DependentTemplateName::Profile(ID, NNS, Name);
4006
4007 void *InsertPos = 0;
4008 DependentTemplateName *QTN =
4009 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4010
4011 if (QTN)
4012 return TemplateName(QTN);
4013
4014 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4015 if (CanonNNS == NNS) {
4016 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4017 } else {
4018 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4019 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004020 DependentTemplateName *CheckQTN =
4021 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4022 assert(!CheckQTN && "Dependent type name canonicalization broken");
4023 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004024 }
4025
4026 DependentTemplateNames.InsertNode(QTN, InsertPos);
4027 return TemplateName(QTN);
4028}
4029
Douglas Gregor71395fa2009-11-04 00:56:37 +00004030/// \brief Retrieve the template name that represents a dependent
4031/// template name such as \c MetaFun::template operator+.
4032TemplateName
4033ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4034 OverloadedOperatorKind Operator) {
4035 assert((!NNS || NNS->isDependent()) &&
4036 "Nested name specifier must be dependent");
4037
4038 llvm::FoldingSetNodeID ID;
4039 DependentTemplateName::Profile(ID, NNS, Operator);
4040
4041 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004042 DependentTemplateName *QTN
4043 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004044
4045 if (QTN)
4046 return TemplateName(QTN);
4047
4048 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4049 if (CanonNNS == NNS) {
4050 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4051 } else {
4052 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4053 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004054
4055 DependentTemplateName *CheckQTN
4056 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4057 assert(!CheckQTN && "Dependent template name canonicalization broken");
4058 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004059 }
4060
4061 DependentTemplateNames.InsertNode(QTN, InsertPos);
4062 return TemplateName(QTN);
4063}
4064
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004065/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004066/// TargetInfo, produce the corresponding type. The unsigned @p Type
4067/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004068CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004069 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004070 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004071 case TargetInfo::SignedShort: return ShortTy;
4072 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4073 case TargetInfo::SignedInt: return IntTy;
4074 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4075 case TargetInfo::SignedLong: return LongTy;
4076 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4077 case TargetInfo::SignedLongLong: return LongLongTy;
4078 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4079 }
4080
4081 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004082 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004083}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004084
4085//===----------------------------------------------------------------------===//
4086// Type Predicates.
4087//===----------------------------------------------------------------------===//
4088
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004089/// isObjCNSObjectType - Return true if this is an NSObject object using
4090/// NSObject attribute on a c-style pointer type.
4091/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004092/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004093///
4094bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4095 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4096 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004097 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004098 return true;
4099 }
Mike Stump11289f42009-09-09 15:08:12 +00004100 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004101}
4102
Fariborz Jahanian96207692009-02-18 21:49:28 +00004103/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4104/// garbage collection attribute.
4105///
John McCall8ccfcb52009-09-24 19:53:00 +00004106Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4107 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004108 if (getLangOptions().ObjC1 &&
4109 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004110 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004111 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004112 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004113 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004114 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004115 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004116 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004117 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004118 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004119 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004120 // Non-pointers have none gc'able attribute regardless of the attribute
4121 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004122 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004123 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004124 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004125 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004126}
4127
Chris Lattner49af6a42008-04-07 06:51:04 +00004128//===----------------------------------------------------------------------===//
4129// Type Compatibility Testing
4130//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004131
Mike Stump11289f42009-09-09 15:08:12 +00004132/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004133/// compatible.
4134static bool areCompatVectorTypes(const VectorType *LHS,
4135 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004136 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004137 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004138 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004139}
4140
Steve Naroff8e6aee52009-07-23 01:01:38 +00004141//===----------------------------------------------------------------------===//
4142// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4143//===----------------------------------------------------------------------===//
4144
4145/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4146/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004147bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4148 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004149 if (lProto == rProto)
4150 return true;
4151 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4152 E = rProto->protocol_end(); PI != E; ++PI)
4153 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4154 return true;
4155 return false;
4156}
4157
Steve Naroff8e6aee52009-07-23 01:01:38 +00004158/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4159/// return true if lhs's protocols conform to rhs's protocol; false
4160/// otherwise.
4161bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4162 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4163 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4164 return false;
4165}
4166
4167/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4168/// ObjCQualifiedIDType.
4169bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4170 bool compare) {
4171 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004172 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004173 lhs->isObjCIdType() || lhs->isObjCClassType())
4174 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004175 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004176 rhs->isObjCIdType() || rhs->isObjCClassType())
4177 return true;
4178
4179 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004180 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004181
Steve Naroff8e6aee52009-07-23 01:01:38 +00004182 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004183
Steve Naroff8e6aee52009-07-23 01:01:38 +00004184 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004185 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004186 // make sure we check the class hierarchy.
4187 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4188 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4189 E = lhsQID->qual_end(); I != E; ++I) {
4190 // when comparing an id<P> on lhs with a static type on rhs,
4191 // see if static class implements all of id's protocols, directly or
4192 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004193 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004194 return false;
4195 }
4196 }
4197 // If there are no qualifiers and no interface, we have an 'id'.
4198 return true;
4199 }
Mike Stump11289f42009-09-09 15:08:12 +00004200 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004201 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4202 E = lhsQID->qual_end(); I != E; ++I) {
4203 ObjCProtocolDecl *lhsProto = *I;
4204 bool match = false;
4205
4206 // when comparing an id<P> on lhs with a static type on rhs,
4207 // see if static class implements all of id's protocols, directly or
4208 // through its super class and categories.
4209 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4210 E = rhsOPT->qual_end(); J != E; ++J) {
4211 ObjCProtocolDecl *rhsProto = *J;
4212 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4213 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4214 match = true;
4215 break;
4216 }
4217 }
Mike Stump11289f42009-09-09 15:08:12 +00004218 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004219 // make sure we check the class hierarchy.
4220 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4221 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4222 E = lhsQID->qual_end(); I != E; ++I) {
4223 // when comparing an id<P> on lhs with a static type on rhs,
4224 // see if static class implements all of id's protocols, directly or
4225 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004226 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004227 match = true;
4228 break;
4229 }
4230 }
4231 }
4232 if (!match)
4233 return false;
4234 }
Mike Stump11289f42009-09-09 15:08:12 +00004235
Steve Naroff8e6aee52009-07-23 01:01:38 +00004236 return true;
4237 }
Mike Stump11289f42009-09-09 15:08:12 +00004238
Steve Naroff8e6aee52009-07-23 01:01:38 +00004239 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4240 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4241
Mike Stump11289f42009-09-09 15:08:12 +00004242 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004243 lhs->getAsObjCInterfacePointerType()) {
4244 if (lhsOPT->qual_empty()) {
4245 bool match = false;
4246 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4247 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4248 E = rhsQID->qual_end(); I != E; ++I) {
4249 // when comparing an id<P> on lhs with a static type on rhs,
4250 // see if static class implements all of id's protocols, directly or
4251 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004252 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004253 match = true;
4254 break;
4255 }
4256 }
4257 if (!match)
4258 return false;
4259 }
4260 return true;
4261 }
Mike Stump11289f42009-09-09 15:08:12 +00004262 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004263 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4264 E = lhsOPT->qual_end(); I != E; ++I) {
4265 ObjCProtocolDecl *lhsProto = *I;
4266 bool match = false;
4267
4268 // when comparing an id<P> on lhs with a static type on rhs,
4269 // see if static class implements all of id's protocols, directly or
4270 // through its super class and categories.
4271 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4272 E = rhsQID->qual_end(); J != E; ++J) {
4273 ObjCProtocolDecl *rhsProto = *J;
4274 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4275 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4276 match = true;
4277 break;
4278 }
4279 }
4280 if (!match)
4281 return false;
4282 }
4283 return true;
4284 }
4285 return false;
4286}
4287
Eli Friedman47f77112008-08-22 00:56:42 +00004288/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004289/// compatible for assignment from RHS to LHS. This handles validation of any
4290/// protocol qualifiers on the LHS or RHS.
4291///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004292bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4293 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004294 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4295 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4296
Steve Naroff1329fa02009-07-15 18:40:39 +00004297 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004298 if (LHS->isObjCUnqualifiedIdOrClass() ||
4299 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004300 return true;
4301
John McCall8b07ec22010-05-15 11:32:37 +00004302 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004303 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4304 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004305 false);
4306
John McCall8b07ec22010-05-15 11:32:37 +00004307 // If we have 2 user-defined types, fall into that path.
4308 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004309 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004310
Steve Naroff8e6aee52009-07-23 01:01:38 +00004311 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004312}
4313
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004314/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4315/// for providing type-safty for objective-c pointers used to pass/return
4316/// arguments in block literals. When passed as arguments, passing 'A*' where
4317/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4318/// not OK. For the return type, the opposite is not OK.
4319bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4320 const ObjCObjectPointerType *LHSOPT,
4321 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004322 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004323 return true;
4324
4325 if (LHSOPT->isObjCBuiltinType()) {
4326 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4327 }
4328
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004329 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004330 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4331 QualType(RHSOPT,0),
4332 false);
4333
4334 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4335 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4336 if (LHS && RHS) { // We have 2 user-defined types.
4337 if (LHS != RHS) {
4338 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4339 return false;
4340 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4341 return true;
4342 }
4343 else
4344 return true;
4345 }
4346 return false;
4347}
4348
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004349/// getIntersectionOfProtocols - This routine finds the intersection of set
4350/// of protocols inherited from two distinct objective-c pointer objects.
4351/// It is used to build composite qualifier list of the composite type of
4352/// the conditional expression involving two objective-c pointer objects.
4353static
4354void getIntersectionOfProtocols(ASTContext &Context,
4355 const ObjCObjectPointerType *LHSOPT,
4356 const ObjCObjectPointerType *RHSOPT,
4357 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4358
John McCall8b07ec22010-05-15 11:32:37 +00004359 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4360 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4361 assert(LHS->getInterface() && "LHS must have an interface base");
4362 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004363
4364 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4365 unsigned LHSNumProtocols = LHS->getNumProtocols();
4366 if (LHSNumProtocols > 0)
4367 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4368 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004369 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004370 Context.CollectInheritedProtocols(LHS->getInterface(),
4371 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004372 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4373 LHSInheritedProtocols.end());
4374 }
4375
4376 unsigned RHSNumProtocols = RHS->getNumProtocols();
4377 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004378 ObjCProtocolDecl **RHSProtocols =
4379 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004380 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4381 if (InheritedProtocolSet.count(RHSProtocols[i]))
4382 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4383 }
4384 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004385 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004386 Context.CollectInheritedProtocols(RHS->getInterface(),
4387 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004388 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4389 RHSInheritedProtocols.begin(),
4390 E = RHSInheritedProtocols.end(); I != E; ++I)
4391 if (InheritedProtocolSet.count((*I)))
4392 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004393 }
4394}
4395
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004396/// areCommonBaseCompatible - Returns common base class of the two classes if
4397/// one found. Note that this is O'2 algorithm. But it will be called as the
4398/// last type comparison in a ?-exp of ObjC pointer types before a
4399/// warning is issued. So, its invokation is extremely rare.
4400QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004401 const ObjCObjectPointerType *Lptr,
4402 const ObjCObjectPointerType *Rptr) {
4403 const ObjCObjectType *LHS = Lptr->getObjectType();
4404 const ObjCObjectType *RHS = Rptr->getObjectType();
4405 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4406 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4407 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004408 return QualType();
4409
John McCall8b07ec22010-05-15 11:32:37 +00004410 while ((LDecl = LDecl->getSuperClass())) {
4411 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004412 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004413 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4414 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4415
4416 QualType Result = QualType(LHS, 0);
4417 if (!Protocols.empty())
4418 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4419 Result = getObjCObjectPointerType(Result);
4420 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004421 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004422 }
4423
4424 return QualType();
4425}
4426
John McCall8b07ec22010-05-15 11:32:37 +00004427bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4428 const ObjCObjectType *RHS) {
4429 assert(LHS->getInterface() && "LHS is not an interface type");
4430 assert(RHS->getInterface() && "RHS is not an interface type");
4431
Chris Lattner49af6a42008-04-07 06:51:04 +00004432 // Verify that the base decls are compatible: the RHS must be a subclass of
4433 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004434 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004435 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004436
Chris Lattner49af6a42008-04-07 06:51:04 +00004437 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4438 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004439 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004440 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004441
Chris Lattner49af6a42008-04-07 06:51:04 +00004442 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4443 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004444 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004445 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004446
John McCall8b07ec22010-05-15 11:32:37 +00004447 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4448 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004449 LHSPI != LHSPE; LHSPI++) {
4450 bool RHSImplementsProtocol = false;
4451
4452 // If the RHS doesn't implement the protocol on the left, the types
4453 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004454 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4455 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004456 RHSPI != RHSPE; RHSPI++) {
4457 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004458 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004459 break;
4460 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004461 }
4462 // FIXME: For better diagnostics, consider passing back the protocol name.
4463 if (!RHSImplementsProtocol)
4464 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004465 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004466 // The RHS implements all protocols listed on the LHS.
4467 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004468}
4469
Steve Naroffb7605152009-02-12 17:52:19 +00004470bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4471 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004472 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4473 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004474
Steve Naroff7cae42b2009-07-10 23:34:53 +00004475 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004476 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004477
4478 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4479 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004480}
4481
Mike Stump11289f42009-09-09 15:08:12 +00004482/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004483/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004484/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004485/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004486bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004487 if (getLangOptions().CPlusPlus)
4488 return hasSameType(LHS, RHS);
4489
Eli Friedman47f77112008-08-22 00:56:42 +00004490 return !mergeTypes(LHS, RHS).isNull();
4491}
4492
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004493bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4494 return !mergeTypes(LHS, RHS, true).isNull();
4495}
4496
4497QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4498 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004499 const FunctionType *lbase = lhs->getAs<FunctionType>();
4500 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004501 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4502 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004503 bool allLTypes = true;
4504 bool allRTypes = true;
4505
4506 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004507 QualType retType;
4508 if (OfBlockPointer)
4509 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4510 else
4511 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004512 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004513 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004514 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004515 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004516 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004517 // FIXME: double check this
4518 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4519 // rbase->getRegParmAttr() != 0 &&
4520 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004521 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4522 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004523 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4524 lbaseInfo.getRegParm();
4525 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4526 if (NoReturn != lbaseInfo.getNoReturn() ||
4527 RegParm != lbaseInfo.getRegParm())
4528 allLTypes = false;
4529 if (NoReturn != rbaseInfo.getNoReturn() ||
4530 RegParm != rbaseInfo.getRegParm())
4531 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004532 CallingConv lcc = lbaseInfo.getCC();
4533 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004534 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004535 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004536 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004537
Eli Friedman47f77112008-08-22 00:56:42 +00004538 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004539 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4540 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004541 unsigned lproto_nargs = lproto->getNumArgs();
4542 unsigned rproto_nargs = rproto->getNumArgs();
4543
4544 // Compatible functions must have the same number of arguments
4545 if (lproto_nargs != rproto_nargs)
4546 return QualType();
4547
4548 // Variadic and non-variadic functions aren't compatible
4549 if (lproto->isVariadic() != rproto->isVariadic())
4550 return QualType();
4551
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004552 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4553 return QualType();
4554
Eli Friedman47f77112008-08-22 00:56:42 +00004555 // Check argument compatibility
4556 llvm::SmallVector<QualType, 10> types;
4557 for (unsigned i = 0; i < lproto_nargs; i++) {
4558 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4559 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004560 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004561 if (argtype.isNull()) return QualType();
4562 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004563 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4564 allLTypes = false;
4565 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4566 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004567 }
4568 if (allLTypes) return lhs;
4569 if (allRTypes) return rhs;
4570 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004571 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004572 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004573 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004574 }
4575
4576 if (lproto) allRTypes = false;
4577 if (rproto) allLTypes = false;
4578
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004579 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004580 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004581 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004582 if (proto->isVariadic()) return QualType();
4583 // Check that the types are compatible with the types that
4584 // would result from default argument promotions (C99 6.7.5.3p15).
4585 // The only types actually affected are promotable integer
4586 // types and floats, which would be passed as a different
4587 // type depending on whether the prototype is visible.
4588 unsigned proto_nargs = proto->getNumArgs();
4589 for (unsigned i = 0; i < proto_nargs; ++i) {
4590 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004591
4592 // Look at the promotion type of enum types, since that is the type used
4593 // to pass enum values.
4594 if (const EnumType *Enum = argTy->getAs<EnumType>())
4595 argTy = Enum->getDecl()->getPromotionType();
4596
Eli Friedman47f77112008-08-22 00:56:42 +00004597 if (argTy->isPromotableIntegerType() ||
4598 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4599 return QualType();
4600 }
4601
4602 if (allLTypes) return lhs;
4603 if (allRTypes) return rhs;
4604 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004605 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004606 proto->getTypeQuals(),
4607 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004608 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004609 }
4610
4611 if (allLTypes) return lhs;
4612 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004613 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004614 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004615}
4616
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004617QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4618 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004619 // C++ [expr]: If an expression initially has the type "reference to T", the
4620 // type is adjusted to "T" prior to any further analysis, the expression
4621 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004622 // expression is an lvalue unless the reference is an rvalue reference and
4623 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004624 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4625 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4626
Eli Friedman47f77112008-08-22 00:56:42 +00004627 QualType LHSCan = getCanonicalType(LHS),
4628 RHSCan = getCanonicalType(RHS);
4629
4630 // If two types are identical, they are compatible.
4631 if (LHSCan == RHSCan)
4632 return LHS;
4633
John McCall8ccfcb52009-09-24 19:53:00 +00004634 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004635 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4636 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004637 if (LQuals != RQuals) {
4638 // If any of these qualifiers are different, we have a type
4639 // mismatch.
4640 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4641 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4642 return QualType();
4643
4644 // Exactly one GC qualifier difference is allowed: __strong is
4645 // okay if the other type has no GC qualifier but is an Objective
4646 // C object pointer (i.e. implicitly strong by default). We fix
4647 // this by pretending that the unqualified type was actually
4648 // qualified __strong.
4649 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4650 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4651 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4652
4653 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4654 return QualType();
4655
4656 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4657 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4658 }
4659 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4660 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4661 }
Eli Friedman47f77112008-08-22 00:56:42 +00004662 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004663 }
4664
4665 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004666
Eli Friedmandcca6332009-06-01 01:22:52 +00004667 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4668 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004669
Chris Lattnerfd652912008-01-14 05:45:46 +00004670 // We want to consider the two function types to be the same for these
4671 // comparisons, just force one to the other.
4672 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4673 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004674
4675 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004676 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4677 LHSClass = Type::ConstantArray;
4678 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4679 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004680
John McCall8b07ec22010-05-15 11:32:37 +00004681 // ObjCInterfaces are just specialized ObjCObjects.
4682 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4683 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4684
Nate Begemance4d7fc2008-04-18 23:10:10 +00004685 // Canonicalize ExtVector -> Vector.
4686 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4687 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004688
Chris Lattner95554662008-04-07 05:43:21 +00004689 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004690 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004691 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004692 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004693 // Compatibility is based on the underlying type, not the promotion
4694 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004695 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004696 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4697 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004698 }
John McCall9dd450b2009-09-21 23:43:11 +00004699 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004700 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4701 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004702 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004703
Eli Friedman47f77112008-08-22 00:56:42 +00004704 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004705 }
Eli Friedman47f77112008-08-22 00:56:42 +00004706
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004707 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004708 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004709#define TYPE(Class, Base)
4710#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004711#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004712#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4713#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4714#include "clang/AST/TypeNodes.def"
4715 assert(false && "Non-canonical and dependent types shouldn't get here");
4716 return QualType();
4717
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004718 case Type::LValueReference:
4719 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004720 case Type::MemberPointer:
4721 assert(false && "C++ should never be in mergeTypes");
4722 return QualType();
4723
John McCall8b07ec22010-05-15 11:32:37 +00004724 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004725 case Type::IncompleteArray:
4726 case Type::VariableArray:
4727 case Type::FunctionProto:
4728 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004729 assert(false && "Types are eliminated above");
4730 return QualType();
4731
Chris Lattnerfd652912008-01-14 05:45:46 +00004732 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004733 {
4734 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004735 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4736 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004737 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4738 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004739 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004740 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004741 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004742 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004743 return getPointerType(ResultType);
4744 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004745 case Type::BlockPointer:
4746 {
4747 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004748 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4749 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004750 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004751 if (ResultType.isNull()) return QualType();
4752 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4753 return LHS;
4754 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4755 return RHS;
4756 return getBlockPointerType(ResultType);
4757 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004758 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004759 {
4760 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4761 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4762 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4763 return QualType();
4764
4765 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4766 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4767 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4768 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004769 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4770 return LHS;
4771 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4772 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004773 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4774 ArrayType::ArraySizeModifier(), 0);
4775 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4776 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004777 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4778 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004779 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4780 return LHS;
4781 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4782 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004783 if (LVAT) {
4784 // FIXME: This isn't correct! But tricky to implement because
4785 // the array's size has to be the size of LHS, but the type
4786 // has to be different.
4787 return LHS;
4788 }
4789 if (RVAT) {
4790 // FIXME: This isn't correct! But tricky to implement because
4791 // the array's size has to be the size of RHS, but the type
4792 // has to be different.
4793 return RHS;
4794 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004795 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4796 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004797 return getIncompleteArrayType(ResultType,
4798 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004799 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004800 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004801 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004802 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004803 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004804 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004805 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004806 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004807 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004808 case Type::Complex:
4809 // Distinct complex types are incompatible.
4810 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004811 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004812 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004813 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4814 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004815 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004816 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004817 case Type::ObjCObject: {
4818 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004819 // FIXME: This should be type compatibility, e.g. whether
4820 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004821 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4822 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4823 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004824 return LHS;
4825
Eli Friedman47f77112008-08-22 00:56:42 +00004826 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004827 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004828 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004829 if (OfBlockPointer) {
4830 if (canAssignObjCInterfacesInBlockPointer(
4831 LHS->getAs<ObjCObjectPointerType>(),
4832 RHS->getAs<ObjCObjectPointerType>()))
4833 return LHS;
4834 return QualType();
4835 }
John McCall9dd450b2009-09-21 23:43:11 +00004836 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4837 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004838 return LHS;
4839
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004840 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004841 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004842 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004843
4844 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004845}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004846
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004847/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4848/// 'RHS' attributes and returns the merged version; including for function
4849/// return types.
4850QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4851 QualType LHSCan = getCanonicalType(LHS),
4852 RHSCan = getCanonicalType(RHS);
4853 // If two types are identical, they are compatible.
4854 if (LHSCan == RHSCan)
4855 return LHS;
4856 if (RHSCan->isFunctionType()) {
4857 if (!LHSCan->isFunctionType())
4858 return QualType();
4859 QualType OldReturnType =
4860 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4861 QualType NewReturnType =
4862 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4863 QualType ResReturnType =
4864 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4865 if (ResReturnType.isNull())
4866 return QualType();
4867 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4868 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4869 // In either case, use OldReturnType to build the new function type.
4870 const FunctionType *F = LHS->getAs<FunctionType>();
4871 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4872 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4873 QualType ResultType
4874 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4875 FPT->getNumArgs(), FPT->isVariadic(),
4876 FPT->getTypeQuals(),
4877 FPT->hasExceptionSpec(),
4878 FPT->hasAnyExceptionSpec(),
4879 FPT->getNumExceptions(),
4880 FPT->exception_begin(),
4881 Info);
4882 return ResultType;
4883 }
4884 }
4885 return QualType();
4886 }
4887
4888 // If the qualifiers are different, the types can still be merged.
4889 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4890 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4891 if (LQuals != RQuals) {
4892 // If any of these qualifiers are different, we have a type mismatch.
4893 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4894 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4895 return QualType();
4896
4897 // Exactly one GC qualifier difference is allowed: __strong is
4898 // okay if the other type has no GC qualifier but is an Objective
4899 // C object pointer (i.e. implicitly strong by default). We fix
4900 // this by pretending that the unqualified type was actually
4901 // qualified __strong.
4902 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4903 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4904 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4905
4906 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4907 return QualType();
4908
4909 if (GC_L == Qualifiers::Strong)
4910 return LHS;
4911 if (GC_R == Qualifiers::Strong)
4912 return RHS;
4913 return QualType();
4914 }
4915
4916 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4917 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4918 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4919 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4920 if (ResQT == LHSBaseQT)
4921 return LHS;
4922 if (ResQT == RHSBaseQT)
4923 return RHS;
4924 }
4925 return QualType();
4926}
4927
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004928//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004929// Integer Predicates
4930//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004931
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004932unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004933 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004934 return 1;
John McCall56774992009-12-09 09:09:27 +00004935 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004936 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004937 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004938 return (unsigned)getTypeSize(T);
4939}
4940
4941QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4942 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004943
4944 // Turn <4 x signed int> -> <4 x unsigned int>
4945 if (const VectorType *VTy = T->getAs<VectorType>())
4946 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00004947 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004948
4949 // For enums, we return the unsigned version of the base type.
4950 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004951 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004952
4953 const BuiltinType *BTy = T->getAs<BuiltinType>();
4954 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004955 switch (BTy->getKind()) {
4956 case BuiltinType::Char_S:
4957 case BuiltinType::SChar:
4958 return UnsignedCharTy;
4959 case BuiltinType::Short:
4960 return UnsignedShortTy;
4961 case BuiltinType::Int:
4962 return UnsignedIntTy;
4963 case BuiltinType::Long:
4964 return UnsignedLongTy;
4965 case BuiltinType::LongLong:
4966 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004967 case BuiltinType::Int128:
4968 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004969 default:
4970 assert(0 && "Unexpected signed integer type");
4971 return QualType();
4972 }
4973}
4974
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004975ExternalASTSource::~ExternalASTSource() { }
4976
4977void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004978
4979
4980//===----------------------------------------------------------------------===//
4981// Builtin Type Computation
4982//===----------------------------------------------------------------------===//
4983
4984/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4985/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004986static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004987 ASTContext::GetBuiltinTypeError &Error,
4988 bool AllowTypeModifiers = true) {
4989 // Modifiers.
4990 int HowLong = 0;
4991 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004992
Chris Lattnerecd79c62009-06-14 00:45:47 +00004993 // Read the modifiers first.
4994 bool Done = false;
4995 while (!Done) {
4996 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004997 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004998 case 'S':
4999 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5000 assert(!Signed && "Can't use 'S' modifier multiple times!");
5001 Signed = true;
5002 break;
5003 case 'U':
5004 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5005 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5006 Unsigned = true;
5007 break;
5008 case 'L':
5009 assert(HowLong <= 2 && "Can't have LLLL modifier");
5010 ++HowLong;
5011 break;
5012 }
5013 }
5014
5015 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005016
Chris Lattnerecd79c62009-06-14 00:45:47 +00005017 // Read the base type.
5018 switch (*Str++) {
5019 default: assert(0 && "Unknown builtin type letter!");
5020 case 'v':
5021 assert(HowLong == 0 && !Signed && !Unsigned &&
5022 "Bad modifiers used with 'v'!");
5023 Type = Context.VoidTy;
5024 break;
5025 case 'f':
5026 assert(HowLong == 0 && !Signed && !Unsigned &&
5027 "Bad modifiers used with 'f'!");
5028 Type = Context.FloatTy;
5029 break;
5030 case 'd':
5031 assert(HowLong < 2 && !Signed && !Unsigned &&
5032 "Bad modifiers used with 'd'!");
5033 if (HowLong)
5034 Type = Context.LongDoubleTy;
5035 else
5036 Type = Context.DoubleTy;
5037 break;
5038 case 's':
5039 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5040 if (Unsigned)
5041 Type = Context.UnsignedShortTy;
5042 else
5043 Type = Context.ShortTy;
5044 break;
5045 case 'i':
5046 if (HowLong == 3)
5047 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5048 else if (HowLong == 2)
5049 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5050 else if (HowLong == 1)
5051 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5052 else
5053 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5054 break;
5055 case 'c':
5056 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5057 if (Signed)
5058 Type = Context.SignedCharTy;
5059 else if (Unsigned)
5060 Type = Context.UnsignedCharTy;
5061 else
5062 Type = Context.CharTy;
5063 break;
5064 case 'b': // boolean
5065 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5066 Type = Context.BoolTy;
5067 break;
5068 case 'z': // size_t.
5069 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5070 Type = Context.getSizeType();
5071 break;
5072 case 'F':
5073 Type = Context.getCFConstantStringType();
5074 break;
5075 case 'a':
5076 Type = Context.getBuiltinVaListType();
5077 assert(!Type.isNull() && "builtin va list type not initialized!");
5078 break;
5079 case 'A':
5080 // This is a "reference" to a va_list; however, what exactly
5081 // this means depends on how va_list is defined. There are two
5082 // different kinds of va_list: ones passed by value, and ones
5083 // passed by reference. An example of a by-value va_list is
5084 // x86, where va_list is a char*. An example of by-ref va_list
5085 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5086 // we want this argument to be a char*&; for x86-64, we want
5087 // it to be a __va_list_tag*.
5088 Type = Context.getBuiltinVaListType();
5089 assert(!Type.isNull() && "builtin va list type not initialized!");
5090 if (Type->isArrayType()) {
5091 Type = Context.getArrayDecayedType(Type);
5092 } else {
5093 Type = Context.getLValueReferenceType(Type);
5094 }
5095 break;
5096 case 'V': {
5097 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005098 unsigned NumElements = strtoul(Str, &End, 10);
5099 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005100
Chris Lattnerecd79c62009-06-14 00:45:47 +00005101 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005102
Chris Lattnerecd79c62009-06-14 00:45:47 +00005103 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005104 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005105 Type = Context.getVectorType(ElementType, NumElements,
5106 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005107 break;
5108 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005109 case 'X': {
5110 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5111 Type = Context.getComplexType(ElementType);
5112 break;
5113 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005114 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005115 Type = Context.getFILEType();
5116 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005117 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005118 return QualType();
5119 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005120 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005121 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005122 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005123 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005124 else
5125 Type = Context.getjmp_bufType();
5126
Mike Stump2adb4da2009-07-28 23:47:15 +00005127 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005128 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005129 return QualType();
5130 }
5131 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005132 }
Mike Stump11289f42009-09-09 15:08:12 +00005133
Chris Lattnerecd79c62009-06-14 00:45:47 +00005134 if (!AllowTypeModifiers)
5135 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005136
Chris Lattnerecd79c62009-06-14 00:45:47 +00005137 Done = false;
5138 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005139 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005140 default: Done = true; --Str; break;
5141 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005142 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005143 {
5144 // Both pointers and references can have their pointee types
5145 // qualified with an address space.
5146 char *End;
5147 unsigned AddrSpace = strtoul(Str, &End, 10);
5148 if (End != Str && AddrSpace != 0) {
5149 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5150 Str = End;
5151 }
5152 }
5153 if (c == '*')
5154 Type = Context.getPointerType(Type);
5155 else
5156 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005157 break;
5158 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5159 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005160 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005161 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005162 case 'D':
5163 Type = Context.getVolatileType(Type);
5164 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005165 }
5166 }
Mike Stump11289f42009-09-09 15:08:12 +00005167
Chris Lattnerecd79c62009-06-14 00:45:47 +00005168 return Type;
5169}
5170
5171/// GetBuiltinType - Return the type for the specified builtin.
5172QualType ASTContext::GetBuiltinType(unsigned id,
5173 GetBuiltinTypeError &Error) {
5174 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005175
Chris Lattnerecd79c62009-06-14 00:45:47 +00005176 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005177
Chris Lattnerecd79c62009-06-14 00:45:47 +00005178 Error = GE_None;
5179 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5180 if (Error != GE_None)
5181 return QualType();
5182 while (TypeStr[0] && TypeStr[0] != '.') {
5183 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5184 if (Error != GE_None)
5185 return QualType();
5186
5187 // Do array -> pointer decay. The builtin should use the decayed type.
5188 if (Ty->isArrayType())
5189 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005190
Chris Lattnerecd79c62009-06-14 00:45:47 +00005191 ArgTypes.push_back(Ty);
5192 }
5193
5194 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5195 "'.' should only occur at end of builtin type list!");
5196
5197 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5198 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5199 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005200
5201 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005202 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005203 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005204 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005205}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005206
5207QualType
5208ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5209 // Perform the usual unary conversions. We do this early so that
5210 // integral promotions to "int" can allow us to exit early, in the
5211 // lhs == rhs check. Also, for conversion purposes, we ignore any
5212 // qualifiers. For example, "const float" and "float" are
5213 // equivalent.
5214 if (lhs->isPromotableIntegerType())
5215 lhs = getPromotedIntegerType(lhs);
5216 else
5217 lhs = lhs.getUnqualifiedType();
5218 if (rhs->isPromotableIntegerType())
5219 rhs = getPromotedIntegerType(rhs);
5220 else
5221 rhs = rhs.getUnqualifiedType();
5222
5223 // If both types are identical, no conversion is needed.
5224 if (lhs == rhs)
5225 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005226
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005227 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5228 // The caller can deal with this (e.g. pointer + int).
5229 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5230 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005231
5232 // At this point, we have two different arithmetic types.
5233
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005234 // Handle complex types first (C99 6.3.1.8p1).
5235 if (lhs->isComplexType() || rhs->isComplexType()) {
5236 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005237 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005238 // convert the rhs to the lhs complex type.
5239 return lhs;
5240 }
Mike Stump11289f42009-09-09 15:08:12 +00005241 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005242 // convert the lhs to the rhs complex type.
5243 return rhs;
5244 }
5245 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005246 // When both operands are complex, the shorter operand is converted to the
5247 // type of the longer, and that is the type of the result. This corresponds
5248 // to what is done when combining two real floating-point operands.
5249 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005250 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005251 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005252 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005253 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005254 // "double _Complex" is promoted to "long double _Complex".
5255 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005256
5257 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005258 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005259 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005260 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005261 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005262 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5263 // domains match. This is a requirement for our implementation, C99
5264 // does not require this promotion.
5265 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5266 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5267 return rhs;
5268 } else { // handle "_Complex double, double".
5269 return lhs;
5270 }
5271 }
5272 return lhs; // The domain/size match exactly.
5273 }
5274 // Now handle "real" floating types (i.e. float, double, long double).
5275 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5276 // if we have an integer operand, the result is the real floating type.
5277 if (rhs->isIntegerType()) {
5278 // convert rhs to the lhs floating point type.
5279 return lhs;
5280 }
5281 if (rhs->isComplexIntegerType()) {
5282 // convert rhs to the complex floating point type.
5283 return getComplexType(lhs);
5284 }
5285 if (lhs->isIntegerType()) {
5286 // convert lhs to the rhs floating point type.
5287 return rhs;
5288 }
Mike Stump11289f42009-09-09 15:08:12 +00005289 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005290 // convert lhs to the complex floating point type.
5291 return getComplexType(rhs);
5292 }
5293 // We have two real floating types, float/complex combos were handled above.
5294 // Convert the smaller operand to the bigger result.
5295 int result = getFloatingTypeOrder(lhs, rhs);
5296 if (result > 0) // convert the rhs
5297 return lhs;
5298 assert(result < 0 && "illegal float comparison");
5299 return rhs; // convert the lhs
5300 }
5301 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5302 // Handle GCC complex int extension.
5303 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5304 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5305
5306 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005307 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005308 rhsComplexInt->getElementType()) >= 0)
5309 return lhs; // convert the rhs
5310 return rhs;
5311 } else if (lhsComplexInt && rhs->isIntegerType()) {
5312 // convert the rhs to the lhs complex type.
5313 return lhs;
5314 } else if (rhsComplexInt && lhs->isIntegerType()) {
5315 // convert the lhs to the rhs complex type.
5316 return rhs;
5317 }
5318 }
5319 // Finally, we have two differing integer types.
5320 // The rules for this case are in C99 6.3.1.8
5321 int compare = getIntegerTypeOrder(lhs, rhs);
5322 bool lhsSigned = lhs->isSignedIntegerType(),
5323 rhsSigned = rhs->isSignedIntegerType();
5324 QualType destType;
5325 if (lhsSigned == rhsSigned) {
5326 // Same signedness; use the higher-ranked type
5327 destType = compare >= 0 ? lhs : rhs;
5328 } else if (compare != (lhsSigned ? 1 : -1)) {
5329 // The unsigned type has greater than or equal rank to the
5330 // signed type, so use the unsigned type
5331 destType = lhsSigned ? rhs : lhs;
5332 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5333 // The two types are different widths; if we are here, that
5334 // means the signed type is larger than the unsigned type, so
5335 // use the signed type.
5336 destType = lhsSigned ? lhs : rhs;
5337 } else {
5338 // The signed type is higher-ranked than the unsigned type,
5339 // but isn't actually any bigger (like unsigned int and long
5340 // on most 32-bit systems). Use the unsigned type corresponding
5341 // to the signed type.
5342 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5343 }
5344 return destType;
5345}