blob: 2d52bd08d557f8060f21afd1880d55a756cc02fe [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor18274032010-07-03 00:47:00 +000034unsigned ASTContext::NumImplicitDefaultConstructors;
35unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000036unsigned ASTContext::NumImplicitCopyConstructors;
37unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000038unsigned ASTContext::NumImplicitCopyAssignmentOperators;
39unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000040unsigned ASTContext::NumImplicitDestructors;
41unsigned ASTContext::NumImplicitDestructorsDeclared;
42
Reid Spencer5f016e22007-07-11 17:01:13 +000043enum FloatingRank {
44 FloatRank, DoubleRank, LongDoubleRank
45};
46
Douglas Gregor3e1274f2010-06-16 21:09:37 +000047void
48ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
49 TemplateTemplateParmDecl *Parm) {
50 ID.AddInteger(Parm->getDepth());
51 ID.AddInteger(Parm->getPosition());
52 // FIXME: Parameter pack
53
54 TemplateParameterList *Params = Parm->getTemplateParameters();
55 ID.AddInteger(Params->size());
56 for (TemplateParameterList::const_iterator P = Params->begin(),
57 PEnd = Params->end();
58 P != PEnd; ++P) {
59 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
60 ID.AddInteger(0);
61 ID.AddBoolean(TTP->isParameterPack());
62 continue;
63 }
64
65 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
66 ID.AddInteger(1);
67 // FIXME: Parameter pack
68 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
69 continue;
70 }
71
72 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
73 ID.AddInteger(2);
74 Profile(ID, TTP);
75 }
76}
77
78TemplateTemplateParmDecl *
79ASTContext::getCanonicalTemplateTemplateParmDecl(
80 TemplateTemplateParmDecl *TTP) {
81 // Check if we already have a canonical template template parameter.
82 llvm::FoldingSetNodeID ID;
83 CanonicalTemplateTemplateParm::Profile(ID, TTP);
84 void *InsertPos = 0;
85 CanonicalTemplateTemplateParm *Canonical
86 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
87 if (Canonical)
88 return Canonical->getParam();
89
90 // Build a canonical template parameter list.
91 TemplateParameterList *Params = TTP->getTemplateParameters();
92 llvm::SmallVector<NamedDecl *, 4> CanonParams;
93 CanonParams.reserve(Params->size());
94 for (TemplateParameterList::const_iterator P = Params->begin(),
95 PEnd = Params->end();
96 P != PEnd; ++P) {
97 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
98 CanonParams.push_back(
99 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
100 SourceLocation(), TTP->getDepth(),
101 TTP->getIndex(), 0, false,
102 TTP->isParameterPack()));
103 else if (NonTypeTemplateParmDecl *NTTP
104 = dyn_cast<NonTypeTemplateParmDecl>(*P))
105 CanonParams.push_back(
106 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
107 SourceLocation(), NTTP->getDepth(),
108 NTTP->getPosition(), 0,
109 getCanonicalType(NTTP->getType()),
110 0));
111 else
112 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
113 cast<TemplateTemplateParmDecl>(*P)));
114 }
115
116 TemplateTemplateParmDecl *CanonTTP
117 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
118 SourceLocation(), TTP->getDepth(),
119 TTP->getPosition(), 0,
120 TemplateParameterList::Create(*this, SourceLocation(),
121 SourceLocation(),
122 CanonParams.data(),
123 CanonParams.size(),
124 SourceLocation()));
125
126 // Get the new insert position for the node we care about.
127 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
128 assert(Canonical == 0 && "Shouldn't be in the map!");
129 (void)Canonical;
130
131 // Create the canonical template template parameter entry.
132 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
133 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
134 return CanonTTP;
135}
136
Chris Lattner61710852008-10-05 17:34:18 +0000137ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000138 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000139 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000140 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +0000141 bool FreeMem, unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000142 TemplateSpecializationTypes(this_()),
143 DependentTemplateSpecializationTypes(this_()),
Mike Stump1eb44332009-09-09 15:08:12 +0000144 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +0000145 NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000146 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000147 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000148 NullTypeSourceInfo(QualType()),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000149 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000150 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000151 BuiltinInfo(builtins),
152 DeclarationNames(*this),
153 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000154 LastSDM(0, 0),
155 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000156 ObjCIdRedefinitionType = QualType();
157 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000158 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000159 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000160 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000161 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000162}
163
Reid Spencer5f016e22007-07-11 17:01:13 +0000164ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000165 // Release the DenseMaps associated with DeclContext objects.
166 // FIXME: Is this the ideal solution?
167 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000168
Douglas Gregor00545312010-05-23 18:26:36 +0000169 if (!FreeMemory) {
170 // Call all of the deallocation functions.
171 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
172 Deallocations[I].first(Deallocations[I].second);
173 }
174
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000175 // Release all of the memory associated with overridden C++ methods.
176 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
177 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
178 OM != OMEnd; ++OM)
179 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000180
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000181 if (FreeMemory) {
182 // Deallocate all the types.
183 while (!Types.empty()) {
184 Types.back()->Destroy(*this);
185 Types.pop_back();
186 }
Eli Friedmanb26153c2008-05-27 03:08:09 +0000187
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000188 for (llvm::FoldingSet<ExtQuals>::iterator
189 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
190 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +0000191 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +0000192 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000193
Ted Kremenek503524a2010-03-08 20:56:29 +0000194 for (llvm::DenseMap<const ObjCContainerDecl*,
195 const ASTRecordLayout*>::iterator
196 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
197 // Increment in loop to prevent using deallocated memory.
198 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
199 R->Destroy(*this);
200 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000201 }
202
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000203 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
204 // even when using the BumpPtrAllocator because they can contain
205 // DenseMaps.
206 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
207 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
208 // Increment in loop to prevent using deallocated memory.
209 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
210 R->Destroy(*this);
211 }
212
Douglas Gregorab452ba2009-03-26 23:50:42 +0000213 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000214 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
215 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000216 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000217 NNS != NNSEnd; ) {
218 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000219 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000220 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000221
222 if (GlobalNestedNameSpecifier)
223 GlobalNestedNameSpecifier->Destroy(*this);
224
Eli Friedmanb26153c2008-05-27 03:08:09 +0000225 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000226}
227
Douglas Gregor00545312010-05-23 18:26:36 +0000228void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
229 Deallocations.push_back(std::make_pair(Callback, Data));
230}
231
Mike Stump1eb44332009-09-09 15:08:12 +0000232void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000233ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
234 ExternalSource.reset(Source.take());
235}
236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237void ASTContext::PrintStats() const {
238 fprintf(stderr, "*** AST Context Stats:\n");
239 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000240
Douglas Gregordbe833d2009-05-26 14:40:08 +0000241 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000242#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000243#define ABSTRACT_TYPE(Name, Parent)
244#include "clang/AST/TypeNodes.def"
245 0 // Extra
246 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
249 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000250 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 }
252
Douglas Gregordbe833d2009-05-26 14:40:08 +0000253 unsigned Idx = 0;
254 unsigned TotalBytes = 0;
255#define TYPE(Name, Parent) \
256 if (counts[Idx]) \
257 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
258 TotalBytes += counts[Idx] * sizeof(Name##Type); \
259 ++Idx;
260#define ABSTRACT_TYPE(Name, Parent)
261#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Douglas Gregordbe833d2009-05-26 14:40:08 +0000263 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000264
Douglas Gregor4923aa22010-07-02 20:37:36 +0000265 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000266 fprintf(stderr, " %u/%u implicit default constructors created\n",
267 NumImplicitDefaultConstructorsDeclared,
268 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000269 fprintf(stderr, " %u/%u implicit copy constructors created\n",
270 NumImplicitCopyConstructorsDeclared,
271 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000272 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
273 NumImplicitCopyAssignmentOperatorsDeclared,
274 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000275 fprintf(stderr, " %u/%u implicit destructors created\n",
276 NumImplicitDestructorsDeclared, NumImplicitDestructors);
277
Douglas Gregor2cf26342009-04-09 22:27:44 +0000278 if (ExternalSource.get()) {
279 fprintf(stderr, "\n");
280 ExternalSource->PrintStats();
281 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000282}
283
284
John McCalle27ec8a2009-10-23 23:03:21 +0000285void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000286 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000287 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000288 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000289}
290
Reid Spencer5f016e22007-07-11 17:01:13 +0000291void ASTContext::InitBuiltinTypes() {
292 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // C99 6.2.5p19.
295 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // C99 6.2.5p2.
298 InitBuiltinType(BoolTy, BuiltinType::Bool);
299 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000300 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 InitBuiltinType(CharTy, BuiltinType::Char_S);
302 else
303 InitBuiltinType(CharTy, BuiltinType::Char_U);
304 // C99 6.2.5p4.
305 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
306 InitBuiltinType(ShortTy, BuiltinType::Short);
307 InitBuiltinType(IntTy, BuiltinType::Int);
308 InitBuiltinType(LongTy, BuiltinType::Long);
309 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // C99 6.2.5p6.
312 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
313 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
314 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
315 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
316 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 // C99 6.2.5p10.
319 InitBuiltinType(FloatTy, BuiltinType::Float);
320 InitBuiltinType(DoubleTy, BuiltinType::Double);
321 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000322
Chris Lattner2df9ced2009-04-30 02:43:43 +0000323 // GNU extension, 128-bit integers.
324 InitBuiltinType(Int128Ty, BuiltinType::Int128);
325 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
326
Chris Lattner3a250322009-02-26 23:43:47 +0000327 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
328 InitBuiltinType(WCharTy, BuiltinType::WChar);
329 else // C99
330 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000331
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000332 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
333 InitBuiltinType(Char16Ty, BuiltinType::Char16);
334 else // C99
335 Char16Ty = getFromTargetType(Target.getChar16Type());
336
337 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
338 InitBuiltinType(Char32Ty, BuiltinType::Char32);
339 else // C99
340 Char32Ty = getFromTargetType(Target.getChar32Type());
341
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000342 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000343 InitBuiltinType(OverloadTy, BuiltinType::Overload);
344
345 // Placeholder type for type-dependent expressions whose type is
346 // completely unknown. No code should ever check a type against
347 // DependentTy and users should never see it; however, it is here to
348 // help diagnose failures to properly check for type-dependent
349 // expressions.
350 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000351
Mike Stump1eb44332009-09-09 15:08:12 +0000352 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000353 // not yet been deduced.
354 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // C99 6.2.5p11.
357 FloatComplexTy = getComplexType(FloatTy);
358 DoubleComplexTy = getComplexType(DoubleTy);
359 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000360
Steve Naroff7e219e42007-10-15 14:41:52 +0000361 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroffde2e22d2009-07-15 18:40:39 +0000363 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
364 ObjCIdTypedefType = QualType();
365 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000366 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000368 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000369 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
370 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000371 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000372
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000373 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000375 // void * type
376 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000377
378 // nullptr type (C++0x 2.14.7)
379 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380}
381
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000382MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000383ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000384 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000385 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000386 = InstantiatedFromStaticDataMember.find(Var);
387 if (Pos == InstantiatedFromStaticDataMember.end())
388 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Douglas Gregor7caa6822009-07-24 20:34:43 +0000390 return Pos->second;
391}
392
Mike Stump1eb44332009-09-09 15:08:12 +0000393void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000394ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
395 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000396 assert(Inst->isStaticDataMember() && "Not a static data member");
397 assert(Tmpl->isStaticDataMember() && "Not a static data member");
398 assert(!InstantiatedFromStaticDataMember[Inst] &&
399 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000400 InstantiatedFromStaticDataMember[Inst]
401 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000402}
403
John McCall7ba107a2009-11-18 02:36:19 +0000404NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000405ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000406 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000407 = InstantiatedFromUsingDecl.find(UUD);
408 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000409 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Anders Carlsson0d8df782009-08-29 19:37:28 +0000411 return Pos->second;
412}
413
414void
John McCalled976492009-12-04 22:46:56 +0000415ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
416 assert((isa<UsingDecl>(Pattern) ||
417 isa<UnresolvedUsingValueDecl>(Pattern) ||
418 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
419 "pattern decl is not a using decl");
420 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
421 InstantiatedFromUsingDecl[Inst] = Pattern;
422}
423
424UsingShadowDecl *
425ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
426 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
427 = InstantiatedFromUsingShadowDecl.find(Inst);
428 if (Pos == InstantiatedFromUsingShadowDecl.end())
429 return 0;
430
431 return Pos->second;
432}
433
434void
435ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
436 UsingShadowDecl *Pattern) {
437 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
438 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000439}
440
Anders Carlssond8b285f2009-09-01 04:26:58 +0000441FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
442 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
443 = InstantiatedFromUnnamedFieldDecl.find(Field);
444 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
445 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Anders Carlssond8b285f2009-09-01 04:26:58 +0000447 return Pos->second;
448}
449
450void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
451 FieldDecl *Tmpl) {
452 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
453 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
454 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
455 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Anders Carlssond8b285f2009-09-01 04:26:58 +0000457 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
458}
459
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000460ASTContext::overridden_cxx_method_iterator
461ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
462 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
463 = OverriddenMethods.find(Method);
464 if (Pos == OverriddenMethods.end())
465 return 0;
466
467 return Pos->second.begin();
468}
469
470ASTContext::overridden_cxx_method_iterator
471ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
472 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
473 = OverriddenMethods.find(Method);
474 if (Pos == OverriddenMethods.end())
475 return 0;
476
477 return Pos->second.end();
478}
479
480void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
481 const CXXMethodDecl *Overridden) {
482 OverriddenMethods[Method].push_back(Overridden);
483}
484
Douglas Gregor2e222532009-07-02 17:08:52 +0000485namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000486 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000487 : std::binary_function<SourceRange, SourceRange, bool> {
488 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregor2e222532009-07-02 17:08:52 +0000490 public:
491 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregor2e222532009-07-02 17:08:52 +0000493 bool operator()(SourceRange X, SourceRange Y) {
494 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
495 }
496 };
497}
498
Chris Lattner464175b2007-07-18 17:52:12 +0000499//===----------------------------------------------------------------------===//
500// Type Sizing and Analysis
501//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000502
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000503/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
504/// scalar floating point type.
505const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000506 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000507 assert(BT && "Not a floating point type!");
508 switch (BT->getKind()) {
509 default: assert(0 && "Not a floating point type!");
510 case BuiltinType::Float: return Target.getFloatFormat();
511 case BuiltinType::Double: return Target.getDoubleFormat();
512 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
513 }
514}
515
Ken Dyck8b752f12010-01-27 17:10:57 +0000516/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000517/// specified decl. Note that bitfields do not have a valid alignment, so
518/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000519/// If @p RefAsPointee, references are treated like their underlying type
520/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000521CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000522 unsigned Align = Target.getCharWidth();
523
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000524 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000525 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000526
Chris Lattneraf707ab2009-01-24 21:53:27 +0000527 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
528 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000529 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000530 if (RefAsPointee)
531 T = RT->getPointeeType();
532 else
533 T = getPointerType(RT->getPointeeType());
534 }
535 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000536 unsigned MinWidth = Target.getLargeArrayMinWidth();
537 unsigned ArrayAlign = Target.getLargeArrayAlign();
538 if (isa<VariableArrayType>(T) && MinWidth != 0)
539 Align = std::max(Align, ArrayAlign);
540 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
541 unsigned Size = getTypeSize(CT);
542 if (MinWidth != 0 && MinWidth <= Size)
543 Align = std::max(Align, ArrayAlign);
544 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000545 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
547 T = cast<ArrayType>(T)->getElementType();
548
549 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
550 }
Charles Davis05f62472010-02-23 04:52:00 +0000551 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
552 // In the case of a field in a packed struct, we want the minimum
553 // of the alignment of the field and the alignment of the struct.
554 Align = std::min(Align,
555 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
556 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000557 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000558
Ken Dyck8b752f12010-01-27 17:10:57 +0000559 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000560}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000561
John McCallea1471e2010-05-20 01:18:31 +0000562std::pair<CharUnits, CharUnits>
563ASTContext::getTypeInfoInChars(const Type *T) {
564 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
565 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
566 CharUnits::fromQuantity(Info.second / getCharWidth()));
567}
568
569std::pair<CharUnits, CharUnits>
570ASTContext::getTypeInfoInChars(QualType T) {
571 return getTypeInfoInChars(T.getTypePtr());
572}
573
Chris Lattnera7674d82007-07-13 22:13:22 +0000574/// getTypeSize - Return the size of the specified type, in bits. This method
575/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000576///
577/// FIXME: Pointers into different addr spaces could have different sizes and
578/// alignment requirements: getPointerInfo should take an AddrSpace, this
579/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000580std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000581ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000582 uint64_t Width=0;
583 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000584 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000585#define TYPE(Class, Base)
586#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000587#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000588#define DEPENDENT_TYPE(Class, Base) case Type::Class:
589#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000590 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000591 break;
592
Chris Lattner692233e2007-07-13 22:27:08 +0000593 case Type::FunctionNoProto:
594 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000595 // GCC extension: alignof(function) = 32 bits
596 Width = 0;
597 Align = 32;
598 break;
599
Douglas Gregor72564e72009-02-26 23:50:07 +0000600 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000601 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000602 Width = 0;
603 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
604 break;
605
Steve Narofffb22d962007-08-30 01:06:46 +0000606 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000607 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner98be4942008-03-05 18:54:05 +0000609 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000610 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000611 Align = EltInfo.second;
612 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000613 }
Nate Begeman213541a2008-04-18 23:10:10 +0000614 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000615 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000616 const VectorType *VT = cast<VectorType>(T);
617 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
618 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000619 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000620 // If the alignment is not a power of 2, round up to the next power of 2.
621 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000622 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000623 Align = llvm::NextPowerOf2(Align);
624 Width = llvm::RoundUpToAlignment(Width, Align);
625 }
Chris Lattner030d8842007-07-19 22:06:24 +0000626 break;
627 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000628
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000629 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000630 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000631 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000632 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000633 // GCC extension: alignof(void) = 8 bits.
634 Width = 0;
635 Align = 8;
636 break;
637
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getBoolWidth();
640 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000642 case BuiltinType::Char_S:
643 case BuiltinType::Char_U:
644 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000646 Width = Target.getCharWidth();
647 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000648 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000649 case BuiltinType::WChar:
650 Width = Target.getWCharWidth();
651 Align = Target.getWCharAlign();
652 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000653 case BuiltinType::Char16:
654 Width = Target.getChar16Width();
655 Align = Target.getChar16Align();
656 break;
657 case BuiltinType::Char32:
658 Width = Target.getChar32Width();
659 Align = Target.getChar32Align();
660 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000661 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000663 Width = Target.getShortWidth();
664 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000666 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000667 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000668 Width = Target.getIntWidth();
669 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000671 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000672 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000673 Width = Target.getLongWidth();
674 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000675 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000676 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000677 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000678 Width = Target.getLongLongWidth();
679 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000680 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000681 case BuiltinType::Int128:
682 case BuiltinType::UInt128:
683 Width = 128;
684 Align = 128; // int128_t is 128-bit aligned on all targets.
685 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000687 Width = Target.getFloatWidth();
688 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000689 break;
690 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000691 Width = Target.getDoubleWidth();
692 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000693 break;
694 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000695 Width = Target.getLongDoubleWidth();
696 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000697 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000698 case BuiltinType::NullPtr:
699 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
700 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000701 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000702 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000703 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000704 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000705 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000706 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000708 case Type::BlockPointer: {
709 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
710 Width = Target.getPointerWidth(AS);
711 Align = Target.getPointerAlign(AS);
712 break;
713 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000714 case Type::LValueReference:
715 case Type::RValueReference: {
716 // alignof and sizeof should never enter this code path here, so we go
717 // the pointer route.
718 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
719 Width = Target.getPointerWidth(AS);
720 Align = Target.getPointerAlign(AS);
721 break;
722 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 case Type::Pointer: {
724 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000725 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000726 Align = Target.getPointerAlign(AS);
727 break;
728 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000729 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000730 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000731 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000732 getTypeInfo(getPointerDiffType());
733 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000734 if (Pointee->isFunctionType())
735 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000736 Align = PtrDiffInfo.second;
737 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000738 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000739 case Type::Complex: {
740 // Complex types have the same alignment as their elements, but twice the
741 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000742 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000743 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000744 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000745 Align = EltInfo.second;
746 break;
747 }
John McCallc12c5bb2010-05-15 11:32:37 +0000748 case Type::ObjCObject:
749 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000750 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000751 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000752 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
753 Width = Layout.getSize();
754 Align = Layout.getAlignment();
755 break;
756 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000757 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000758 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000759 const TagType *TT = cast<TagType>(T);
760
761 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000762 Width = 1;
763 Align = 1;
764 break;
765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Daniel Dunbar1d751182008-11-08 05:48:37 +0000767 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000768 return getTypeInfo(ET->getDecl()->getIntegerType());
769
Daniel Dunbar1d751182008-11-08 05:48:37 +0000770 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000771 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
772 Width = Layout.getSize();
773 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000774 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000775 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000776
Chris Lattner9fcfe922009-10-22 05:17:15 +0000777 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000778 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
779 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000780
Douglas Gregor18857642009-04-30 17:32:17 +0000781 case Type::Typedef: {
782 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000783 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000784 Align = std::max(Aligned->getMaxAlignment(),
785 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000786 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
787 } else
788 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000789 break;
Chris Lattner71763312008-04-06 22:05:18 +0000790 }
Douglas Gregor18857642009-04-30 17:32:17 +0000791
792 case Type::TypeOfExpr:
793 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
794 .getTypePtr());
795
796 case Type::TypeOf:
797 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
798
Anders Carlsson395b4752009-06-24 19:06:50 +0000799 case Type::Decltype:
800 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
801 .getTypePtr());
802
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000803 case Type::Elaborated:
804 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Douglas Gregor18857642009-04-30 17:32:17 +0000806 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000807 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000808 "Cannot request the size of a dependent type");
809 // FIXME: this is likely to be wrong once we support template
810 // aliases, since a template alias could refer to a typedef that
811 // has an __aligned__ attribute on it.
812 return getTypeInfo(getCanonicalType(T));
813 }
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Chris Lattner464175b2007-07-18 17:52:12 +0000815 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000816 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000817}
818
Ken Dyckbdc601b2009-12-22 14:23:30 +0000819/// getTypeSizeInChars - Return the size of the specified type, in characters.
820/// This method does not work on incomplete types.
821CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000822 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000823}
824CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000825 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000826}
827
Ken Dyck16e20cc2010-01-26 17:25:18 +0000828/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000829/// characters. This method does not work on incomplete types.
830CharUnits ASTContext::getTypeAlignInChars(QualType T) {
831 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
832}
833CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
834 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
835}
836
Chris Lattner34ebde42009-01-27 18:08:34 +0000837/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
838/// type for the current target in bits. This can be different than the ABI
839/// alignment in cases where it is beneficial for performance to overalign
840/// a data type.
841unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
842 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000843
844 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000845 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000846 T = CT->getElementType().getTypePtr();
847 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
848 T->isSpecificBuiltinType(BuiltinType::LongLong))
849 return std::max(ABIAlign, (unsigned)getTypeSize(T));
850
Chris Lattner34ebde42009-01-27 18:08:34 +0000851 return ABIAlign;
852}
853
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000854static void CollectLocalObjCIvars(ASTContext *Ctx,
855 const ObjCInterfaceDecl *OI,
856 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000857 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
858 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000859 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000860 if (!IVDecl->isInvalidDecl())
861 Fields.push_back(cast<FieldDecl>(IVDecl));
862 }
863}
864
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000865void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
866 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
867 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
868 CollectObjCIvars(SuperClass, Fields);
869 CollectLocalObjCIvars(this, OI, Fields);
870}
871
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000872/// ShallowCollectObjCIvars -
873/// Collect all ivars, including those synthesized, in the current class.
874///
875void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000876 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000877 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
878 E = OI->ivar_end(); I != E; ++I) {
879 Ivars.push_back(*I);
880 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000881
882 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000883}
884
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000885/// CollectNonClassIvars -
886/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000887/// This includes synthesized ivars (via @synthesize) and those in
888// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000889///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000890void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000891 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000892 // Find ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000893 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
894 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000895 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
896 E = CDecl->ivar_end(); I != E; ++I) {
897 Ivars.push_back(*I);
898 }
899 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000900
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000901 // Also add any ivar defined in this class's implementation. This
902 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000903 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
904 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
905 E = ImplDecl->ivar_end(); I != E; ++I)
906 Ivars.push_back(*I);
907 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000908}
909
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000910/// CollectInheritedProtocols - Collect all protocols in current class and
911/// those inherited by it.
912void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000913 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000914 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
915 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
916 PE = OI->protocol_end(); P != PE; ++P) {
917 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000918 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000919 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000920 PE = Proto->protocol_end(); P != PE; ++P) {
921 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000922 CollectInheritedProtocols(*P, Protocols);
923 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000924 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000925
926 // Categories of this Interface.
927 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
928 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
929 CollectInheritedProtocols(CDeclChain, Protocols);
930 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
931 while (SD) {
932 CollectInheritedProtocols(SD, Protocols);
933 SD = SD->getSuperClass();
934 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000935 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
937 PE = OC->protocol_end(); P != PE; ++P) {
938 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000939 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000940 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
941 PE = Proto->protocol_end(); P != PE; ++P)
942 CollectInheritedProtocols(*P, Protocols);
943 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000944 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000945 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
946 PE = OP->protocol_end(); P != PE; ++P) {
947 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000948 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000949 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
950 PE = Proto->protocol_end(); P != PE; ++P)
951 CollectInheritedProtocols(*P, Protocols);
952 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000953 }
954}
955
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000956unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
957 unsigned count = 0;
958 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000959 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
960 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000961 count += CDecl->ivar_size();
962
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000963 // Count ivar defined in this class's implementation. This
964 // includes synthesized ivars.
965 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000966 count += ImplDecl->ivar_size();
967
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000968 return count;
969}
970
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000971/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
972ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
973 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
974 I = ObjCImpls.find(D);
975 if (I != ObjCImpls.end())
976 return cast<ObjCImplementationDecl>(I->second);
977 return 0;
978}
979/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
980ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
981 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
982 I = ObjCImpls.find(D);
983 if (I != ObjCImpls.end())
984 return cast<ObjCCategoryImplDecl>(I->second);
985 return 0;
986}
987
988/// \brief Set the implementation of ObjCInterfaceDecl.
989void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
990 ObjCImplementationDecl *ImplD) {
991 assert(IFaceD && ImplD && "Passed null params");
992 ObjCImpls[IFaceD] = ImplD;
993}
994/// \brief Set the implementation of ObjCCategoryDecl.
995void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
996 ObjCCategoryImplDecl *ImplD) {
997 assert(CatD && ImplD && "Passed null params");
998 ObjCImpls[CatD] = ImplD;
999}
1000
John McCalla93c9342009-12-07 02:54:59 +00001001/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001002///
John McCalla93c9342009-12-07 02:54:59 +00001003/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001004/// the TypeLoc wrappers.
1005///
1006/// \param T the type that will be the basis for type source info. This type
1007/// should refer to how the declarator was written in source code, not to
1008/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001009TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001010 unsigned DataSize) {
1011 if (!DataSize)
1012 DataSize = TypeLoc::getFullDataSizeForType(T);
1013 else
1014 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001015 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001016
John McCalla93c9342009-12-07 02:54:59 +00001017 TypeSourceInfo *TInfo =
1018 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1019 new (TInfo) TypeSourceInfo(T);
1020 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001021}
1022
John McCalla93c9342009-12-07 02:54:59 +00001023TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001024 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001025 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001026 DI->getTypeLoc().initialize(L);
1027 return DI;
1028}
1029
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001030const ASTRecordLayout &
1031ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1032 return getObjCLayout(D, 0);
1033}
1034
1035const ASTRecordLayout &
1036ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1037 return getObjCLayout(D->getClassInterface(), D);
1038}
1039
Chris Lattnera7674d82007-07-13 22:13:22 +00001040//===----------------------------------------------------------------------===//
1041// Type creation/memoization methods
1042//===----------------------------------------------------------------------===//
1043
John McCall0953e762009-09-24 19:53:00 +00001044QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1045 unsigned Fast = Quals.getFastQualifiers();
1046 Quals.removeFastQualifiers();
1047
1048 // Check if we've already instantiated this type.
1049 llvm::FoldingSetNodeID ID;
1050 ExtQuals::Profile(ID, TypeNode, Quals);
1051 void *InsertPos = 0;
1052 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1053 assert(EQ->getQualifiers() == Quals);
1054 QualType T = QualType(EQ, Fast);
1055 return T;
1056 }
1057
John McCall6b304a02009-09-24 23:30:46 +00001058 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001059 ExtQualNodes.InsertNode(New, InsertPos);
1060 QualType T = QualType(New, Fast);
1061 return T;
1062}
1063
1064QualType ASTContext::getVolatileType(QualType T) {
1065 QualType CanT = getCanonicalType(T);
1066 if (CanT.isVolatileQualified()) return T;
1067
1068 QualifierCollector Quals;
1069 const Type *TypeNode = Quals.strip(T);
1070 Quals.addVolatile();
1071
1072 return getExtQualType(TypeNode, Quals);
1073}
1074
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001075QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001076 QualType CanT = getCanonicalType(T);
1077 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001078 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001079
John McCall0953e762009-09-24 19:53:00 +00001080 // If we are composing extended qualifiers together, merge together
1081 // into one ExtQuals node.
1082 QualifierCollector Quals;
1083 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001084
John McCall0953e762009-09-24 19:53:00 +00001085 // If this type already has an address space specified, it cannot get
1086 // another one.
1087 assert(!Quals.hasAddressSpace() &&
1088 "Type cannot be in multiple addr spaces!");
1089 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001090
John McCall0953e762009-09-24 19:53:00 +00001091 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001092}
1093
Chris Lattnerb7d25532009-02-18 22:53:11 +00001094QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001095 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001096 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001097 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001098 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001100 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001101 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001102 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001103 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1104 return getPointerType(ResultType);
1105 }
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
John McCall0953e762009-09-24 19:53:00 +00001108 // If we are composing extended qualifiers together, merge together
1109 // into one ExtQuals node.
1110 QualifierCollector Quals;
1111 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001112
John McCall0953e762009-09-24 19:53:00 +00001113 // If this type already has an ObjCGC specified, it cannot get
1114 // another one.
1115 assert(!Quals.hasObjCGCAttr() &&
1116 "Type cannot have multiple ObjCGCs!");
1117 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001118
John McCall0953e762009-09-24 19:53:00 +00001119 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001120}
Chris Lattnera7674d82007-07-13 22:13:22 +00001121
Rafael Espindola264ba482010-03-30 20:24:48 +00001122static QualType getExtFunctionType(ASTContext& Context, QualType T,
1123 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001124 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001125 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1126 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001127 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001128 if (ResultType == Pointee)
1129 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001130
1131 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001132 } else if (const BlockPointerType *BlockPointer
1133 = T->getAs<BlockPointerType>()) {
1134 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001135 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001136 if (ResultType == Pointee)
1137 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001138
1139 ResultType = Context.getBlockPointerType(ResultType);
1140 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001141 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001142 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001143
Douglas Gregor43c79c22009-12-09 00:47:37 +00001144 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001145 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001146 Info);
John McCall0953e762009-09-24 19:53:00 +00001147 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001148 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001149 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001150 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1151 FPT->getNumArgs(), FPT->isVariadic(),
1152 FPT->getTypeQuals(),
1153 FPT->hasExceptionSpec(),
1154 FPT->hasAnyExceptionSpec(),
1155 FPT->getNumExceptions(),
1156 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001157 Info);
John McCall0953e762009-09-24 19:53:00 +00001158 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001159 } else
1160 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001161
1162 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1163}
1164
1165QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001166 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001167 return getExtFunctionType(*this, T,
1168 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001169}
1170
1171QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001172 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001173 return getExtFunctionType(*this, T,
1174 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001175}
1176
Rafael Espindola425ef722010-03-30 22:15:11 +00001177QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1178 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1179 return getExtFunctionType(*this, T,
1180 Info.withRegParm(RegParm));
1181}
1182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183/// getComplexType - Return the uniqued reference to the type for a complex
1184/// number with the specified element type.
1185QualType ASTContext::getComplexType(QualType T) {
1186 // Unique pointers, to guarantee there is only one pointer of a particular
1187 // structure.
1188 llvm::FoldingSetNodeID ID;
1189 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 void *InsertPos = 0;
1192 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1193 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // If the pointee type isn't canonical, this won't be a canonical type either,
1196 // so fill in the canonical type field.
1197 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001198 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001199 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 // Get the new insert position for the node we care about.
1202 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
John McCall6b304a02009-09-24 23:30:46 +00001205 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 Types.push_back(New);
1207 ComplexTypes.InsertNode(New, InsertPos);
1208 return QualType(New, 0);
1209}
1210
Reid Spencer5f016e22007-07-11 17:01:13 +00001211/// getPointerType - Return the uniqued reference to the type for a pointer to
1212/// the specified type.
1213QualType ASTContext::getPointerType(QualType T) {
1214 // Unique pointers, to guarantee there is only one pointer of a particular
1215 // structure.
1216 llvm::FoldingSetNodeID ID;
1217 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 void *InsertPos = 0;
1220 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1221 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 // If the pointee type isn't canonical, this won't be a canonical type either,
1224 // so fill in the canonical type field.
1225 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001226 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001227 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // Get the new insert position for the node we care about.
1230 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001231 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 }
John McCall6b304a02009-09-24 23:30:46 +00001233 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 Types.push_back(New);
1235 PointerTypes.InsertNode(New, InsertPos);
1236 return QualType(New, 0);
1237}
1238
Mike Stump1eb44332009-09-09 15:08:12 +00001239/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001240/// a pointer to the specified block.
1241QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001242 assert(T->isFunctionType() && "block of function types only");
1243 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001244 // structure.
1245 llvm::FoldingSetNodeID ID;
1246 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Steve Naroff5618bd42008-08-27 16:04:49 +00001248 void *InsertPos = 0;
1249 if (BlockPointerType *PT =
1250 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1251 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
1253 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001254 // type either so fill in the canonical type field.
1255 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001256 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001257 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Steve Naroff5618bd42008-08-27 16:04:49 +00001259 // Get the new insert position for the node we care about.
1260 BlockPointerType *NewIP =
1261 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001262 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001263 }
John McCall6b304a02009-09-24 23:30:46 +00001264 BlockPointerType *New
1265 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001266 Types.push_back(New);
1267 BlockPointerTypes.InsertNode(New, InsertPos);
1268 return QualType(New, 0);
1269}
1270
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001271/// getLValueReferenceType - Return the uniqued reference to the type for an
1272/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001273QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // Unique pointers, to guarantee there is only one pointer of a particular
1275 // structure.
1276 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001277 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278
1279 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001280 if (LValueReferenceType *RT =
1281 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001283
John McCall54e14c42009-10-22 22:37:11 +00001284 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 // If the referencee type isn't canonical, this won't be a canonical type
1287 // either, so fill in the canonical type field.
1288 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001289 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1291 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294 LValueReferenceType *NewIP =
1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
1298
John McCall6b304a02009-09-24 23:30:46 +00001299 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001300 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1301 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001304
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305 return QualType(New, 0);
1306}
1307
1308/// getRValueReferenceType - Return the uniqued reference to the type for an
1309/// rvalue reference to the specified type.
1310QualType ASTContext::getRValueReferenceType(QualType T) {
1311 // Unique pointers, to guarantee there is only one pointer of a particular
1312 // structure.
1313 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001314 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315
1316 void *InsertPos = 0;
1317 if (RValueReferenceType *RT =
1318 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1319 return QualType(RT, 0);
1320
John McCall54e14c42009-10-22 22:37:11 +00001321 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1322
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001323 // If the referencee type isn't canonical, this won't be a canonical type
1324 // either, so fill in the canonical type field.
1325 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001326 if (InnerRef || !T.isCanonical()) {
1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1328 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001329
1330 // Get the new insert position for the node we care about.
1331 RValueReferenceType *NewIP =
1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1333 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1334 }
1335
John McCall6b304a02009-09-24 23:30:46 +00001336 RValueReferenceType *New
1337 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001338 Types.push_back(New);
1339 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 return QualType(New, 0);
1341}
1342
Sebastian Redlf30208a2009-01-24 21:16:55 +00001343/// getMemberPointerType - Return the uniqued reference to the type for a
1344/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001346 // Unique pointers, to guarantee there is only one pointer of a particular
1347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 MemberPointerType::Profile(ID, T, Cls);
1350
1351 void *InsertPos = 0;
1352 if (MemberPointerType *PT =
1353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
1355
1356 // If the pointee or class type isn't canonical, this won't be a canonical
1357 // type either, so fill in the canonical type field.
1358 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1361
1362 // Get the new insert position for the node we care about.
1363 MemberPointerType *NewIP =
1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1365 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1366 }
John McCall6b304a02009-09-24 23:30:46 +00001367 MemberPointerType *New
1368 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001369 Types.push_back(New);
1370 MemberPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Mike Stump1eb44332009-09-09 15:08:12 +00001374/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001375/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001376QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001377 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001378 ArrayType::ArraySizeModifier ASM,
1379 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001380 assert((EltTy->isDependentType() ||
1381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001382 "Constant array of VLAs is illegal!");
1383
Chris Lattner38aeec72009-05-13 04:12:56 +00001384 // Convert the array size into a canonical width matching the pointer size for
1385 // the target.
1386 llvm::APInt ArySize(ArySizeIn);
1387 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001390 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001393 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001394 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 // If the element type isn't canonical, this won't be a canonical type either,
1398 // so fill in the canonical type field.
1399 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001400 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001401 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001402 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001404 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001405 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001406 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408
John McCall6b304a02009-09-24 23:30:46 +00001409 ConstantArrayType *New = new(*this,TypeAlignment)
1410 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001411 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 Types.push_back(New);
1413 return QualType(New, 0);
1414}
1415
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001416/// getVariableArrayType - Returns a non-unique reference to the type for a
1417/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001418QualType ASTContext::getVariableArrayType(QualType EltTy,
1419 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001420 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001421 unsigned EltTypeQuals,
1422 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001423 // Since we don't unique expressions, it isn't possible to unique VLA's
1424 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001425 QualType CanonType;
1426
1427 if (!EltTy.isCanonical()) {
1428 if (NumElts)
1429 NumElts->Retain();
1430 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1431 EltTypeQuals, Brackets);
1432 }
1433
John McCall6b304a02009-09-24 23:30:46 +00001434 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001435 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001436
1437 VariableArrayTypes.push_back(New);
1438 Types.push_back(New);
1439 return QualType(New, 0);
1440}
1441
Douglas Gregor898574e2008-12-05 23:32:09 +00001442/// getDependentSizedArrayType - Returns a non-unique reference to
1443/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001444/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001445QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1446 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001447 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001448 unsigned EltTypeQuals,
1449 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001450 assert((!NumElts || NumElts->isTypeDependent() ||
1451 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001452 "Size must be type- or value-dependent!");
1453
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001454 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001455 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001456 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001457
1458 if (NumElts) {
1459 // Dependently-sized array types that do not have a specified
1460 // number of elements will have their sizes deduced from an
1461 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001462 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1463 EltTypeQuals, NumElts);
1464
1465 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1466 }
1467
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001468 DependentSizedArrayType *New;
1469 if (Canon) {
1470 // We already have a canonical version of this array type; use it as
1471 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001472 New = new (*this, TypeAlignment)
1473 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1474 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001475 } else {
1476 QualType CanonEltTy = getCanonicalType(EltTy);
1477 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001478 New = new (*this, TypeAlignment)
1479 DependentSizedArrayType(*this, EltTy, QualType(),
1480 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001481
Douglas Gregor789b1f62010-02-04 18:10:26 +00001482 if (NumElts) {
1483 DependentSizedArrayType *CanonCheck
1484 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1485 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1486 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001487 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001488 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001489 } else {
1490 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1491 ASM, EltTypeQuals,
1492 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001493 New = new (*this, TypeAlignment)
1494 DependentSizedArrayType(*this, EltTy, Canon,
1495 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001496 }
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Douglas Gregor898574e2008-12-05 23:32:09 +00001499 Types.push_back(New);
1500 return QualType(New, 0);
1501}
1502
Eli Friedmanc5773c42008-02-15 18:16:39 +00001503QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1504 ArrayType::ArraySizeModifier ASM,
1505 unsigned EltTypeQuals) {
1506 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001507 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001508
1509 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001510 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001511 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1512 return QualType(ATP, 0);
1513
1514 // If the element type isn't canonical, this won't be a canonical type
1515 // either, so fill in the canonical type field.
1516 QualType Canonical;
1517
John McCall467b27b2009-10-22 20:10:53 +00001518 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001519 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001520 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001521
1522 // Get the new insert position for the node we care about.
1523 IncompleteArrayType *NewIP =
1524 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001525 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001526 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001527
John McCall6b304a02009-09-24 23:30:46 +00001528 IncompleteArrayType *New = new (*this, TypeAlignment)
1529 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001530
1531 IncompleteArrayTypes.InsertNode(New, InsertPos);
1532 Types.push_back(New);
1533 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001534}
1535
Steve Naroff73322922007-07-18 18:00:27 +00001536/// getVectorType - Return the unique reference to a vector type of
1537/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001538QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001539 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Chris Lattnerf52ab252008-04-06 22:59:24 +00001542 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001543 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 // Check if we've already instantiated a vector of this type.
1546 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001547 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 void *InsertPos = 0;
1550 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1551 return QualType(VTP, 0);
1552
1553 // If the element type isn't canonical, this won't be a canonical type either,
1554 // so fill in the canonical type field.
1555 QualType Canonical;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001556 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1557 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1558 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1559 // the equivalent GCC vector types
1560 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1561 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 // Get the new insert position for the node we care about.
1564 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001565 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 }
John McCall6b304a02009-09-24 23:30:46 +00001567 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001568 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 VectorTypes.InsertNode(New, InsertPos);
1570 Types.push_back(New);
1571 return QualType(New, 0);
1572}
1573
Nate Begeman213541a2008-04-18 23:10:10 +00001574/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001575/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001576QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001577 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Chris Lattnerf52ab252008-04-06 22:59:24 +00001579 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001580 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Steve Naroff73322922007-07-18 18:00:27 +00001582 // Check if we've already instantiated a vector of this type.
1583 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001584 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1585 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001586 void *InsertPos = 0;
1587 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1588 return QualType(VTP, 0);
1589
1590 // If the element type isn't canonical, this won't be a canonical type either,
1591 // so fill in the canonical type field.
1592 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001593 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001594 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Steve Naroff73322922007-07-18 18:00:27 +00001596 // Get the new insert position for the node we care about.
1597 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001598 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001599 }
John McCall6b304a02009-09-24 23:30:46 +00001600 ExtVectorType *New = new (*this, TypeAlignment)
1601 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001602 VectorTypes.InsertNode(New, InsertPos);
1603 Types.push_back(New);
1604 return QualType(New, 0);
1605}
1606
Mike Stump1eb44332009-09-09 15:08:12 +00001607QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001608 Expr *SizeExpr,
1609 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001610 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001611 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001612 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001614 void *InsertPos = 0;
1615 DependentSizedExtVectorType *Canon
1616 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1617 DependentSizedExtVectorType *New;
1618 if (Canon) {
1619 // We already have a canonical version of this array type; use it as
1620 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001621 New = new (*this, TypeAlignment)
1622 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1623 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001624 } else {
1625 QualType CanonVecTy = getCanonicalType(vecType);
1626 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001627 New = new (*this, TypeAlignment)
1628 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1629 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001630
1631 DependentSizedExtVectorType *CanonCheck
1632 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1633 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1634 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001635 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1636 } else {
1637 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1638 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001639 New = new (*this, TypeAlignment)
1640 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001641 }
1642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001644 Types.push_back(New);
1645 return QualType(New, 0);
1646}
1647
Douglas Gregor72564e72009-02-26 23:50:07 +00001648/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001649///
Rafael Espindola264ba482010-03-30 20:24:48 +00001650QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1651 const FunctionType::ExtInfo &Info) {
1652 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 // Unique functions, to guarantee there is only one function of a particular
1654 // structure.
1655 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001656 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001659 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001660 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001664 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001665 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001666 Canonical =
1667 getFunctionNoProtoType(getCanonicalType(ResultTy),
1668 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001671 FunctionNoProtoType *NewIP =
1672 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001673 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 }
Mike Stump1eb44332009-09-09 15:08:12 +00001675
John McCall6b304a02009-09-24 23:30:46 +00001676 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001677 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001679 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 return QualType(New, 0);
1681}
1682
1683/// getFunctionType - Return a normal function type with a typed argument
1684/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001685QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001686 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001687 unsigned TypeQuals, bool hasExceptionSpec,
1688 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001689 const QualType *ExArray,
1690 const FunctionType::ExtInfo &Info) {
1691 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 // Unique functions, to guarantee there is only one function of a particular
1693 // structure.
1694 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001696 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001697 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698
1699 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001700 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001701 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001703
1704 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001705 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001707 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 isCanonical = false;
1709
1710 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001711 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001713 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 llvm::SmallVector<QualType, 16> CanonicalArgs;
1715 CanonicalArgs.reserve(NumArgs);
1716 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001717 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001718
Chris Lattnerf52ab252008-04-06 22:59:24 +00001719 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001720 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001721 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001722 false, 0, 0,
1723 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001724
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001726 FunctionProtoType *NewIP =
1727 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001728 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001730
Douglas Gregor72564e72009-02-26 23:50:07 +00001731 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001732 // for two variable size arrays (for parameter and exception types) at the
1733 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001734 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001735 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1736 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001737 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001738 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001739 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001740 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001742 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 return QualType(FTP, 0);
1744}
1745
John McCall3cb0ebd2010-03-10 03:28:59 +00001746#ifndef NDEBUG
1747static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1748 if (!isa<CXXRecordDecl>(D)) return false;
1749 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1750 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1751 return true;
1752 if (RD->getDescribedClassTemplate() &&
1753 !isa<ClassTemplateSpecializationDecl>(RD))
1754 return true;
1755 return false;
1756}
1757#endif
1758
1759/// getInjectedClassNameType - Return the unique reference to the
1760/// injected class name type for the specified templated declaration.
1761QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1762 QualType TST) {
1763 assert(NeedsInjectedClassNameType(Decl));
1764 if (Decl->TypeForDecl) {
1765 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001766 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001767 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1768 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1769 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1770 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001771 Decl->TypeForDecl =
1772 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001773 Types.push_back(Decl->TypeForDecl);
1774 }
1775 return QualType(Decl->TypeForDecl, 0);
1776}
1777
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001778/// getTypeDeclType - Return the unique reference to the type for the
1779/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001780QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001781 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001782 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001783
John McCall19c85762010-02-16 03:57:14 +00001784 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001785 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001786
John McCallbecb8d52010-03-10 06:48:02 +00001787 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1788 "Template type parameter types are always available.");
1789
John McCall19c85762010-02-16 03:57:14 +00001790 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001791 assert(!Record->getPreviousDeclaration() &&
1792 "struct/union has previous declaration");
1793 assert(!NeedsInjectedClassNameType(Record));
1794 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001795 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001796 assert(!Enum->getPreviousDeclaration() &&
1797 "enum has previous declaration");
1798 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001799 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001800 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1801 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001802 } else
John McCallbecb8d52010-03-10 06:48:02 +00001803 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001804
John McCallbecb8d52010-03-10 06:48:02 +00001805 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001806 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001807}
1808
Reid Spencer5f016e22007-07-11 17:01:13 +00001809/// getTypedefType - Return the unique reference to the type for the
1810/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001811QualType
1812ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001815 if (Canonical.isNull())
1816 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001817 Decl->TypeForDecl = new(*this, TypeAlignment)
1818 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 Types.push_back(Decl->TypeForDecl);
1820 return QualType(Decl->TypeForDecl, 0);
1821}
1822
John McCall49a832b2009-10-18 09:09:24 +00001823/// \brief Retrieve a substitution-result type.
1824QualType
1825ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1826 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001827 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001828 && "replacement types must always be canonical");
1829
1830 llvm::FoldingSetNodeID ID;
1831 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1832 void *InsertPos = 0;
1833 SubstTemplateTypeParmType *SubstParm
1834 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1835
1836 if (!SubstParm) {
1837 SubstParm = new (*this, TypeAlignment)
1838 SubstTemplateTypeParmType(Parm, Replacement);
1839 Types.push_back(SubstParm);
1840 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1841 }
1842
1843 return QualType(SubstParm, 0);
1844}
1845
Douglas Gregorfab9d672009-02-05 23:33:38 +00001846/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001847/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001848/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001849QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001850 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001851 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001852 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001853 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001854 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001855 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001856 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1857
1858 if (TypeParm)
1859 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregorefed5c82010-06-16 15:23:05 +00001861 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001862 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001863 TypeParm = new (*this, TypeAlignment)
1864 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001865
1866 TemplateTypeParmType *TypeCheck
1867 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1868 assert(!TypeCheck && "Template type parameter canonical type broken");
1869 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001870 } else
John McCall6b304a02009-09-24 23:30:46 +00001871 TypeParm = new (*this, TypeAlignment)
1872 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001873
1874 Types.push_back(TypeParm);
1875 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1876
1877 return QualType(TypeParm, 0);
1878}
1879
John McCall3cb0ebd2010-03-10 03:28:59 +00001880TypeSourceInfo *
1881ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1882 SourceLocation NameLoc,
1883 const TemplateArgumentListInfo &Args,
1884 QualType CanonType) {
1885 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1886
1887 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1888 TemplateSpecializationTypeLoc TL
1889 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1890 TL.setTemplateNameLoc(NameLoc);
1891 TL.setLAngleLoc(Args.getLAngleLoc());
1892 TL.setRAngleLoc(Args.getRAngleLoc());
1893 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1894 TL.setArgLocInfo(i, Args[i].getLocInfo());
1895 return DI;
1896}
1897
Mike Stump1eb44332009-09-09 15:08:12 +00001898QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001899ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001900 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001901 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001902 unsigned NumArgs = Args.size();
1903
John McCall833ca992009-10-29 08:12:44 +00001904 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1905 ArgVec.reserve(NumArgs);
1906 for (unsigned i = 0; i != NumArgs; ++i)
1907 ArgVec.push_back(Args[i].getArgument());
1908
John McCall31f17ec2010-04-27 00:57:59 +00001909 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001910 Canon);
John McCall833ca992009-10-29 08:12:44 +00001911}
1912
1913QualType
1914ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001915 const TemplateArgument *Args,
1916 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001917 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001918 if (!Canon.isNull())
1919 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001920 else
1921 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001922
Douglas Gregor1275ae02009-07-28 23:00:59 +00001923 // Allocate the (non-canonical) template specialization type, but don't
1924 // try to unique it: these types typically have location information that
1925 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001926 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001927 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001928 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001929 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001930 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001931 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001932 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Douglas Gregor55f6b142009-02-09 18:46:07 +00001934 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001935 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001936}
1937
Mike Stump1eb44332009-09-09 15:08:12 +00001938QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001939ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1940 const TemplateArgument *Args,
1941 unsigned NumArgs) {
1942 // Build the canonical template specialization type.
1943 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1944 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1945 CanonArgs.reserve(NumArgs);
1946 for (unsigned I = 0; I != NumArgs; ++I)
1947 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1948
1949 // Determine whether this canonical template specialization type already
1950 // exists.
1951 llvm::FoldingSetNodeID ID;
1952 TemplateSpecializationType::Profile(ID, CanonTemplate,
1953 CanonArgs.data(), NumArgs, *this);
1954
1955 void *InsertPos = 0;
1956 TemplateSpecializationType *Spec
1957 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1958
1959 if (!Spec) {
1960 // Allocate a new canonical template specialization type.
1961 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1962 sizeof(TemplateArgument) * NumArgs),
1963 TypeAlignment);
1964 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1965 CanonArgs.data(), NumArgs,
1966 QualType());
1967 Types.push_back(Spec);
1968 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1969 }
1970
1971 assert(Spec->isDependentType() &&
1972 "Non-dependent template-id type must have a canonical type");
1973 return QualType(Spec, 0);
1974}
1975
1976QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001977ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1978 NestedNameSpecifier *NNS,
1979 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001980 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001981 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001982
1983 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001984 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001985 if (T)
1986 return QualType(T, 0);
1987
Douglas Gregor789b1f62010-02-04 18:10:26 +00001988 QualType Canon = NamedType;
1989 if (!Canon.isCanonical()) {
1990 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001991 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1992 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001993 (void)CheckT;
1994 }
1995
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001996 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001997 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001998 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001999 return QualType(T, 0);
2000}
2001
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002002QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2003 NestedNameSpecifier *NNS,
2004 const IdentifierInfo *Name,
2005 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002006 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2007
2008 if (Canon.isNull()) {
2009 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002010 ElaboratedTypeKeyword CanonKeyword = Keyword;
2011 if (Keyword == ETK_None)
2012 CanonKeyword = ETK_Typename;
2013
2014 if (CanonNNS != NNS || CanonKeyword != Keyword)
2015 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002016 }
2017
2018 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002019 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002020
2021 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002022 DependentNameType *T
2023 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002024 if (T)
2025 return QualType(T, 0);
2026
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002027 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002028 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002029 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002030 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002031}
2032
Mike Stump1eb44332009-09-09 15:08:12 +00002033QualType
John McCall33500952010-06-11 00:33:02 +00002034ASTContext::getDependentTemplateSpecializationType(
2035 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002036 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002037 const IdentifierInfo *Name,
2038 const TemplateArgumentListInfo &Args) {
2039 // TODO: avoid this copy
2040 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2041 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2042 ArgCopy.push_back(Args[I].getArgument());
2043 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2044 ArgCopy.size(),
2045 ArgCopy.data());
2046}
2047
2048QualType
2049ASTContext::getDependentTemplateSpecializationType(
2050 ElaboratedTypeKeyword Keyword,
2051 NestedNameSpecifier *NNS,
2052 const IdentifierInfo *Name,
2053 unsigned NumArgs,
2054 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002055 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2056
Douglas Gregor789b1f62010-02-04 18:10:26 +00002057 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002058 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2059 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002060
2061 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002062 DependentTemplateSpecializationType *T
2063 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002064 if (T)
2065 return QualType(T, 0);
2066
John McCall33500952010-06-11 00:33:02 +00002067 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002068
John McCall33500952010-06-11 00:33:02 +00002069 ElaboratedTypeKeyword CanonKeyword = Keyword;
2070 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2071
2072 bool AnyNonCanonArgs = false;
2073 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2074 for (unsigned I = 0; I != NumArgs; ++I) {
2075 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2076 if (!CanonArgs[I].structurallyEquals(Args[I]))
2077 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002078 }
2079
John McCall33500952010-06-11 00:33:02 +00002080 QualType Canon;
2081 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2082 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2083 Name, NumArgs,
2084 CanonArgs.data());
2085
2086 // Find the insert position again.
2087 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2088 }
2089
2090 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2091 sizeof(TemplateArgument) * NumArgs),
2092 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002093 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002094 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002095 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002096 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002097 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002098}
2099
Chris Lattner88cb27a2008-04-07 04:56:42 +00002100/// CmpProtocolNames - Comparison predicate for sorting protocols
2101/// alphabetically.
2102static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2103 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002104 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002105}
2106
John McCallc12c5bb2010-05-15 11:32:37 +00002107static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002108 unsigned NumProtocols) {
2109 if (NumProtocols == 0) return true;
2110
2111 for (unsigned i = 1; i != NumProtocols; ++i)
2112 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2113 return false;
2114 return true;
2115}
2116
2117static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002118 unsigned &NumProtocols) {
2119 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Chris Lattner88cb27a2008-04-07 04:56:42 +00002121 // Sort protocols, keyed by name.
2122 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2123
2124 // Remove duplicates.
2125 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2126 NumProtocols = ProtocolsEnd-Protocols;
2127}
2128
John McCallc12c5bb2010-05-15 11:32:37 +00002129QualType ASTContext::getObjCObjectType(QualType BaseType,
2130 ObjCProtocolDecl * const *Protocols,
2131 unsigned NumProtocols) {
2132 // If the base type is an interface and there aren't any protocols
2133 // to add, then the interface type will do just fine.
2134 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2135 return BaseType;
2136
2137 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002138 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002139 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002140 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002141 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2142 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002143
John McCallc12c5bb2010-05-15 11:32:37 +00002144 // Build the canonical type, which has the canonical base type and
2145 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002146 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002147 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2148 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2149 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002150 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2151 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002152 unsigned UniqueCount = NumProtocols;
2153
John McCall54e14c42009-10-22 22:37:11 +00002154 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002155 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2156 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002157 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002158 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2159 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002160 }
2161
2162 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002163 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2164 }
2165
2166 unsigned Size = sizeof(ObjCObjectTypeImpl);
2167 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2168 void *Mem = Allocate(Size, TypeAlignment);
2169 ObjCObjectTypeImpl *T =
2170 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2171
2172 Types.push_back(T);
2173 ObjCObjectTypes.InsertNode(T, InsertPos);
2174 return QualType(T, 0);
2175}
2176
2177/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2178/// the given object type.
2179QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2180 llvm::FoldingSetNodeID ID;
2181 ObjCObjectPointerType::Profile(ID, ObjectT);
2182
2183 void *InsertPos = 0;
2184 if (ObjCObjectPointerType *QT =
2185 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2186 return QualType(QT, 0);
2187
2188 // Find the canonical object type.
2189 QualType Canonical;
2190 if (!ObjectT.isCanonical()) {
2191 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2192
2193 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002194 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2195 }
2196
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002197 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002198 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2199 ObjCObjectPointerType *QType =
2200 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002202 Types.push_back(QType);
2203 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002204 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002205}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002206
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002207/// getObjCInterfaceType - Return the unique reference to the type for the
2208/// specified ObjC interface decl. The list of protocols is optional.
John McCallc12c5bb2010-05-15 11:32:37 +00002209QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2210 if (Decl->TypeForDecl)
2211 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
John McCallc12c5bb2010-05-15 11:32:37 +00002213 // FIXME: redeclarations?
2214 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2215 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2216 Decl->TypeForDecl = T;
2217 Types.push_back(T);
2218 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002219}
2220
Douglas Gregor72564e72009-02-26 23:50:07 +00002221/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2222/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002223/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002224/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002225/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002226QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002227 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002228 if (tofExpr->isTypeDependent()) {
2229 llvm::FoldingSetNodeID ID;
2230 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Douglas Gregorb1975722009-07-30 23:18:24 +00002232 void *InsertPos = 0;
2233 DependentTypeOfExprType *Canon
2234 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2235 if (Canon) {
2236 // We already have a "canonical" version of an identical, dependent
2237 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002238 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002239 QualType((TypeOfExprType*)Canon, 0));
2240 }
2241 else {
2242 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002243 Canon
2244 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002245 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2246 toe = Canon;
2247 }
2248 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002249 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002250 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002251 }
Steve Naroff9752f252007-08-01 18:02:17 +00002252 Types.push_back(toe);
2253 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002254}
2255
Steve Naroff9752f252007-08-01 18:02:17 +00002256/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2257/// TypeOfType AST's. The only motivation to unique these nodes would be
2258/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002259/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002260/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002261QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002262 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002263 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002264 Types.push_back(tot);
2265 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002266}
2267
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002268/// getDecltypeForExpr - Given an expr, will return the decltype for that
2269/// expression, according to the rules in C++0x [dcl.type.simple]p4
2270static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002271 if (e->isTypeDependent())
2272 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002274 // If e is an id expression or a class member access, decltype(e) is defined
2275 // as the type of the entity named by e.
2276 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2277 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2278 return VD->getType();
2279 }
2280 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2281 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2282 return FD->getType();
2283 }
2284 // If e is a function call or an invocation of an overloaded operator,
2285 // (parentheses around e are ignored), decltype(e) is defined as the
2286 // return type of that function.
2287 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2288 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002290 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002291
2292 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002293 // defined as T&, otherwise decltype(e) is defined as T.
2294 if (e->isLvalue(Context) == Expr::LV_Valid)
2295 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002297 return T;
2298}
2299
Anders Carlsson395b4752009-06-24 19:06:50 +00002300/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2301/// DecltypeType AST's. The only motivation to unique these nodes would be
2302/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002303/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002304/// on canonical type's (which are always unique).
2305QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002306 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002307 if (e->isTypeDependent()) {
2308 llvm::FoldingSetNodeID ID;
2309 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002311 void *InsertPos = 0;
2312 DependentDecltypeType *Canon
2313 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2314 if (Canon) {
2315 // We already have a "canonical" version of an equivalent, dependent
2316 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002317 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002318 QualType((DecltypeType*)Canon, 0));
2319 }
2320 else {
2321 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002322 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002323 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2324 dt = Canon;
2325 }
2326 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002327 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002328 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002329 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002330 Types.push_back(dt);
2331 return QualType(dt, 0);
2332}
2333
Reid Spencer5f016e22007-07-11 17:01:13 +00002334/// getTagDeclType - Return the unique reference to the type for the
2335/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002336QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002337 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002338 // FIXME: What is the design on getTagDeclType when it requires casting
2339 // away const? mutable?
2340 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002341}
2342
Mike Stump1eb44332009-09-09 15:08:12 +00002343/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2344/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2345/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002346CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002347 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002348}
2349
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002350/// getSignedWCharType - Return the type of "signed wchar_t".
2351/// Used when in C++, as a GCC extension.
2352QualType ASTContext::getSignedWCharType() const {
2353 // FIXME: derive from "Target" ?
2354 return WCharTy;
2355}
2356
2357/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2358/// Used when in C++, as a GCC extension.
2359QualType ASTContext::getUnsignedWCharType() const {
2360 // FIXME: derive from "Target" ?
2361 return UnsignedIntTy;
2362}
2363
Chris Lattner8b9023b2007-07-13 03:05:23 +00002364/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2365/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2366QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002367 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002368}
2369
Chris Lattnere6327742008-04-02 05:18:44 +00002370//===----------------------------------------------------------------------===//
2371// Type Operators
2372//===----------------------------------------------------------------------===//
2373
John McCall54e14c42009-10-22 22:37:11 +00002374CanQualType ASTContext::getCanonicalParamType(QualType T) {
2375 // Push qualifiers into arrays, and then discard any remaining
2376 // qualifiers.
2377 T = getCanonicalType(T);
2378 const Type *Ty = T.getTypePtr();
2379
2380 QualType Result;
2381 if (isa<ArrayType>(Ty)) {
2382 Result = getArrayDecayedType(QualType(Ty,0));
2383 } else if (isa<FunctionType>(Ty)) {
2384 Result = getPointerType(QualType(Ty, 0));
2385 } else {
2386 Result = QualType(Ty, 0);
2387 }
2388
2389 return CanQualType::CreateUnsafe(Result);
2390}
2391
Chris Lattner77c96472008-04-06 22:41:35 +00002392/// getCanonicalType - Return the canonical (structural) type corresponding to
2393/// the specified potentially non-canonical type. The non-canonical version
2394/// of a type may have many "decorated" versions of types. Decorators can
2395/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2396/// to be free of any of these, allowing two canonical types to be compared
2397/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002398CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002399 QualifierCollector Quals;
2400 const Type *Ptr = Quals.strip(T);
2401 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002402
John McCall0953e762009-09-24 19:53:00 +00002403 // The canonical internal type will be the canonical type *except*
2404 // that we push type qualifiers down through array types.
2405
2406 // If there are no new qualifiers to push down, stop here.
2407 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002408 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002409
John McCall0953e762009-09-24 19:53:00 +00002410 // If the type qualifiers are on an array type, get the canonical
2411 // type of the array with the qualifiers applied to the element
2412 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002413 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2414 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002415 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002417 // Get the canonical version of the element with the extra qualifiers on it.
2418 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002419 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002420 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002421
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002422 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002423 return CanQualType::CreateUnsafe(
2424 getConstantArrayType(NewEltTy, CAT->getSize(),
2425 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002426 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002427 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002428 return CanQualType::CreateUnsafe(
2429 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002430 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Douglas Gregor898574e2008-12-05 23:32:09 +00002432 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002433 return CanQualType::CreateUnsafe(
2434 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002435 DSAT->getSizeExpr() ?
2436 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002437 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002438 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002439 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002440
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002441 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002442 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002443 VAT->getSizeExpr() ?
2444 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002445 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002446 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002447 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002448}
2449
Chandler Carruth28e318c2009-12-29 07:16:59 +00002450QualType ASTContext::getUnqualifiedArrayType(QualType T,
2451 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002452 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002453 const ArrayType *AT = getAsArrayType(T);
2454 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002455 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002456 }
2457
Chandler Carruth28e318c2009-12-29 07:16:59 +00002458 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002459 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002460 if (Elt == UnqualElt)
2461 return T;
2462
Douglas Gregor9dadd942010-05-17 18:45:21 +00002463 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002464 return getConstantArrayType(UnqualElt, CAT->getSize(),
2465 CAT->getSizeModifier(), 0);
2466 }
2467
Douglas Gregor9dadd942010-05-17 18:45:21 +00002468 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002469 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2470 }
2471
Douglas Gregor9dadd942010-05-17 18:45:21 +00002472 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2473 return getVariableArrayType(UnqualElt,
2474 VAT->getSizeExpr() ?
2475 VAT->getSizeExpr()->Retain() : 0,
2476 VAT->getSizeModifier(),
2477 VAT->getIndexTypeCVRQualifiers(),
2478 VAT->getBracketsRange());
2479 }
2480
2481 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002482 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2483 DSAT->getSizeModifier(), 0,
2484 SourceRange());
2485}
2486
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002487/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2488/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2489/// they point to and return true. If T1 and T2 aren't pointer types
2490/// or pointer-to-member types, or if they are not similar at this
2491/// level, returns false and leaves T1 and T2 unchanged. Top-level
2492/// qualifiers on T1 and T2 are ignored. This function will typically
2493/// be called in a loop that successively "unwraps" pointer and
2494/// pointer-to-member types to compare them at each level.
2495bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2496 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2497 *T2PtrType = T2->getAs<PointerType>();
2498 if (T1PtrType && T2PtrType) {
2499 T1 = T1PtrType->getPointeeType();
2500 T2 = T2PtrType->getPointeeType();
2501 return true;
2502 }
2503
2504 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2505 *T2MPType = T2->getAs<MemberPointerType>();
2506 if (T1MPType && T2MPType &&
2507 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2508 QualType(T2MPType->getClass(), 0))) {
2509 T1 = T1MPType->getPointeeType();
2510 T2 = T2MPType->getPointeeType();
2511 return true;
2512 }
2513
2514 if (getLangOptions().ObjC1) {
2515 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2516 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2517 if (T1OPType && T2OPType) {
2518 T1 = T1OPType->getPointeeType();
2519 T2 = T2OPType->getPointeeType();
2520 return true;
2521 }
2522 }
2523
2524 // FIXME: Block pointers, too?
2525
2526 return false;
2527}
2528
John McCall80ad16f2009-11-24 18:42:40 +00002529DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2530 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2531 return TD->getDeclName();
2532
2533 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2534 if (DTN->isIdentifier()) {
2535 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2536 } else {
2537 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2538 }
2539 }
2540
John McCall0bd6feb2009-12-02 08:04:21 +00002541 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2542 assert(Storage);
2543 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002544}
2545
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002546TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002547 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2548 if (TemplateTemplateParmDecl *TTP
2549 = dyn_cast<TemplateTemplateParmDecl>(Template))
2550 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2551
2552 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002553 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002554 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002555
John McCall0bd6feb2009-12-02 08:04:21 +00002556 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002558 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2559 assert(DTN && "Non-dependent template names must refer to template decls.");
2560 return DTN->CanonicalTemplateName;
2561}
2562
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002563bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2564 X = getCanonicalTemplateName(X);
2565 Y = getCanonicalTemplateName(Y);
2566 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2567}
2568
Mike Stump1eb44332009-09-09 15:08:12 +00002569TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002570ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2571 switch (Arg.getKind()) {
2572 case TemplateArgument::Null:
2573 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Douglas Gregor1275ae02009-07-28 23:00:59 +00002575 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002576 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Douglas Gregor1275ae02009-07-28 23:00:59 +00002578 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002579 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Douglas Gregor788cd062009-11-11 01:00:40 +00002581 case TemplateArgument::Template:
2582 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2583
Douglas Gregor1275ae02009-07-28 23:00:59 +00002584 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002585 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002586 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Douglas Gregor1275ae02009-07-28 23:00:59 +00002588 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002589 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregor1275ae02009-07-28 23:00:59 +00002591 case TemplateArgument::Pack: {
2592 // FIXME: Allocate in ASTContext
2593 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2594 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002595 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002596 AEnd = Arg.pack_end();
2597 A != AEnd; (void)++A, ++Idx)
2598 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Douglas Gregor1275ae02009-07-28 23:00:59 +00002600 TemplateArgument Result;
2601 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2602 return Result;
2603 }
2604 }
2605
2606 // Silence GCC warning
2607 assert(false && "Unhandled template argument kind");
2608 return TemplateArgument();
2609}
2610
Douglas Gregord57959a2009-03-27 23:10:48 +00002611NestedNameSpecifier *
2612ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002613 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002614 return 0;
2615
2616 switch (NNS->getKind()) {
2617 case NestedNameSpecifier::Identifier:
2618 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002619 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002620 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2621 NNS->getAsIdentifier());
2622
2623 case NestedNameSpecifier::Namespace:
2624 // A namespace is canonical; build a nested-name-specifier with
2625 // this namespace and no prefix.
2626 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2627
2628 case NestedNameSpecifier::TypeSpec:
2629 case NestedNameSpecifier::TypeSpecWithTemplate: {
2630 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002631 return NestedNameSpecifier::Create(*this, 0,
2632 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002633 T.getTypePtr());
2634 }
2635
2636 case NestedNameSpecifier::Global:
2637 // The global specifier is canonical and unique.
2638 return NNS;
2639 }
2640
2641 // Required to silence a GCC warning
2642 return 0;
2643}
2644
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002645
2646const ArrayType *ASTContext::getAsArrayType(QualType T) {
2647 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002648 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002649 // Handle the common positive case fast.
2650 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2651 return AT;
2652 }
Mike Stump1eb44332009-09-09 15:08:12 +00002653
John McCall0953e762009-09-24 19:53:00 +00002654 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002655 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002656 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002657 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002658
John McCall0953e762009-09-24 19:53:00 +00002659 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002660 // implements C99 6.7.3p8: "If the specification of an array type includes
2661 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002663 // If we get here, we either have type qualifiers on the type, or we have
2664 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002665 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002666
John McCall0953e762009-09-24 19:53:00 +00002667 QualifierCollector Qs;
2668 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002670 // If we have a simple case, just return now.
2671 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002672 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002673 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002675 // Otherwise, we have an array and we have qualifiers on it. Push the
2676 // qualifiers into the array element type and return a new array type.
2677 // Get the canonical version of the element with the extra qualifiers on it.
2678 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002679 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002681 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2682 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2683 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002684 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002685 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2686 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2687 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002688 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002689
Mike Stump1eb44332009-09-09 15:08:12 +00002690 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002691 = dyn_cast<DependentSizedArrayType>(ATy))
2692 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002693 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002694 DSAT->getSizeExpr() ?
2695 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002696 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002697 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002698 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002700 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002701 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002702 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002703 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002704 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002705 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002706 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002707}
2708
2709
Chris Lattnere6327742008-04-02 05:18:44 +00002710/// getArrayDecayedType - Return the properly qualified result of decaying the
2711/// specified array type to a pointer. This operation is non-trivial when
2712/// handling typedefs etc. The canonical type of "T" must be an array type,
2713/// this returns a pointer to a properly qualified element of the array.
2714///
2715/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2716QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002717 // Get the element type with 'getAsArrayType' so that we don't lose any
2718 // typedefs in the element type of the array. This also handles propagation
2719 // of type qualifiers from the array type into the element type if present
2720 // (C99 6.7.3p8).
2721 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2722 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002724 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002725
2726 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002727 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002728}
2729
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002730QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002731 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002732 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2733 QT = AT->getElementType();
2734 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002735}
2736
Anders Carlssonfbbce492009-09-25 01:23:32 +00002737QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2738 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Anders Carlssonfbbce492009-09-25 01:23:32 +00002740 if (const ArrayType *AT = getAsArrayType(ElemTy))
2741 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Anders Carlsson6183a992008-12-21 03:44:36 +00002743 return ElemTy;
2744}
2745
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002746/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002747uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002748ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2749 uint64_t ElementCount = 1;
2750 do {
2751 ElementCount *= CA->getSize().getZExtValue();
2752 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2753 } while (CA);
2754 return ElementCount;
2755}
2756
Reid Spencer5f016e22007-07-11 17:01:13 +00002757/// getFloatingRank - Return a relative rank for floating point types.
2758/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002759static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002760 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002762
John McCall183700f2009-09-21 23:43:11 +00002763 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2764 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002765 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002766 case BuiltinType::Float: return FloatRank;
2767 case BuiltinType::Double: return DoubleRank;
2768 case BuiltinType::LongDouble: return LongDoubleRank;
2769 }
2770}
2771
Mike Stump1eb44332009-09-09 15:08:12 +00002772/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2773/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002774/// 'typeDomain' is a real floating point or complex type.
2775/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002776QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2777 QualType Domain) const {
2778 FloatingRank EltRank = getFloatingRank(Size);
2779 if (Domain->isComplexType()) {
2780 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002781 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002782 case FloatRank: return FloatComplexTy;
2783 case DoubleRank: return DoubleComplexTy;
2784 case LongDoubleRank: return LongDoubleComplexTy;
2785 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 }
Chris Lattner1361b112008-04-06 23:58:54 +00002787
2788 assert(Domain->isRealFloatingType() && "Unknown domain!");
2789 switch (EltRank) {
2790 default: assert(0 && "getFloatingRank(): illegal value for rank");
2791 case FloatRank: return FloatTy;
2792 case DoubleRank: return DoubleTy;
2793 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002794 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002795}
2796
Chris Lattner7cfeb082008-04-06 23:55:33 +00002797/// getFloatingTypeOrder - Compare the rank of the two specified floating
2798/// point types, ignoring the domain of the type (i.e. 'double' ==
2799/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002800/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002801int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2802 FloatingRank LHSR = getFloatingRank(LHS);
2803 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Chris Lattnera75cea32008-04-06 23:38:49 +00002805 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002806 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002807 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002808 return 1;
2809 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002810}
2811
Chris Lattnerf52ab252008-04-06 22:59:24 +00002812/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2813/// routine will assert if passed a built-in type that isn't an integer or enum,
2814/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002815unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002816 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002817 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002818 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002819
Eli Friedmana3426752009-07-05 23:44:27 +00002820 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2821 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2822
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002823 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2824 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2825
2826 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2827 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2828
Chris Lattnerf52ab252008-04-06 22:59:24 +00002829 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002830 default: assert(0 && "getIntegerRank(): not a built-in integer");
2831 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002832 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002833 case BuiltinType::Char_S:
2834 case BuiltinType::Char_U:
2835 case BuiltinType::SChar:
2836 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002837 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002838 case BuiltinType::Short:
2839 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002840 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002841 case BuiltinType::Int:
2842 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002843 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002844 case BuiltinType::Long:
2845 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002846 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002847 case BuiltinType::LongLong:
2848 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002849 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002850 case BuiltinType::Int128:
2851 case BuiltinType::UInt128:
2852 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002853 }
2854}
2855
Eli Friedman04e83572009-08-20 04:21:42 +00002856/// \brief Whether this is a promotable bitfield reference according
2857/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2858///
2859/// \returns the type this bit-field will promote to, or NULL if no
2860/// promotion occurs.
2861QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002862 if (E->isTypeDependent() || E->isValueDependent())
2863 return QualType();
2864
Eli Friedman04e83572009-08-20 04:21:42 +00002865 FieldDecl *Field = E->getBitField();
2866 if (!Field)
2867 return QualType();
2868
2869 QualType FT = Field->getType();
2870
2871 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2872 uint64_t BitWidth = BitWidthAP.getZExtValue();
2873 uint64_t IntSize = getTypeSize(IntTy);
2874 // GCC extension compatibility: if the bit-field size is less than or equal
2875 // to the size of int, it gets promoted no matter what its type is.
2876 // For instance, unsigned long bf : 4 gets promoted to signed int.
2877 if (BitWidth < IntSize)
2878 return IntTy;
2879
2880 if (BitWidth == IntSize)
2881 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2882
2883 // Types bigger than int are not subject to promotions, and therefore act
2884 // like the base type.
2885 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2886 // is ridiculous.
2887 return QualType();
2888}
2889
Eli Friedmana95d7572009-08-19 07:44:53 +00002890/// getPromotedIntegerType - Returns the type that Promotable will
2891/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2892/// integer type.
2893QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2894 assert(!Promotable.isNull());
2895 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002896 if (const EnumType *ET = Promotable->getAs<EnumType>())
2897 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002898 if (Promotable->isSignedIntegerType())
2899 return IntTy;
2900 uint64_t PromotableSize = getTypeSize(Promotable);
2901 uint64_t IntSize = getTypeSize(IntTy);
2902 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2903 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2904}
2905
Mike Stump1eb44332009-09-09 15:08:12 +00002906/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002907/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002908/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002909int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002910 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2911 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002912 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Chris Lattnerf52ab252008-04-06 22:59:24 +00002914 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2915 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Chris Lattner7cfeb082008-04-06 23:55:33 +00002917 unsigned LHSRank = getIntegerRank(LHSC);
2918 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Chris Lattner7cfeb082008-04-06 23:55:33 +00002920 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2921 if (LHSRank == RHSRank) return 0;
2922 return LHSRank > RHSRank ? 1 : -1;
2923 }
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Chris Lattner7cfeb082008-04-06 23:55:33 +00002925 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2926 if (LHSUnsigned) {
2927 // If the unsigned [LHS] type is larger, return it.
2928 if (LHSRank >= RHSRank)
2929 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Chris Lattner7cfeb082008-04-06 23:55:33 +00002931 // If the signed type can represent all values of the unsigned type, it
2932 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002933 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002934 return -1;
2935 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002936
Chris Lattner7cfeb082008-04-06 23:55:33 +00002937 // If the unsigned [RHS] type is larger, return it.
2938 if (RHSRank >= LHSRank)
2939 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Chris Lattner7cfeb082008-04-06 23:55:33 +00002941 // If the signed type can represent all values of the unsigned type, it
2942 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002943 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002944 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002945}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002946
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002947static RecordDecl *
2948CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2949 SourceLocation L, IdentifierInfo *Id) {
2950 if (Ctx.getLangOptions().CPlusPlus)
2951 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2952 else
2953 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2954}
2955
Mike Stump1eb44332009-09-09 15:08:12 +00002956// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002957QualType ASTContext::getCFConstantStringType() {
2958 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002959 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002960 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002961 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002962 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002963
Anders Carlssonf06273f2007-11-19 00:25:30 +00002964 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Anders Carlsson71993dd2007-08-17 05:31:46 +00002966 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002967 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002968 // int flags;
2969 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002970 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002971 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002972 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002973 FieldTypes[3] = LongTy;
2974
Anders Carlsson71993dd2007-08-17 05:31:46 +00002975 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002976 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002977 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002978 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002979 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002980 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002981 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002982 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002983 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002984 }
2985
Douglas Gregor838db382010-02-11 01:19:42 +00002986 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002987 }
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Anders Carlsson71993dd2007-08-17 05:31:46 +00002989 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002990}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002991
Douglas Gregor319ac892009-04-23 22:29:11 +00002992void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002993 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002994 assert(Rec && "Invalid CFConstantStringType");
2995 CFConstantStringTypeDecl = Rec->getDecl();
2996}
2997
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002998// getNSConstantStringType - Return the type used for constant NSStrings.
2999QualType ASTContext::getNSConstantStringType() {
3000 if (!NSConstantStringTypeDecl) {
3001 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003002 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003003 &Idents.get("__builtin_NSString"));
3004 NSConstantStringTypeDecl->startDefinition();
3005
3006 QualType FieldTypes[3];
3007
3008 // const int *isa;
3009 FieldTypes[0] = getPointerType(IntTy.withConst());
3010 // const char *str;
3011 FieldTypes[1] = getPointerType(CharTy.withConst());
3012 // unsigned int length;
3013 FieldTypes[2] = UnsignedIntTy;
3014
3015 // Create fields
3016 for (unsigned i = 0; i < 3; ++i) {
3017 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3018 SourceLocation(), 0,
3019 FieldTypes[i], /*TInfo=*/0,
3020 /*BitWidth=*/0,
3021 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003022 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003023 NSConstantStringTypeDecl->addDecl(Field);
3024 }
3025
3026 NSConstantStringTypeDecl->completeDefinition();
3027 }
3028
3029 return getTagDeclType(NSConstantStringTypeDecl);
3030}
3031
3032void ASTContext::setNSConstantStringType(QualType T) {
3033 const RecordType *Rec = T->getAs<RecordType>();
3034 assert(Rec && "Invalid NSConstantStringType");
3035 NSConstantStringTypeDecl = Rec->getDecl();
3036}
3037
Mike Stump1eb44332009-09-09 15:08:12 +00003038QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003039 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003040 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003041 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003042 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003043 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003045 QualType FieldTypes[] = {
3046 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003047 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003048 getPointerType(UnsignedLongTy),
3049 getConstantArrayType(UnsignedLongTy,
3050 llvm::APInt(32, 5), ArrayType::Normal, 0)
3051 };
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Douglas Gregor44b43212008-12-11 16:49:14 +00003053 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003054 FieldDecl *Field = FieldDecl::Create(*this,
3055 ObjCFastEnumerationStateTypeDecl,
3056 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003057 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003058 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003059 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003060 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003061 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003062 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003063 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003064 if (CXXRecordDecl *CXXRD =
3065 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003066 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Douglas Gregor838db382010-02-11 01:19:42 +00003068 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003069 }
Mike Stump1eb44332009-09-09 15:08:12 +00003070
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003071 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3072}
3073
Mike Stumpadaaad32009-10-20 02:12:22 +00003074QualType ASTContext::getBlockDescriptorType() {
3075 if (BlockDescriptorType)
3076 return getTagDeclType(BlockDescriptorType);
3077
3078 RecordDecl *T;
3079 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003080 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003081 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003082 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003083
3084 QualType FieldTypes[] = {
3085 UnsignedLongTy,
3086 UnsignedLongTy,
3087 };
3088
3089 const char *FieldNames[] = {
3090 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003091 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003092 };
3093
3094 for (size_t i = 0; i < 2; ++i) {
3095 FieldDecl *Field = FieldDecl::Create(*this,
3096 T,
3097 SourceLocation(),
3098 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003099 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003100 /*BitWidth=*/0,
3101 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003102 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003103 T->addDecl(Field);
3104 }
3105
Douglas Gregor838db382010-02-11 01:19:42 +00003106 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003107
3108 BlockDescriptorType = T;
3109
3110 return getTagDeclType(BlockDescriptorType);
3111}
3112
3113void ASTContext::setBlockDescriptorType(QualType T) {
3114 const RecordType *Rec = T->getAs<RecordType>();
3115 assert(Rec && "Invalid BlockDescriptorType");
3116 BlockDescriptorType = Rec->getDecl();
3117}
3118
Mike Stump083c25e2009-10-22 00:49:09 +00003119QualType ASTContext::getBlockDescriptorExtendedType() {
3120 if (BlockDescriptorExtendedType)
3121 return getTagDeclType(BlockDescriptorExtendedType);
3122
3123 RecordDecl *T;
3124 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003125 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003126 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003127 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003128
3129 QualType FieldTypes[] = {
3130 UnsignedLongTy,
3131 UnsignedLongTy,
3132 getPointerType(VoidPtrTy),
3133 getPointerType(VoidPtrTy)
3134 };
3135
3136 const char *FieldNames[] = {
3137 "reserved",
3138 "Size",
3139 "CopyFuncPtr",
3140 "DestroyFuncPtr"
3141 };
3142
3143 for (size_t i = 0; i < 4; ++i) {
3144 FieldDecl *Field = FieldDecl::Create(*this,
3145 T,
3146 SourceLocation(),
3147 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003148 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003149 /*BitWidth=*/0,
3150 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003151 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003152 T->addDecl(Field);
3153 }
3154
Douglas Gregor838db382010-02-11 01:19:42 +00003155 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003156
3157 BlockDescriptorExtendedType = T;
3158
3159 return getTagDeclType(BlockDescriptorExtendedType);
3160}
3161
3162void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3163 const RecordType *Rec = T->getAs<RecordType>();
3164 assert(Rec && "Invalid BlockDescriptorType");
3165 BlockDescriptorExtendedType = Rec->getDecl();
3166}
3167
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003168bool ASTContext::BlockRequiresCopying(QualType Ty) {
3169 if (Ty->isBlockPointerType())
3170 return true;
3171 if (isObjCNSObjectType(Ty))
3172 return true;
3173 if (Ty->isObjCObjectPointerType())
3174 return true;
3175 return false;
3176}
3177
3178QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3179 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003180 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003181 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003182 // unsigned int __flags;
3183 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003184 // void *__copy_helper; // as needed
3185 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003186 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003187 // } *
3188
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003189 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3190
3191 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003192 llvm::SmallString<36> Name;
3193 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3194 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003195 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003196 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003197 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003198 T->startDefinition();
3199 QualType Int32Ty = IntTy;
3200 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3201 QualType FieldTypes[] = {
3202 getPointerType(VoidPtrTy),
3203 getPointerType(getTagDeclType(T)),
3204 Int32Ty,
3205 Int32Ty,
3206 getPointerType(VoidPtrTy),
3207 getPointerType(VoidPtrTy),
3208 Ty
3209 };
3210
3211 const char *FieldNames[] = {
3212 "__isa",
3213 "__forwarding",
3214 "__flags",
3215 "__size",
3216 "__copy_helper",
3217 "__destroy_helper",
3218 DeclName,
3219 };
3220
3221 for (size_t i = 0; i < 7; ++i) {
3222 if (!HasCopyAndDispose && i >=4 && i <= 5)
3223 continue;
3224 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3225 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003226 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003227 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003228 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003229 T->addDecl(Field);
3230 }
3231
Douglas Gregor838db382010-02-11 01:19:42 +00003232 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003233
3234 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003235}
3236
3237
3238QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003239 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003240 llvm::SmallVectorImpl<const Expr *> &Layout) {
3241
Mike Stumpadaaad32009-10-20 02:12:22 +00003242 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003243 llvm::SmallString<36> Name;
3244 llvm::raw_svector_ostream(Name) << "__block_literal_"
3245 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003246 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003247 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003248 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003249 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003250 QualType FieldTypes[] = {
3251 getPointerType(VoidPtrTy),
3252 IntTy,
3253 IntTy,
3254 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003255 (BlockHasCopyDispose ?
3256 getPointerType(getBlockDescriptorExtendedType()) :
3257 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003258 };
3259
3260 const char *FieldNames[] = {
3261 "__isa",
3262 "__flags",
3263 "__reserved",
3264 "__FuncPtr",
3265 "__descriptor"
3266 };
3267
3268 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003269 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003270 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003271 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003272 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003273 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003274 T->addDecl(Field);
3275 }
3276
John McCallea1471e2010-05-20 01:18:31 +00003277 for (unsigned i = 0; i < Layout.size(); ++i) {
3278 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003279
John McCallea1471e2010-05-20 01:18:31 +00003280 QualType FieldType = E->getType();
3281 IdentifierInfo *FieldName = 0;
3282 if (isa<CXXThisExpr>(E)) {
3283 FieldName = &Idents.get("this");
3284 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3285 const ValueDecl *D = BDRE->getDecl();
3286 FieldName = D->getIdentifier();
3287 if (BDRE->isByRef())
3288 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3289 } else {
3290 // Padding.
3291 assert(isa<ConstantArrayType>(FieldType) &&
3292 isa<DeclRefExpr>(E) &&
3293 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3294 "doesn't match characteristics of padding decl");
3295 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003296
3297 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003298 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003299 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003300 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003301 T->addDecl(Field);
3302 }
3303
Douglas Gregor838db382010-02-11 01:19:42 +00003304 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003305
3306 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003307}
3308
Douglas Gregor319ac892009-04-23 22:29:11 +00003309void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003310 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003311 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3312 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3313}
3314
Anders Carlssone8c49532007-10-29 06:33:42 +00003315// This returns true if a type has been typedefed to BOOL:
3316// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003317static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003318 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003319 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3320 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003322 return false;
3323}
3324
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003325/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003326/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003327CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003328 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003330 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003331 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003332 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003333 // Treat arrays as pointers, since that's how they're passed in.
3334 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003335 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003336 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003337}
3338
3339static inline
3340std::string charUnitsToString(const CharUnits &CU) {
3341 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003342}
3343
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003344/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003345/// declaration.
3346void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3347 std::string& S) {
3348 const BlockDecl *Decl = Expr->getBlockDecl();
3349 QualType BlockTy =
3350 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3351 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003352 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003353 // Compute size of all parameters.
3354 // Start with computing size of a pointer in number of bytes.
3355 // FIXME: There might(should) be a better way of doing this computation!
3356 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003357 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3358 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003359 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003360 E = Decl->param_end(); PI != E; ++PI) {
3361 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003362 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003363 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003364 ParmOffset += sz;
3365 }
3366 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003367 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003368 // Block pointer and offset.
3369 S += "@?0";
3370 ParmOffset = PtrSize;
3371
3372 // Argument types.
3373 ParmOffset = PtrSize;
3374 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3375 Decl->param_end(); PI != E; ++PI) {
3376 ParmVarDecl *PVDecl = *PI;
3377 QualType PType = PVDecl->getOriginalType();
3378 if (const ArrayType *AT =
3379 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3380 // Use array's original type only if it has known number of
3381 // elements.
3382 if (!isa<ConstantArrayType>(AT))
3383 PType = PVDecl->getType();
3384 } else if (PType->isFunctionType())
3385 PType = PVDecl->getType();
3386 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003387 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003388 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003389 }
3390}
3391
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003392/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003393/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003394void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003395 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003396 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003397 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003398 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003399 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003400 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003401 // Compute size of all parameters.
3402 // Start with computing size of a pointer in number of bytes.
3403 // FIXME: There might(should) be a better way of doing this computation!
3404 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003405 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003406 // The first two arguments (self and _cmd) are pointers; account for
3407 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003408 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003409 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003410 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003411 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003412 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003413 assert (sz.isPositive() &&
3414 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003415 ParmOffset += sz;
3416 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003417 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003418 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003419 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003420
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003421 // Argument types.
3422 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003423 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003424 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003425 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003426 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003427 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003428 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3429 // Use array's original type only if it has known number of
3430 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003431 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003432 PType = PVDecl->getType();
3433 } else if (PType->isFunctionType())
3434 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003435 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003436 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003437 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003438 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003439 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003440 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003441 }
3442}
3443
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003444/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003445/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003446/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3447/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003448/// Property attributes are stored as a comma-delimited C string. The simple
3449/// attributes readonly and bycopy are encoded as single characters. The
3450/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3451/// encoded as single characters, followed by an identifier. Property types
3452/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003453/// these attributes are defined by the following enumeration:
3454/// @code
3455/// enum PropertyAttributes {
3456/// kPropertyReadOnly = 'R', // property is read-only.
3457/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3458/// kPropertyByref = '&', // property is a reference to the value last assigned
3459/// kPropertyDynamic = 'D', // property is dynamic
3460/// kPropertyGetter = 'G', // followed by getter selector name
3461/// kPropertySetter = 'S', // followed by setter selector name
3462/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3463/// kPropertyType = 't' // followed by old-style type encoding.
3464/// kPropertyWeak = 'W' // 'weak' property
3465/// kPropertyStrong = 'P' // property GC'able
3466/// kPropertyNonAtomic = 'N' // property non-atomic
3467/// };
3468/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003469void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003470 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003471 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003472 // Collect information from the property implementation decl(s).
3473 bool Dynamic = false;
3474 ObjCPropertyImplDecl *SynthesizePID = 0;
3475
3476 // FIXME: Duplicated code due to poor abstraction.
3477 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003478 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003479 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3480 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003481 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003482 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003483 ObjCPropertyImplDecl *PID = *i;
3484 if (PID->getPropertyDecl() == PD) {
3485 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3486 Dynamic = true;
3487 } else {
3488 SynthesizePID = PID;
3489 }
3490 }
3491 }
3492 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003493 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003494 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003495 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003496 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003497 ObjCPropertyImplDecl *PID = *i;
3498 if (PID->getPropertyDecl() == PD) {
3499 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3500 Dynamic = true;
3501 } else {
3502 SynthesizePID = PID;
3503 }
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003506 }
3507 }
3508
3509 // FIXME: This is not very efficient.
3510 S = "T";
3511
3512 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003513 // GCC has some special rules regarding encoding of properties which
3514 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003515 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003516 true /* outermost type */,
3517 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003518
3519 if (PD->isReadOnly()) {
3520 S += ",R";
3521 } else {
3522 switch (PD->getSetterKind()) {
3523 case ObjCPropertyDecl::Assign: break;
3524 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003525 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003526 }
3527 }
3528
3529 // It really isn't clear at all what this means, since properties
3530 // are "dynamic by default".
3531 if (Dynamic)
3532 S += ",D";
3533
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003534 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3535 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003537 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3538 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003539 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003540 }
3541
3542 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3543 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003544 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003545 }
3546
3547 if (SynthesizePID) {
3548 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3549 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003550 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003551 }
3552
3553 // FIXME: OBJCGC: weak & strong
3554}
3555
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003556/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003557/// Another legacy compatibility encoding: 32-bit longs are encoded as
3558/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003559/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3560///
3561void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003562 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003563 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003564 if (BT->getKind() == BuiltinType::ULong &&
3565 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003566 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003567 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003568 if (BT->getKind() == BuiltinType::Long &&
3569 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003570 PointeeTy = IntTy;
3571 }
3572 }
3573}
3574
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003575void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003576 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003577 // We follow the behavior of gcc, expanding structures which are
3578 // directly pointed to, and expanding embedded structures. Note that
3579 // these rules are sufficient to prevent recursive encoding of the
3580 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003581 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003582 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003583}
3584
David Chisnall64fd7e82010-06-04 01:10:52 +00003585static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3586 switch (T->getAs<BuiltinType>()->getKind()) {
3587 default: assert(0 && "Unhandled builtin type kind");
3588 case BuiltinType::Void: return 'v';
3589 case BuiltinType::Bool: return 'B';
3590 case BuiltinType::Char_U:
3591 case BuiltinType::UChar: return 'C';
3592 case BuiltinType::UShort: return 'S';
3593 case BuiltinType::UInt: return 'I';
3594 case BuiltinType::ULong:
3595 return
3596 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3597 case BuiltinType::UInt128: return 'T';
3598 case BuiltinType::ULongLong: return 'Q';
3599 case BuiltinType::Char_S:
3600 case BuiltinType::SChar: return 'c';
3601 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003602 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003603 case BuiltinType::Int: return 'i';
3604 case BuiltinType::Long:
3605 return
3606 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3607 case BuiltinType::LongLong: return 'q';
3608 case BuiltinType::Int128: return 't';
3609 case BuiltinType::Float: return 'f';
3610 case BuiltinType::Double: return 'd';
3611 case BuiltinType::LongDouble: return 'd';
3612 }
3613}
3614
Mike Stump1eb44332009-09-09 15:08:12 +00003615static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003616 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003617 const Expr *E = FD->getBitWidth();
3618 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3619 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003620 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003621 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3622 // The GNU runtime requires more information; bitfields are encoded as b,
3623 // then the offset (in bits) of the first element, then the type of the
3624 // bitfield, then the size in bits. For example, in this structure:
3625 //
3626 // struct
3627 // {
3628 // int integer;
3629 // int flags:2;
3630 // };
3631 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3632 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3633 // information is not especially sensible, but we're stuck with it for
3634 // compatibility with GCC, although providing it breaks anything that
3635 // actually uses runtime introspection and wants to work on both runtimes...
3636 if (!Ctx->getLangOptions().NeXTRuntime) {
3637 const RecordDecl *RD = FD->getParent();
3638 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3639 // FIXME: This same linear search is also used in ExprConstant - it might
3640 // be better if the FieldDecl stored its offset. We'd be increasing the
3641 // size of the object slightly, but saving some time every time it is used.
3642 unsigned i = 0;
3643 for (RecordDecl::field_iterator Field = RD->field_begin(),
3644 FieldEnd = RD->field_end();
3645 Field != FieldEnd; (void)++Field, ++i) {
3646 if (*Field == FD)
3647 break;
3648 }
3649 S += llvm::utostr(RL.getFieldOffset(i));
3650 S += ObjCEncodingForPrimitiveKind(Context, T);
3651 }
3652 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003653 S += llvm::utostr(N);
3654}
3655
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003656// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003657void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3658 bool ExpandPointedToStructures,
3659 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003660 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003661 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003662 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003663 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003664 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003665 return EncodeBitField(this, S, T, FD);
3666 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003667 return;
3668 }
Mike Stump1eb44332009-09-09 15:08:12 +00003669
John McCall183700f2009-09-21 23:43:11 +00003670 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003671 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003672 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003673 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003674 return;
3675 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003676
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003677 // encoding for pointer or r3eference types.
3678 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003679 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003680 if (PT->isObjCSelType()) {
3681 S += ':';
3682 return;
3683 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003684 PointeeTy = PT->getPointeeType();
3685 }
3686 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3687 PointeeTy = RT->getPointeeType();
3688 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003689 bool isReadOnly = false;
3690 // For historical/compatibility reasons, the read-only qualifier of the
3691 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3692 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003693 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003694 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003695 if (OutermostType && T.isConstQualified()) {
3696 isReadOnly = true;
3697 S += 'r';
3698 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003699 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003700 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003701 while (P->getAs<PointerType>())
3702 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003703 if (P.isConstQualified()) {
3704 isReadOnly = true;
3705 S += 'r';
3706 }
3707 }
3708 if (isReadOnly) {
3709 // Another legacy compatibility encoding. Some ObjC qualifier and type
3710 // combinations need to be rearranged.
3711 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003712 if (llvm::StringRef(S).endswith("nr"))
3713 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003714 }
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003716 if (PointeeTy->isCharType()) {
3717 // char pointer types should be encoded as '*' unless it is a
3718 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003719 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003720 S += '*';
3721 return;
3722 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003723 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003724 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3725 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3726 S += '#';
3727 return;
3728 }
3729 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3730 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3731 S += '@';
3732 return;
3733 }
3734 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003735 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003736 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003737 getLegacyIntegralTypeEncoding(PointeeTy);
3738
Mike Stump1eb44332009-09-09 15:08:12 +00003739 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003740 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003741 return;
3742 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003743
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003744 if (const ArrayType *AT =
3745 // Ignore type qualifiers etc.
3746 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003747 if (isa<IncompleteArrayType>(AT)) {
3748 // Incomplete arrays are encoded as a pointer to the array element.
3749 S += '^';
3750
Mike Stump1eb44332009-09-09 15:08:12 +00003751 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003752 false, ExpandStructures, FD);
3753 } else {
3754 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Anders Carlsson559a8332009-02-22 01:38:57 +00003756 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3757 S += llvm::utostr(CAT->getSize().getZExtValue());
3758 else {
3759 //Variable length arrays are encoded as a regular array with 0 elements.
3760 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3761 S += '0';
3762 }
Mike Stump1eb44332009-09-09 15:08:12 +00003763
3764 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003765 false, ExpandStructures, FD);
3766 S += ']';
3767 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003768 return;
3769 }
Mike Stump1eb44332009-09-09 15:08:12 +00003770
John McCall183700f2009-09-21 23:43:11 +00003771 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003772 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003773 return;
3774 }
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Ted Kremenek6217b802009-07-29 21:53:49 +00003776 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003777 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003778 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003779 // Anonymous structures print as '?'
3780 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3781 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003782 if (ClassTemplateSpecializationDecl *Spec
3783 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3784 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3785 std::string TemplateArgsStr
3786 = TemplateSpecializationType::PrintTemplateArgumentList(
3787 TemplateArgs.getFlatArgumentList(),
3788 TemplateArgs.flat_size(),
3789 (*this).PrintingPolicy);
3790
3791 S += TemplateArgsStr;
3792 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003793 } else {
3794 S += '?';
3795 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003796 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003797 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003798 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3799 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003800 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003801 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003802 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003803 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003804 S += '"';
3805 }
Mike Stump1eb44332009-09-09 15:08:12 +00003806
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003807 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003808 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003809 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003810 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003811 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003812 QualType qt = Field->getType();
3813 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003814 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003815 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003816 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003817 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003818 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003819 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003820 return;
3821 }
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003823 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003824 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003825 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003826 else
3827 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003828 return;
3829 }
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003831 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003832 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003833 return;
3834 }
Mike Stump1eb44332009-09-09 15:08:12 +00003835
John McCallc12c5bb2010-05-15 11:32:37 +00003836 // Ignore protocol qualifiers when mangling at this level.
3837 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3838 T = OT->getBaseType();
3839
John McCall0953e762009-09-24 19:53:00 +00003840 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003841 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003842 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003843 S += '{';
3844 const IdentifierInfo *II = OI->getIdentifier();
3845 S += II->getName();
3846 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003847 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003848 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003849 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003850 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003851 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003852 RecFields[i]);
3853 else
Mike Stump1eb44332009-09-09 15:08:12 +00003854 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003855 FD);
3856 }
3857 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003858 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003859 }
Mike Stump1eb44332009-09-09 15:08:12 +00003860
John McCall183700f2009-09-21 23:43:11 +00003861 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003862 if (OPT->isObjCIdType()) {
3863 S += '@';
3864 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Steve Naroff27d20a22009-10-28 22:03:49 +00003867 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3868 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3869 // Since this is a binary compatibility issue, need to consult with runtime
3870 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003871 S += '#';
3872 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003875 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003876 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003877 ExpandPointedToStructures,
3878 ExpandStructures, FD);
3879 if (FD || EncodingProperty) {
3880 // Note that we do extended encoding of protocol qualifer list
3881 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003882 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003883 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3884 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003885 S += '<';
3886 S += (*I)->getNameAsString();
3887 S += '>';
3888 }
3889 S += '"';
3890 }
3891 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003892 }
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003894 QualType PointeeTy = OPT->getPointeeType();
3895 if (!EncodingProperty &&
3896 isa<TypedefType>(PointeeTy.getTypePtr())) {
3897 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003898 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 // {...};
3900 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003901 getObjCEncodingForTypeImpl(PointeeTy, S,
3902 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003903 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003904 return;
3905 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003906
3907 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003908 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003909 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003910 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003911 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3912 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003913 S += '<';
3914 S += (*I)->getNameAsString();
3915 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003916 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003917 S += '"';
3918 }
3919 return;
3920 }
Mike Stump1eb44332009-09-09 15:08:12 +00003921
John McCall532ec7b2010-05-17 23:56:34 +00003922 // gcc just blithely ignores member pointers.
3923 // TODO: maybe there should be a mangling for these
3924 if (T->getAs<MemberPointerType>())
3925 return;
3926
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003927 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003928}
3929
Mike Stump1eb44332009-09-09 15:08:12 +00003930void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003931 std::string& S) const {
3932 if (QT & Decl::OBJC_TQ_In)
3933 S += 'n';
3934 if (QT & Decl::OBJC_TQ_Inout)
3935 S += 'N';
3936 if (QT & Decl::OBJC_TQ_Out)
3937 S += 'o';
3938 if (QT & Decl::OBJC_TQ_Bycopy)
3939 S += 'O';
3940 if (QT & Decl::OBJC_TQ_Byref)
3941 S += 'R';
3942 if (QT & Decl::OBJC_TQ_Oneway)
3943 S += 'V';
3944}
3945
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003946void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003947 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003949 BuiltinVaListType = T;
3950}
3951
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003952void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003953 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003954}
3955
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003956void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003957 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003958}
3959
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003960void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003961 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003962}
3963
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003964void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003965 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003966}
3967
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003968void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003969 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003970 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003972 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003973}
3974
John McCall0bd6feb2009-12-02 08:04:21 +00003975/// \brief Retrieve the template name that corresponds to a non-empty
3976/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003977TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3978 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003979 unsigned size = End - Begin;
3980 assert(size > 1 && "set is not overloaded!");
3981
3982 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3983 size * sizeof(FunctionTemplateDecl*));
3984 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3985
3986 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003987 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003988 NamedDecl *D = *I;
3989 assert(isa<FunctionTemplateDecl>(D) ||
3990 (isa<UsingShadowDecl>(D) &&
3991 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3992 *Storage++ = D;
3993 }
3994
3995 return TemplateName(OT);
3996}
3997
Douglas Gregor7532dc62009-03-30 22:58:21 +00003998/// \brief Retrieve the template name that represents a qualified
3999/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004000TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004001 bool TemplateKeyword,
4002 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004003 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004004 llvm::FoldingSetNodeID ID;
4005 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4006
4007 void *InsertPos = 0;
4008 QualifiedTemplateName *QTN =
4009 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4010 if (!QTN) {
4011 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4012 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4013 }
4014
4015 return TemplateName(QTN);
4016}
4017
4018/// \brief Retrieve the template name that represents a dependent
4019/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004020TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004021 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004022 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004023 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004024
4025 llvm::FoldingSetNodeID ID;
4026 DependentTemplateName::Profile(ID, NNS, Name);
4027
4028 void *InsertPos = 0;
4029 DependentTemplateName *QTN =
4030 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4031
4032 if (QTN)
4033 return TemplateName(QTN);
4034
4035 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4036 if (CanonNNS == NNS) {
4037 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4038 } else {
4039 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4040 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004041 DependentTemplateName *CheckQTN =
4042 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4043 assert(!CheckQTN && "Dependent type name canonicalization broken");
4044 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004045 }
4046
4047 DependentTemplateNames.InsertNode(QTN, InsertPos);
4048 return TemplateName(QTN);
4049}
4050
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004051/// \brief Retrieve the template name that represents a dependent
4052/// template name such as \c MetaFun::template operator+.
4053TemplateName
4054ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4055 OverloadedOperatorKind Operator) {
4056 assert((!NNS || NNS->isDependent()) &&
4057 "Nested name specifier must be dependent");
4058
4059 llvm::FoldingSetNodeID ID;
4060 DependentTemplateName::Profile(ID, NNS, Operator);
4061
4062 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004063 DependentTemplateName *QTN
4064 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004065
4066 if (QTN)
4067 return TemplateName(QTN);
4068
4069 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4070 if (CanonNNS == NNS) {
4071 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4072 } else {
4073 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4074 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004075
4076 DependentTemplateName *CheckQTN
4077 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4078 assert(!CheckQTN && "Dependent template name canonicalization broken");
4079 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004080 }
4081
4082 DependentTemplateNames.InsertNode(QTN, InsertPos);
4083 return TemplateName(QTN);
4084}
4085
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004086/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004087/// TargetInfo, produce the corresponding type. The unsigned @p Type
4088/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004089CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004090 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004091 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004092 case TargetInfo::SignedShort: return ShortTy;
4093 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4094 case TargetInfo::SignedInt: return IntTy;
4095 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4096 case TargetInfo::SignedLong: return LongTy;
4097 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4098 case TargetInfo::SignedLongLong: return LongLongTy;
4099 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4100 }
4101
4102 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004103 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004104}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004105
4106//===----------------------------------------------------------------------===//
4107// Type Predicates.
4108//===----------------------------------------------------------------------===//
4109
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004110/// isObjCNSObjectType - Return true if this is an NSObject object using
4111/// NSObject attribute on a c-style pointer type.
4112/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004113/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004114///
4115bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4116 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4117 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004118 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004119 return true;
4120 }
Mike Stump1eb44332009-09-09 15:08:12 +00004121 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004122}
4123
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004124/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4125/// garbage collection attribute.
4126///
John McCall0953e762009-09-24 19:53:00 +00004127Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4128 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004129 if (getLangOptions().ObjC1 &&
4130 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004131 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004132 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004133 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004134 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004135 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004136 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004137 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004138 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004139 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004140 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004141 // Non-pointers have none gc'able attribute regardless of the attribute
4142 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004143 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004144 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004145 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004146 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004147}
4148
Chris Lattner6ac46a42008-04-07 06:51:04 +00004149//===----------------------------------------------------------------------===//
4150// Type Compatibility Testing
4151//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004152
Mike Stump1eb44332009-09-09 15:08:12 +00004153/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004154/// compatible.
4155static bool areCompatVectorTypes(const VectorType *LHS,
4156 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004157 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004158 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004159 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004160}
4161
Steve Naroff4084c302009-07-23 01:01:38 +00004162//===----------------------------------------------------------------------===//
4163// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4164//===----------------------------------------------------------------------===//
4165
4166/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4167/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004168bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4169 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004170 if (lProto == rProto)
4171 return true;
4172 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4173 E = rProto->protocol_end(); PI != E; ++PI)
4174 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4175 return true;
4176 return false;
4177}
4178
Steve Naroff4084c302009-07-23 01:01:38 +00004179/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4180/// return true if lhs's protocols conform to rhs's protocol; false
4181/// otherwise.
4182bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4183 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4184 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4185 return false;
4186}
4187
4188/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4189/// ObjCQualifiedIDType.
4190bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4191 bool compare) {
4192 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004193 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004194 lhs->isObjCIdType() || lhs->isObjCClassType())
4195 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004196 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004197 rhs->isObjCIdType() || rhs->isObjCClassType())
4198 return true;
4199
4200 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004201 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Steve Naroff4084c302009-07-23 01:01:38 +00004203 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Steve Naroff4084c302009-07-23 01:01:38 +00004205 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004206 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004207 // make sure we check the class hierarchy.
4208 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4209 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4210 E = lhsQID->qual_end(); I != E; ++I) {
4211 // when comparing an id<P> on lhs with a static type on rhs,
4212 // see if static class implements all of id's protocols, directly or
4213 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004214 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004215 return false;
4216 }
4217 }
4218 // If there are no qualifiers and no interface, we have an 'id'.
4219 return true;
4220 }
Mike Stump1eb44332009-09-09 15:08:12 +00004221 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004222 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4223 E = lhsQID->qual_end(); I != E; ++I) {
4224 ObjCProtocolDecl *lhsProto = *I;
4225 bool match = false;
4226
4227 // when comparing an id<P> on lhs with a static type on rhs,
4228 // see if static class implements all of id's protocols, directly or
4229 // through its super class and categories.
4230 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4231 E = rhsOPT->qual_end(); J != E; ++J) {
4232 ObjCProtocolDecl *rhsProto = *J;
4233 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4234 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4235 match = true;
4236 break;
4237 }
4238 }
Mike Stump1eb44332009-09-09 15:08:12 +00004239 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004240 // make sure we check the class hierarchy.
4241 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4242 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4243 E = lhsQID->qual_end(); I != E; ++I) {
4244 // when comparing an id<P> on lhs with a static type on rhs,
4245 // see if static class implements all of id's protocols, directly or
4246 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004247 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004248 match = true;
4249 break;
4250 }
4251 }
4252 }
4253 if (!match)
4254 return false;
4255 }
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Steve Naroff4084c302009-07-23 01:01:38 +00004257 return true;
4258 }
Mike Stump1eb44332009-09-09 15:08:12 +00004259
Steve Naroff4084c302009-07-23 01:01:38 +00004260 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4261 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4262
Mike Stump1eb44332009-09-09 15:08:12 +00004263 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004264 lhs->getAsObjCInterfacePointerType()) {
4265 if (lhsOPT->qual_empty()) {
4266 bool match = false;
4267 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4268 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4269 E = rhsQID->qual_end(); I != E; ++I) {
4270 // when comparing an id<P> on lhs with a static type on rhs,
4271 // see if static class implements all of id's protocols, directly or
4272 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004273 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004274 match = true;
4275 break;
4276 }
4277 }
4278 if (!match)
4279 return false;
4280 }
4281 return true;
4282 }
Mike Stump1eb44332009-09-09 15:08:12 +00004283 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004284 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4285 E = lhsOPT->qual_end(); I != E; ++I) {
4286 ObjCProtocolDecl *lhsProto = *I;
4287 bool match = false;
4288
4289 // when comparing an id<P> on lhs with a static type on rhs,
4290 // see if static class implements all of id's protocols, directly or
4291 // through its super class and categories.
4292 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4293 E = rhsQID->qual_end(); J != E; ++J) {
4294 ObjCProtocolDecl *rhsProto = *J;
4295 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4296 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4297 match = true;
4298 break;
4299 }
4300 }
4301 if (!match)
4302 return false;
4303 }
4304 return true;
4305 }
4306 return false;
4307}
4308
Eli Friedman3d815e72008-08-22 00:56:42 +00004309/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004310/// compatible for assignment from RHS to LHS. This handles validation of any
4311/// protocol qualifiers on the LHS or RHS.
4312///
Steve Naroff14108da2009-07-10 23:34:53 +00004313bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4314 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004315 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4316 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4317
Steve Naroffde2e22d2009-07-15 18:40:39 +00004318 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004319 if (LHS->isObjCUnqualifiedIdOrClass() ||
4320 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004321 return true;
4322
John McCallc12c5bb2010-05-15 11:32:37 +00004323 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004324 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4325 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004326 false);
4327
John McCallc12c5bb2010-05-15 11:32:37 +00004328 // If we have 2 user-defined types, fall into that path.
4329 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004330 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Steve Naroff4084c302009-07-23 01:01:38 +00004332 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004333}
4334
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004335/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4336/// for providing type-safty for objective-c pointers used to pass/return
4337/// arguments in block literals. When passed as arguments, passing 'A*' where
4338/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4339/// not OK. For the return type, the opposite is not OK.
4340bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4341 const ObjCObjectPointerType *LHSOPT,
4342 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004343 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004344 return true;
4345
4346 if (LHSOPT->isObjCBuiltinType()) {
4347 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4348 }
4349
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004350 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004351 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4352 QualType(RHSOPT,0),
4353 false);
4354
4355 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4356 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4357 if (LHS && RHS) { // We have 2 user-defined types.
4358 if (LHS != RHS) {
4359 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4360 return false;
4361 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4362 return true;
4363 }
4364 else
4365 return true;
4366 }
4367 return false;
4368}
4369
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004370/// getIntersectionOfProtocols - This routine finds the intersection of set
4371/// of protocols inherited from two distinct objective-c pointer objects.
4372/// It is used to build composite qualifier list of the composite type of
4373/// the conditional expression involving two objective-c pointer objects.
4374static
4375void getIntersectionOfProtocols(ASTContext &Context,
4376 const ObjCObjectPointerType *LHSOPT,
4377 const ObjCObjectPointerType *RHSOPT,
4378 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4379
John McCallc12c5bb2010-05-15 11:32:37 +00004380 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4381 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4382 assert(LHS->getInterface() && "LHS must have an interface base");
4383 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004384
4385 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4386 unsigned LHSNumProtocols = LHS->getNumProtocols();
4387 if (LHSNumProtocols > 0)
4388 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4389 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004390 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004391 Context.CollectInheritedProtocols(LHS->getInterface(),
4392 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004393 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4394 LHSInheritedProtocols.end());
4395 }
4396
4397 unsigned RHSNumProtocols = RHS->getNumProtocols();
4398 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004399 ObjCProtocolDecl **RHSProtocols =
4400 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004401 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4402 if (InheritedProtocolSet.count(RHSProtocols[i]))
4403 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4404 }
4405 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004406 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004407 Context.CollectInheritedProtocols(RHS->getInterface(),
4408 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004409 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4410 RHSInheritedProtocols.begin(),
4411 E = RHSInheritedProtocols.end(); I != E; ++I)
4412 if (InheritedProtocolSet.count((*I)))
4413 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004414 }
4415}
4416
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004417/// areCommonBaseCompatible - Returns common base class of the two classes if
4418/// one found. Note that this is O'2 algorithm. But it will be called as the
4419/// last type comparison in a ?-exp of ObjC pointer types before a
4420/// warning is issued. So, its invokation is extremely rare.
4421QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004422 const ObjCObjectPointerType *Lptr,
4423 const ObjCObjectPointerType *Rptr) {
4424 const ObjCObjectType *LHS = Lptr->getObjectType();
4425 const ObjCObjectType *RHS = Rptr->getObjectType();
4426 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4427 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4428 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004429 return QualType();
4430
John McCallc12c5bb2010-05-15 11:32:37 +00004431 while ((LDecl = LDecl->getSuperClass())) {
4432 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004433 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004434 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4435 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4436
4437 QualType Result = QualType(LHS, 0);
4438 if (!Protocols.empty())
4439 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4440 Result = getObjCObjectPointerType(Result);
4441 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004442 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004443 }
4444
4445 return QualType();
4446}
4447
John McCallc12c5bb2010-05-15 11:32:37 +00004448bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4449 const ObjCObjectType *RHS) {
4450 assert(LHS->getInterface() && "LHS is not an interface type");
4451 assert(RHS->getInterface() && "RHS is not an interface type");
4452
Chris Lattner6ac46a42008-04-07 06:51:04 +00004453 // Verify that the base decls are compatible: the RHS must be a subclass of
4454 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004455 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004456 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004457
Chris Lattner6ac46a42008-04-07 06:51:04 +00004458 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4459 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004460 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004461 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Chris Lattner6ac46a42008-04-07 06:51:04 +00004463 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4464 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004465 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004466 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004467
John McCallc12c5bb2010-05-15 11:32:37 +00004468 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4469 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004470 LHSPI != LHSPE; LHSPI++) {
4471 bool RHSImplementsProtocol = false;
4472
4473 // If the RHS doesn't implement the protocol on the left, the types
4474 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004475 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4476 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004477 RHSPI != RHSPE; RHSPI++) {
4478 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004479 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004480 break;
4481 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004482 }
4483 // FIXME: For better diagnostics, consider passing back the protocol name.
4484 if (!RHSImplementsProtocol)
4485 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004486 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004487 // The RHS implements all protocols listed on the LHS.
4488 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004489}
4490
Steve Naroff389bf462009-02-12 17:52:19 +00004491bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4492 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004493 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4494 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Steve Naroff14108da2009-07-10 23:34:53 +00004496 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004497 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004498
4499 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4500 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004501}
4502
Mike Stump1eb44332009-09-09 15:08:12 +00004503/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004504/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004505/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004506/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004507bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004508 if (getLangOptions().CPlusPlus)
4509 return hasSameType(LHS, RHS);
4510
Eli Friedman3d815e72008-08-22 00:56:42 +00004511 return !mergeTypes(LHS, RHS).isNull();
4512}
4513
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004514bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4515 return !mergeTypes(LHS, RHS, true).isNull();
4516}
4517
4518QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4519 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004520 const FunctionType *lbase = lhs->getAs<FunctionType>();
4521 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004522 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4523 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004524 bool allLTypes = true;
4525 bool allRTypes = true;
4526
4527 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004528 QualType retType;
4529 if (OfBlockPointer)
4530 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4531 else
4532 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004533 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004534 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004535 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004536 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004537 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004538 // FIXME: double check this
4539 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4540 // rbase->getRegParmAttr() != 0 &&
4541 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004542 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4543 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004544 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4545 lbaseInfo.getRegParm();
4546 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4547 if (NoReturn != lbaseInfo.getNoReturn() ||
4548 RegParm != lbaseInfo.getRegParm())
4549 allLTypes = false;
4550 if (NoReturn != rbaseInfo.getNoReturn() ||
4551 RegParm != rbaseInfo.getRegParm())
4552 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004553 CallingConv lcc = lbaseInfo.getCC();
4554 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004555 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004556 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004557 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Eli Friedman3d815e72008-08-22 00:56:42 +00004559 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004560 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4561 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004562 unsigned lproto_nargs = lproto->getNumArgs();
4563 unsigned rproto_nargs = rproto->getNumArgs();
4564
4565 // Compatible functions must have the same number of arguments
4566 if (lproto_nargs != rproto_nargs)
4567 return QualType();
4568
4569 // Variadic and non-variadic functions aren't compatible
4570 if (lproto->isVariadic() != rproto->isVariadic())
4571 return QualType();
4572
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004573 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4574 return QualType();
4575
Eli Friedman3d815e72008-08-22 00:56:42 +00004576 // Check argument compatibility
4577 llvm::SmallVector<QualType, 10> types;
4578 for (unsigned i = 0; i < lproto_nargs; i++) {
4579 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4580 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004581 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004582 if (argtype.isNull()) return QualType();
4583 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004584 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4585 allLTypes = false;
4586 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4587 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004588 }
4589 if (allLTypes) return lhs;
4590 if (allRTypes) return rhs;
4591 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004592 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004593 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004594 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004595 }
4596
4597 if (lproto) allRTypes = false;
4598 if (rproto) allLTypes = false;
4599
Douglas Gregor72564e72009-02-26 23:50:07 +00004600 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004601 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004602 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004603 if (proto->isVariadic()) return QualType();
4604 // Check that the types are compatible with the types that
4605 // would result from default argument promotions (C99 6.7.5.3p15).
4606 // The only types actually affected are promotable integer
4607 // types and floats, which would be passed as a different
4608 // type depending on whether the prototype is visible.
4609 unsigned proto_nargs = proto->getNumArgs();
4610 for (unsigned i = 0; i < proto_nargs; ++i) {
4611 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004612
4613 // Look at the promotion type of enum types, since that is the type used
4614 // to pass enum values.
4615 if (const EnumType *Enum = argTy->getAs<EnumType>())
4616 argTy = Enum->getDecl()->getPromotionType();
4617
Eli Friedman3d815e72008-08-22 00:56:42 +00004618 if (argTy->isPromotableIntegerType() ||
4619 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4620 return QualType();
4621 }
4622
4623 if (allLTypes) return lhs;
4624 if (allRTypes) return rhs;
4625 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004626 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004627 proto->getTypeQuals(),
4628 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004629 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004630 }
4631
4632 if (allLTypes) return lhs;
4633 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004634 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004635 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004636}
4637
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004638QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4639 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004640 // C++ [expr]: If an expression initially has the type "reference to T", the
4641 // type is adjusted to "T" prior to any further analysis, the expression
4642 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004643 // expression is an lvalue unless the reference is an rvalue reference and
4644 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004645 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4646 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4647
Eli Friedman3d815e72008-08-22 00:56:42 +00004648 QualType LHSCan = getCanonicalType(LHS),
4649 RHSCan = getCanonicalType(RHS);
4650
4651 // If two types are identical, they are compatible.
4652 if (LHSCan == RHSCan)
4653 return LHS;
4654
John McCall0953e762009-09-24 19:53:00 +00004655 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004656 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4657 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004658 if (LQuals != RQuals) {
4659 // If any of these qualifiers are different, we have a type
4660 // mismatch.
4661 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4662 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4663 return QualType();
4664
4665 // Exactly one GC qualifier difference is allowed: __strong is
4666 // okay if the other type has no GC qualifier but is an Objective
4667 // C object pointer (i.e. implicitly strong by default). We fix
4668 // this by pretending that the unqualified type was actually
4669 // qualified __strong.
4670 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4671 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4672 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4673
4674 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4675 return QualType();
4676
4677 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4678 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4679 }
4680 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4681 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4682 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004683 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004684 }
4685
4686 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004687
Eli Friedman852d63b2009-06-01 01:22:52 +00004688 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4689 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004690
Chris Lattner1adb8832008-01-14 05:45:46 +00004691 // We want to consider the two function types to be the same for these
4692 // comparisons, just force one to the other.
4693 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4694 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004695
4696 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004697 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4698 LHSClass = Type::ConstantArray;
4699 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4700 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004701
John McCallc12c5bb2010-05-15 11:32:37 +00004702 // ObjCInterfaces are just specialized ObjCObjects.
4703 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4704 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4705
Nate Begeman213541a2008-04-18 23:10:10 +00004706 // Canonicalize ExtVector -> Vector.
4707 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4708 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Chris Lattnera36a61f2008-04-07 05:43:21 +00004710 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004711 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004712 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004713 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004714 // Compatibility is based on the underlying type, not the promotion
4715 // type.
John McCall183700f2009-09-21 23:43:11 +00004716 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004717 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4718 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004719 }
John McCall183700f2009-09-21 23:43:11 +00004720 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004721 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4722 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004723 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004724
Eli Friedman3d815e72008-08-22 00:56:42 +00004725 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004726 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004727
Steve Naroff4a746782008-01-09 22:43:08 +00004728 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004729 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004730#define TYPE(Class, Base)
4731#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004732#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004733#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4734#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4735#include "clang/AST/TypeNodes.def"
4736 assert(false && "Non-canonical and dependent types shouldn't get here");
4737 return QualType();
4738
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004739 case Type::LValueReference:
4740 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004741 case Type::MemberPointer:
4742 assert(false && "C++ should never be in mergeTypes");
4743 return QualType();
4744
John McCallc12c5bb2010-05-15 11:32:37 +00004745 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004746 case Type::IncompleteArray:
4747 case Type::VariableArray:
4748 case Type::FunctionProto:
4749 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004750 assert(false && "Types are eliminated above");
4751 return QualType();
4752
Chris Lattner1adb8832008-01-14 05:45:46 +00004753 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004754 {
4755 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004756 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4757 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004758 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4759 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004760 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004761 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004762 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004763 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004764 return getPointerType(ResultType);
4765 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004766 case Type::BlockPointer:
4767 {
4768 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004769 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4770 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004771 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004772 if (ResultType.isNull()) return QualType();
4773 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4774 return LHS;
4775 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4776 return RHS;
4777 return getBlockPointerType(ResultType);
4778 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004779 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004780 {
4781 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4782 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4783 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4784 return QualType();
4785
4786 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4787 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4788 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4789 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004790 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4791 return LHS;
4792 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4793 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004794 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4795 ArrayType::ArraySizeModifier(), 0);
4796 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4797 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004798 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4799 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004800 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4801 return LHS;
4802 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4803 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004804 if (LVAT) {
4805 // FIXME: This isn't correct! But tricky to implement because
4806 // the array's size has to be the size of LHS, but the type
4807 // has to be different.
4808 return LHS;
4809 }
4810 if (RVAT) {
4811 // FIXME: This isn't correct! But tricky to implement because
4812 // the array's size has to be the size of RHS, but the type
4813 // has to be different.
4814 return RHS;
4815 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004816 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4817 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004818 return getIncompleteArrayType(ResultType,
4819 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004820 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004821 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004822 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004823 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004824 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004825 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004826 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004827 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004828 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004829 case Type::Complex:
4830 // Distinct complex types are incompatible.
4831 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004832 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004833 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004834 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4835 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004836 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004837 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004838 case Type::ObjCObject: {
4839 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004840 // FIXME: This should be type compatibility, e.g. whether
4841 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004842 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4843 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4844 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004845 return LHS;
4846
Eli Friedman3d815e72008-08-22 00:56:42 +00004847 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004848 }
Steve Naroff14108da2009-07-10 23:34:53 +00004849 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004850 if (OfBlockPointer) {
4851 if (canAssignObjCInterfacesInBlockPointer(
4852 LHS->getAs<ObjCObjectPointerType>(),
4853 RHS->getAs<ObjCObjectPointerType>()))
4854 return LHS;
4855 return QualType();
4856 }
John McCall183700f2009-09-21 23:43:11 +00004857 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4858 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004859 return LHS;
4860
Steve Naroffbc76dd02008-12-10 22:14:21 +00004861 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004862 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004863 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004864
4865 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004866}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004867
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004868/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4869/// 'RHS' attributes and returns the merged version; including for function
4870/// return types.
4871QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4872 QualType LHSCan = getCanonicalType(LHS),
4873 RHSCan = getCanonicalType(RHS);
4874 // If two types are identical, they are compatible.
4875 if (LHSCan == RHSCan)
4876 return LHS;
4877 if (RHSCan->isFunctionType()) {
4878 if (!LHSCan->isFunctionType())
4879 return QualType();
4880 QualType OldReturnType =
4881 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4882 QualType NewReturnType =
4883 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4884 QualType ResReturnType =
4885 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4886 if (ResReturnType.isNull())
4887 return QualType();
4888 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4889 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4890 // In either case, use OldReturnType to build the new function type.
4891 const FunctionType *F = LHS->getAs<FunctionType>();
4892 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4893 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4894 QualType ResultType
4895 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4896 FPT->getNumArgs(), FPT->isVariadic(),
4897 FPT->getTypeQuals(),
4898 FPT->hasExceptionSpec(),
4899 FPT->hasAnyExceptionSpec(),
4900 FPT->getNumExceptions(),
4901 FPT->exception_begin(),
4902 Info);
4903 return ResultType;
4904 }
4905 }
4906 return QualType();
4907 }
4908
4909 // If the qualifiers are different, the types can still be merged.
4910 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4911 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4912 if (LQuals != RQuals) {
4913 // If any of these qualifiers are different, we have a type mismatch.
4914 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4915 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4916 return QualType();
4917
4918 // Exactly one GC qualifier difference is allowed: __strong is
4919 // okay if the other type has no GC qualifier but is an Objective
4920 // C object pointer (i.e. implicitly strong by default). We fix
4921 // this by pretending that the unqualified type was actually
4922 // qualified __strong.
4923 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4924 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4925 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4926
4927 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4928 return QualType();
4929
4930 if (GC_L == Qualifiers::Strong)
4931 return LHS;
4932 if (GC_R == Qualifiers::Strong)
4933 return RHS;
4934 return QualType();
4935 }
4936
4937 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4938 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4939 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4940 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4941 if (ResQT == LHSBaseQT)
4942 return LHS;
4943 if (ResQT == RHSBaseQT)
4944 return RHS;
4945 }
4946 return QualType();
4947}
4948
Chris Lattner5426bf62008-04-07 07:01:58 +00004949//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004950// Integer Predicates
4951//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004952
Eli Friedmanad74a752008-06-28 06:23:08 +00004953unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004954 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004955 return 1;
John McCall842aef82009-12-09 09:09:27 +00004956 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004957 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004958 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004959 return (unsigned)getTypeSize(T);
4960}
4961
4962QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4963 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004964
4965 // Turn <4 x signed int> -> <4 x unsigned int>
4966 if (const VectorType *VTy = T->getAs<VectorType>())
4967 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00004968 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004969
4970 // For enums, we return the unsigned version of the base type.
4971 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004972 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004973
4974 const BuiltinType *BTy = T->getAs<BuiltinType>();
4975 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004976 switch (BTy->getKind()) {
4977 case BuiltinType::Char_S:
4978 case BuiltinType::SChar:
4979 return UnsignedCharTy;
4980 case BuiltinType::Short:
4981 return UnsignedShortTy;
4982 case BuiltinType::Int:
4983 return UnsignedIntTy;
4984 case BuiltinType::Long:
4985 return UnsignedLongTy;
4986 case BuiltinType::LongLong:
4987 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004988 case BuiltinType::Int128:
4989 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004990 default:
4991 assert(0 && "Unexpected signed integer type");
4992 return QualType();
4993 }
4994}
4995
Douglas Gregor2cf26342009-04-09 22:27:44 +00004996ExternalASTSource::~ExternalASTSource() { }
4997
4998void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004999
5000
5001//===----------------------------------------------------------------------===//
5002// Builtin Type Computation
5003//===----------------------------------------------------------------------===//
5004
5005/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5006/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005007static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005008 ASTContext::GetBuiltinTypeError &Error,
5009 bool AllowTypeModifiers = true) {
5010 // Modifiers.
5011 int HowLong = 0;
5012 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005013
Chris Lattner86df27b2009-06-14 00:45:47 +00005014 // Read the modifiers first.
5015 bool Done = false;
5016 while (!Done) {
5017 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005018 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005019 case 'S':
5020 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5021 assert(!Signed && "Can't use 'S' modifier multiple times!");
5022 Signed = true;
5023 break;
5024 case 'U':
5025 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5026 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5027 Unsigned = true;
5028 break;
5029 case 'L':
5030 assert(HowLong <= 2 && "Can't have LLLL modifier");
5031 ++HowLong;
5032 break;
5033 }
5034 }
5035
5036 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Chris Lattner86df27b2009-06-14 00:45:47 +00005038 // Read the base type.
5039 switch (*Str++) {
5040 default: assert(0 && "Unknown builtin type letter!");
5041 case 'v':
5042 assert(HowLong == 0 && !Signed && !Unsigned &&
5043 "Bad modifiers used with 'v'!");
5044 Type = Context.VoidTy;
5045 break;
5046 case 'f':
5047 assert(HowLong == 0 && !Signed && !Unsigned &&
5048 "Bad modifiers used with 'f'!");
5049 Type = Context.FloatTy;
5050 break;
5051 case 'd':
5052 assert(HowLong < 2 && !Signed && !Unsigned &&
5053 "Bad modifiers used with 'd'!");
5054 if (HowLong)
5055 Type = Context.LongDoubleTy;
5056 else
5057 Type = Context.DoubleTy;
5058 break;
5059 case 's':
5060 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5061 if (Unsigned)
5062 Type = Context.UnsignedShortTy;
5063 else
5064 Type = Context.ShortTy;
5065 break;
5066 case 'i':
5067 if (HowLong == 3)
5068 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5069 else if (HowLong == 2)
5070 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5071 else if (HowLong == 1)
5072 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5073 else
5074 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5075 break;
5076 case 'c':
5077 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5078 if (Signed)
5079 Type = Context.SignedCharTy;
5080 else if (Unsigned)
5081 Type = Context.UnsignedCharTy;
5082 else
5083 Type = Context.CharTy;
5084 break;
5085 case 'b': // boolean
5086 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5087 Type = Context.BoolTy;
5088 break;
5089 case 'z': // size_t.
5090 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5091 Type = Context.getSizeType();
5092 break;
5093 case 'F':
5094 Type = Context.getCFConstantStringType();
5095 break;
5096 case 'a':
5097 Type = Context.getBuiltinVaListType();
5098 assert(!Type.isNull() && "builtin va list type not initialized!");
5099 break;
5100 case 'A':
5101 // This is a "reference" to a va_list; however, what exactly
5102 // this means depends on how va_list is defined. There are two
5103 // different kinds of va_list: ones passed by value, and ones
5104 // passed by reference. An example of a by-value va_list is
5105 // x86, where va_list is a char*. An example of by-ref va_list
5106 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5107 // we want this argument to be a char*&; for x86-64, we want
5108 // it to be a __va_list_tag*.
5109 Type = Context.getBuiltinVaListType();
5110 assert(!Type.isNull() && "builtin va list type not initialized!");
5111 if (Type->isArrayType()) {
5112 Type = Context.getArrayDecayedType(Type);
5113 } else {
5114 Type = Context.getLValueReferenceType(Type);
5115 }
5116 break;
5117 case 'V': {
5118 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005119 unsigned NumElements = strtoul(Str, &End, 10);
5120 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005121
Chris Lattner86df27b2009-06-14 00:45:47 +00005122 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005123
Chris Lattner86df27b2009-06-14 00:45:47 +00005124 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005125 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005126 Type = Context.getVectorType(ElementType, NumElements,
5127 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005128 break;
5129 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005130 case 'X': {
5131 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5132 Type = Context.getComplexType(ElementType);
5133 break;
5134 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005135 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005136 Type = Context.getFILEType();
5137 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005138 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005139 return QualType();
5140 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005141 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005142 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005143 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005144 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005145 else
5146 Type = Context.getjmp_bufType();
5147
Mike Stumpfd612db2009-07-28 23:47:15 +00005148 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005149 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005150 return QualType();
5151 }
5152 break;
Mike Stump782fa302009-07-28 02:25:19 +00005153 }
Mike Stump1eb44332009-09-09 15:08:12 +00005154
Chris Lattner86df27b2009-06-14 00:45:47 +00005155 if (!AllowTypeModifiers)
5156 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005157
Chris Lattner86df27b2009-06-14 00:45:47 +00005158 Done = false;
5159 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005160 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005161 default: Done = true; --Str; break;
5162 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005163 case '&':
John McCall187ab372010-03-12 04:21:28 +00005164 {
5165 // Both pointers and references can have their pointee types
5166 // qualified with an address space.
5167 char *End;
5168 unsigned AddrSpace = strtoul(Str, &End, 10);
5169 if (End != Str && AddrSpace != 0) {
5170 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5171 Str = End;
5172 }
5173 }
5174 if (c == '*')
5175 Type = Context.getPointerType(Type);
5176 else
5177 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005178 break;
5179 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5180 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005181 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005182 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005183 case 'D':
5184 Type = Context.getVolatileType(Type);
5185 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005186 }
5187 }
Mike Stump1eb44332009-09-09 15:08:12 +00005188
Chris Lattner86df27b2009-06-14 00:45:47 +00005189 return Type;
5190}
5191
5192/// GetBuiltinType - Return the type for the specified builtin.
5193QualType ASTContext::GetBuiltinType(unsigned id,
5194 GetBuiltinTypeError &Error) {
5195 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005196
Chris Lattner86df27b2009-06-14 00:45:47 +00005197 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Chris Lattner86df27b2009-06-14 00:45:47 +00005199 Error = GE_None;
5200 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5201 if (Error != GE_None)
5202 return QualType();
5203 while (TypeStr[0] && TypeStr[0] != '.') {
5204 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5205 if (Error != GE_None)
5206 return QualType();
5207
5208 // Do array -> pointer decay. The builtin should use the decayed type.
5209 if (Ty->isArrayType())
5210 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005211
Chris Lattner86df27b2009-06-14 00:45:47 +00005212 ArgTypes.push_back(Ty);
5213 }
5214
5215 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5216 "'.' should only occur at end of builtin type list!");
5217
5218 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5219 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5220 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005221
5222 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005223 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005224 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005225 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005226}
Eli Friedmana95d7572009-08-19 07:44:53 +00005227
5228QualType
5229ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5230 // Perform the usual unary conversions. We do this early so that
5231 // integral promotions to "int" can allow us to exit early, in the
5232 // lhs == rhs check. Also, for conversion purposes, we ignore any
5233 // qualifiers. For example, "const float" and "float" are
5234 // equivalent.
5235 if (lhs->isPromotableIntegerType())
5236 lhs = getPromotedIntegerType(lhs);
5237 else
5238 lhs = lhs.getUnqualifiedType();
5239 if (rhs->isPromotableIntegerType())
5240 rhs = getPromotedIntegerType(rhs);
5241 else
5242 rhs = rhs.getUnqualifiedType();
5243
5244 // If both types are identical, no conversion is needed.
5245 if (lhs == rhs)
5246 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005247
Eli Friedmana95d7572009-08-19 07:44:53 +00005248 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5249 // The caller can deal with this (e.g. pointer + int).
5250 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5251 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005252
5253 // At this point, we have two different arithmetic types.
5254
Eli Friedmana95d7572009-08-19 07:44:53 +00005255 // Handle complex types first (C99 6.3.1.8p1).
5256 if (lhs->isComplexType() || rhs->isComplexType()) {
5257 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005258 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005259 // convert the rhs to the lhs complex type.
5260 return lhs;
5261 }
Mike Stump1eb44332009-09-09 15:08:12 +00005262 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005263 // convert the lhs to the rhs complex type.
5264 return rhs;
5265 }
5266 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005267 // When both operands are complex, the shorter operand is converted to the
5268 // type of the longer, and that is the type of the result. This corresponds
5269 // to what is done when combining two real floating-point operands.
5270 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005271 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005272 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005273 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005274 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005275 // "double _Complex" is promoted to "long double _Complex".
5276 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005277
5278 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005279 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005280 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005281 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005282 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005283 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5284 // domains match. This is a requirement for our implementation, C99
5285 // does not require this promotion.
5286 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5287 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5288 return rhs;
5289 } else { // handle "_Complex double, double".
5290 return lhs;
5291 }
5292 }
5293 return lhs; // The domain/size match exactly.
5294 }
5295 // Now handle "real" floating types (i.e. float, double, long double).
5296 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5297 // if we have an integer operand, the result is the real floating type.
5298 if (rhs->isIntegerType()) {
5299 // convert rhs to the lhs floating point type.
5300 return lhs;
5301 }
5302 if (rhs->isComplexIntegerType()) {
5303 // convert rhs to the complex floating point type.
5304 return getComplexType(lhs);
5305 }
5306 if (lhs->isIntegerType()) {
5307 // convert lhs to the rhs floating point type.
5308 return rhs;
5309 }
Mike Stump1eb44332009-09-09 15:08:12 +00005310 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005311 // convert lhs to the complex floating point type.
5312 return getComplexType(rhs);
5313 }
5314 // We have two real floating types, float/complex combos were handled above.
5315 // Convert the smaller operand to the bigger result.
5316 int result = getFloatingTypeOrder(lhs, rhs);
5317 if (result > 0) // convert the rhs
5318 return lhs;
5319 assert(result < 0 && "illegal float comparison");
5320 return rhs; // convert the lhs
5321 }
5322 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5323 // Handle GCC complex int extension.
5324 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5325 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5326
5327 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005328 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005329 rhsComplexInt->getElementType()) >= 0)
5330 return lhs; // convert the rhs
5331 return rhs;
5332 } else if (lhsComplexInt && rhs->isIntegerType()) {
5333 // convert the rhs to the lhs complex type.
5334 return lhs;
5335 } else if (rhsComplexInt && lhs->isIntegerType()) {
5336 // convert the lhs to the rhs complex type.
5337 return rhs;
5338 }
5339 }
5340 // Finally, we have two differing integer types.
5341 // The rules for this case are in C99 6.3.1.8
5342 int compare = getIntegerTypeOrder(lhs, rhs);
5343 bool lhsSigned = lhs->isSignedIntegerType(),
5344 rhsSigned = rhs->isSignedIntegerType();
5345 QualType destType;
5346 if (lhsSigned == rhsSigned) {
5347 // Same signedness; use the higher-ranked type
5348 destType = compare >= 0 ? lhs : rhs;
5349 } else if (compare != (lhsSigned ? 1 : -1)) {
5350 // The unsigned type has greater than or equal rank to the
5351 // signed type, so use the unsigned type
5352 destType = lhsSigned ? rhs : lhs;
5353 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5354 // The two types are different widths; if we are here, that
5355 // means the signed type is larger than the unsigned type, so
5356 // use the signed type.
5357 destType = lhsSigned ? lhs : rhs;
5358 } else {
5359 // The signed type is higher-ranked than the unsigned type,
5360 // but isn't actually any bigger (like unsigned int and long
5361 // on most 32-bit systems). Use the unsigned type corresponding
5362 // to the signed type.
5363 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5364 }
5365 return destType;
5366}