blob: 8c61b5c7503a9037236c3cfcd70b19acc8f62020 [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"
Charles Davis071cc7d2010-08-16 03:33:14 +000031#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000032
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Douglas Gregor18274032010-07-03 00:47:00 +000035unsigned ASTContext::NumImplicitDefaultConstructors;
36unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000037unsigned ASTContext::NumImplicitCopyConstructors;
38unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000039unsigned ASTContext::NumImplicitCopyAssignmentOperators;
40unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000041unsigned ASTContext::NumImplicitDestructors;
42unsigned ASTContext::NumImplicitDestructorsDeclared;
43
Reid Spencer5f016e22007-07-11 17:01:13 +000044enum FloatingRank {
45 FloatRank, DoubleRank, LongDoubleRank
46};
47
Douglas Gregor3e1274f2010-06-16 21:09:37 +000048void
49ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
50 TemplateTemplateParmDecl *Parm) {
51 ID.AddInteger(Parm->getDepth());
52 ID.AddInteger(Parm->getPosition());
53 // FIXME: Parameter pack
54
55 TemplateParameterList *Params = Parm->getTemplateParameters();
56 ID.AddInteger(Params->size());
57 for (TemplateParameterList::const_iterator P = Params->begin(),
58 PEnd = Params->end();
59 P != PEnd; ++P) {
60 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
61 ID.AddInteger(0);
62 ID.AddBoolean(TTP->isParameterPack());
63 continue;
64 }
65
66 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
67 ID.AddInteger(1);
68 // FIXME: Parameter pack
69 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
70 continue;
71 }
72
73 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
74 ID.AddInteger(2);
75 Profile(ID, TTP);
76 }
77}
78
79TemplateTemplateParmDecl *
80ASTContext::getCanonicalTemplateTemplateParmDecl(
81 TemplateTemplateParmDecl *TTP) {
82 // Check if we already have a canonical template template parameter.
83 llvm::FoldingSetNodeID ID;
84 CanonicalTemplateTemplateParm::Profile(ID, TTP);
85 void *InsertPos = 0;
86 CanonicalTemplateTemplateParm *Canonical
87 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
88 if (Canonical)
89 return Canonical->getParam();
90
91 // Build a canonical template parameter list.
92 TemplateParameterList *Params = TTP->getTemplateParameters();
93 llvm::SmallVector<NamedDecl *, 4> CanonParams;
94 CanonParams.reserve(Params->size());
95 for (TemplateParameterList::const_iterator P = Params->begin(),
96 PEnd = Params->end();
97 P != PEnd; ++P) {
98 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
99 CanonParams.push_back(
100 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
101 SourceLocation(), TTP->getDepth(),
102 TTP->getIndex(), 0, false,
103 TTP->isParameterPack()));
104 else if (NonTypeTemplateParmDecl *NTTP
105 = dyn_cast<NonTypeTemplateParmDecl>(*P))
106 CanonParams.push_back(
107 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
108 SourceLocation(), NTTP->getDepth(),
109 NTTP->getPosition(), 0,
110 getCanonicalType(NTTP->getType()),
111 0));
112 else
113 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
114 cast<TemplateTemplateParmDecl>(*P)));
115 }
116
117 TemplateTemplateParmDecl *CanonTTP
118 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
119 SourceLocation(), TTP->getDepth(),
120 TTP->getPosition(), 0,
121 TemplateParameterList::Create(*this, SourceLocation(),
122 SourceLocation(),
123 CanonParams.data(),
124 CanonParams.size(),
125 SourceLocation()));
126
127 // Get the new insert position for the node we care about.
128 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
129 assert(Canonical == 0 && "Shouldn't be in the map!");
130 (void)Canonical;
131
132 // Create the canonical template template parameter entry.
133 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
134 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
135 return CanonTTP;
136}
137
Charles Davis071cc7d2010-08-16 03:33:14 +0000138CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000139 if (!LangOpts.CPlusPlus) return 0;
140
Charles Davis20cf7172010-08-19 02:18:14 +0000141 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000142 case CXXABI_ARM:
143 return CreateARMCXXABI(*this);
144 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000145 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000146 case CXXABI_Microsoft:
147 return CreateMicrosoftCXXABI(*this);
148 }
John McCallee79a4c2010-08-21 22:46:04 +0000149 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000150}
151
Chris Lattner61710852008-10-05 17:34:18 +0000152ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000153 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000154 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000155 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000156 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000157 TemplateSpecializationTypes(this_()),
158 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000159 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
160 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000161 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000162 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000163 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000164 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000165 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000166 BuiltinInfo(builtins),
167 DeclarationNames(*this),
168 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000169 LastSDM(0, 0),
170 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000171 ObjCIdRedefinitionType = QualType();
172 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000173 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000174 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000175 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000176 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000177}
178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000180 // Release the DenseMaps associated with DeclContext objects.
181 // FIXME: Is this the ideal solution?
182 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000183
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000184 // Call all of the deallocation functions.
185 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
186 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000187
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000188 // Release all of the memory associated with overridden C++ methods.
189 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
190 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
191 OM != OMEnd; ++OM)
192 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000193
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000195 // because they can contain DenseMaps.
196 for (llvm::DenseMap<const ObjCContainerDecl*,
197 const ASTRecordLayout*>::iterator
198 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000203 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
204 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
205 // Increment in loop to prevent using deallocated memory.
206 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
207 R->Destroy(*this);
208 }
Douglas Gregor63200642010-08-30 16:49:28 +0000209
210 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
211 AEnd = DeclAttrs.end();
212 A != AEnd; ++A)
213 A->second->~AttrVec();
214}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000215
Douglas Gregor00545312010-05-23 18:26:36 +0000216void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
217 Deallocations.push_back(std::make_pair(Callback, Data));
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000221ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
222 ExternalSource.reset(Source.take());
223}
224
Reid Spencer5f016e22007-07-11 17:01:13 +0000225void ASTContext::PrintStats() const {
226 fprintf(stderr, "*** AST Context Stats:\n");
227 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000228
Douglas Gregordbe833d2009-05-26 14:40:08 +0000229 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000230#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000231#define ABSTRACT_TYPE(Name, Parent)
232#include "clang/AST/TypeNodes.def"
233 0 // Extra
234 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000235
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
237 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000238 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
240
Douglas Gregordbe833d2009-05-26 14:40:08 +0000241 unsigned Idx = 0;
242 unsigned TotalBytes = 0;
243#define TYPE(Name, Parent) \
244 if (counts[Idx]) \
245 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
246 TotalBytes += counts[Idx] * sizeof(Name##Type); \
247 ++Idx;
248#define ABSTRACT_TYPE(Name, Parent)
249#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Douglas Gregordbe833d2009-05-26 14:40:08 +0000251 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000252
Douglas Gregor4923aa22010-07-02 20:37:36 +0000253 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000254 fprintf(stderr, " %u/%u implicit default constructors created\n",
255 NumImplicitDefaultConstructorsDeclared,
256 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000257 fprintf(stderr, " %u/%u implicit copy constructors created\n",
258 NumImplicitCopyConstructorsDeclared,
259 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000260 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
261 NumImplicitCopyAssignmentOperatorsDeclared,
262 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000263 fprintf(stderr, " %u/%u implicit destructors created\n",
264 NumImplicitDestructorsDeclared, NumImplicitDestructors);
265
Douglas Gregor2cf26342009-04-09 22:27:44 +0000266 if (ExternalSource.get()) {
267 fprintf(stderr, "\n");
268 ExternalSource->PrintStats();
269 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000270
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000271 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000272}
273
274
John McCalle27ec8a2009-10-23 23:03:21 +0000275void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000276 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000277 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000278 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279}
280
Reid Spencer5f016e22007-07-11 17:01:13 +0000281void ASTContext::InitBuiltinTypes() {
282 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 // C99 6.2.5p19.
285 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 // C99 6.2.5p2.
288 InitBuiltinType(BoolTy, BuiltinType::Bool);
289 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000290 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 InitBuiltinType(CharTy, BuiltinType::Char_S);
292 else
293 InitBuiltinType(CharTy, BuiltinType::Char_U);
294 // C99 6.2.5p4.
295 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
296 InitBuiltinType(ShortTy, BuiltinType::Short);
297 InitBuiltinType(IntTy, BuiltinType::Int);
298 InitBuiltinType(LongTy, BuiltinType::Long);
299 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 // C99 6.2.5p6.
302 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
303 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
304 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
305 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
306 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 // C99 6.2.5p10.
309 InitBuiltinType(FloatTy, BuiltinType::Float);
310 InitBuiltinType(DoubleTy, BuiltinType::Double);
311 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000312
Chris Lattner2df9ced2009-04-30 02:43:43 +0000313 // GNU extension, 128-bit integers.
314 InitBuiltinType(Int128Ty, BuiltinType::Int128);
315 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
316
Chris Lattner3a250322009-02-26 23:43:47 +0000317 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
318 InitBuiltinType(WCharTy, BuiltinType::WChar);
319 else // C99
320 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000321
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
323 InitBuiltinType(Char16Ty, BuiltinType::Char16);
324 else // C99
325 Char16Ty = getFromTargetType(Target.getChar16Type());
326
327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
328 InitBuiltinType(Char32Ty, BuiltinType::Char32);
329 else // C99
330 Char32Ty = getFromTargetType(Target.getChar32Type());
331
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000332 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000333 InitBuiltinType(OverloadTy, BuiltinType::Overload);
334
335 // Placeholder type for type-dependent expressions whose type is
336 // completely unknown. No code should ever check a type against
337 // DependentTy and users should never see it; however, it is here to
338 // help diagnose failures to properly check for type-dependent
339 // expressions.
340 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000341
Mike Stump1eb44332009-09-09 15:08:12 +0000342 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000343 // not yet been deduced.
344 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // C99 6.2.5p11.
347 FloatComplexTy = getComplexType(FloatTy);
348 DoubleComplexTy = getComplexType(DoubleTy);
349 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000350
Steve Naroff7e219e42007-10-15 14:41:52 +0000351 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroffde2e22d2009-07-15 18:40:39 +0000353 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
354 ObjCIdTypedefType = QualType();
355 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000356 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000358 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000359 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
360 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000361 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000362
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000363 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000365 // void * type
366 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000367
368 // nullptr type (C++0x 2.14.7)
369 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370}
371
Douglas Gregor63200642010-08-30 16:49:28 +0000372AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
373 AttrVec *&Result = DeclAttrs[D];
374 if (!Result) {
375 void *Mem = Allocate(sizeof(AttrVec));
376 Result = new (Mem) AttrVec;
377 }
378
379 return *Result;
380}
381
382/// \brief Erase the attributes corresponding to the given declaration.
383void ASTContext::eraseDeclAttrs(const Decl *D) {
384 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
385 if (Pos != DeclAttrs.end()) {
386 Pos->second->~AttrVec();
387 DeclAttrs.erase(Pos);
388 }
389}
390
391
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000392MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000393ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000394 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000395 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000396 = InstantiatedFromStaticDataMember.find(Var);
397 if (Pos == InstantiatedFromStaticDataMember.end())
398 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Douglas Gregor7caa6822009-07-24 20:34:43 +0000400 return Pos->second;
401}
402
Mike Stump1eb44332009-09-09 15:08:12 +0000403void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000404ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000405 TemplateSpecializationKind TSK,
406 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000407 assert(Inst->isStaticDataMember() && "Not a static data member");
408 assert(Tmpl->isStaticDataMember() && "Not a static data member");
409 assert(!InstantiatedFromStaticDataMember[Inst] &&
410 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000411 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000412 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000413}
414
John McCall7ba107a2009-11-18 02:36:19 +0000415NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000416ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000417 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000418 = InstantiatedFromUsingDecl.find(UUD);
419 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000420 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Anders Carlsson0d8df782009-08-29 19:37:28 +0000422 return Pos->second;
423}
424
425void
John McCalled976492009-12-04 22:46:56 +0000426ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
427 assert((isa<UsingDecl>(Pattern) ||
428 isa<UnresolvedUsingValueDecl>(Pattern) ||
429 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
430 "pattern decl is not a using decl");
431 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
432 InstantiatedFromUsingDecl[Inst] = Pattern;
433}
434
435UsingShadowDecl *
436ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
437 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
438 = InstantiatedFromUsingShadowDecl.find(Inst);
439 if (Pos == InstantiatedFromUsingShadowDecl.end())
440 return 0;
441
442 return Pos->second;
443}
444
445void
446ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
447 UsingShadowDecl *Pattern) {
448 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
449 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000450}
451
Anders Carlssond8b285f2009-09-01 04:26:58 +0000452FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
453 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
454 = InstantiatedFromUnnamedFieldDecl.find(Field);
455 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
456 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Anders Carlssond8b285f2009-09-01 04:26:58 +0000458 return Pos->second;
459}
460
461void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
462 FieldDecl *Tmpl) {
463 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
464 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
465 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
466 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Anders Carlssond8b285f2009-09-01 04:26:58 +0000468 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
469}
470
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000471ASTContext::overridden_cxx_method_iterator
472ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
473 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
474 = OverriddenMethods.find(Method);
475 if (Pos == OverriddenMethods.end())
476 return 0;
477
478 return Pos->second.begin();
479}
480
481ASTContext::overridden_cxx_method_iterator
482ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
483 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
484 = OverriddenMethods.find(Method);
485 if (Pos == OverriddenMethods.end())
486 return 0;
487
488 return Pos->second.end();
489}
490
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000491unsigned
492ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
493 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
494 = OverriddenMethods.find(Method);
495 if (Pos == OverriddenMethods.end())
496 return 0;
497
498 return Pos->second.size();
499}
500
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000501void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
502 const CXXMethodDecl *Overridden) {
503 OverriddenMethods[Method].push_back(Overridden);
504}
505
Chris Lattner464175b2007-07-18 17:52:12 +0000506//===----------------------------------------------------------------------===//
507// Type Sizing and Analysis
508//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000509
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000510/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
511/// scalar floating point type.
512const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000513 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000514 assert(BT && "Not a floating point type!");
515 switch (BT->getKind()) {
516 default: assert(0 && "Not a floating point type!");
517 case BuiltinType::Float: return Target.getFloatFormat();
518 case BuiltinType::Double: return Target.getDoubleFormat();
519 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
520 }
521}
522
Ken Dyck8b752f12010-01-27 17:10:57 +0000523/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000524/// specified decl. Note that bitfields do not have a valid alignment, so
525/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000526/// If @p RefAsPointee, references are treated like their underlying type
527/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000528CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000529 unsigned Align = Target.getCharWidth();
530
Sean Huntcf807c42010-08-18 23:23:40 +0000531 Align = std::max(Align, D->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000532
Chris Lattneraf707ab2009-01-24 21:53:27 +0000533 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
534 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000535 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000536 if (RefAsPointee)
537 T = RT->getPointeeType();
538 else
539 T = getPointerType(RT->getPointeeType());
540 }
541 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000542 unsigned MinWidth = Target.getLargeArrayMinWidth();
543 unsigned ArrayAlign = Target.getLargeArrayAlign();
544 if (isa<VariableArrayType>(T) && MinWidth != 0)
545 Align = std::max(Align, ArrayAlign);
546 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
547 unsigned Size = getTypeSize(CT);
548 if (MinWidth != 0 && MinWidth <= Size)
549 Align = std::max(Align, ArrayAlign);
550 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000551 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000552 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
553 T = cast<ArrayType>(T)->getElementType();
554
555 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
556 }
Charles Davis05f62472010-02-23 04:52:00 +0000557 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
558 // In the case of a field in a packed struct, we want the minimum
559 // of the alignment of the field and the alignment of the struct.
560 Align = std::min(Align,
561 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
562 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000563 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000564
Ken Dyck8b752f12010-01-27 17:10:57 +0000565 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000566}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000567
John McCallea1471e2010-05-20 01:18:31 +0000568std::pair<CharUnits, CharUnits>
569ASTContext::getTypeInfoInChars(const Type *T) {
570 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
571 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
572 CharUnits::fromQuantity(Info.second / getCharWidth()));
573}
574
575std::pair<CharUnits, CharUnits>
576ASTContext::getTypeInfoInChars(QualType T) {
577 return getTypeInfoInChars(T.getTypePtr());
578}
579
Chris Lattnera7674d82007-07-13 22:13:22 +0000580/// getTypeSize - Return the size of the specified type, in bits. This method
581/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000582///
583/// FIXME: Pointers into different addr spaces could have different sizes and
584/// alignment requirements: getPointerInfo should take an AddrSpace, this
585/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000586std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000587ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000588 uint64_t Width=0;
589 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000590 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000591#define TYPE(Class, Base)
592#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000593#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000594#define DEPENDENT_TYPE(Class, Base) case Type::Class:
595#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000596 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000597 break;
598
Chris Lattner692233e2007-07-13 22:27:08 +0000599 case Type::FunctionNoProto:
600 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000601 // GCC extension: alignof(function) = 32 bits
602 Width = 0;
603 Align = 32;
604 break;
605
Douglas Gregor72564e72009-02-26 23:50:07 +0000606 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000607 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000608 Width = 0;
609 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
610 break;
611
Steve Narofffb22d962007-08-30 01:06:46 +0000612 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000613 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner98be4942008-03-05 18:54:05 +0000615 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000616 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000617 Align = EltInfo.second;
618 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000619 }
Nate Begeman213541a2008-04-18 23:10:10 +0000620 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000621 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000622 const VectorType *VT = cast<VectorType>(T);
623 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
624 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000625 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000626 // If the alignment is not a power of 2, round up to the next power of 2.
627 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000628 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000629 Align = llvm::NextPowerOf2(Align);
630 Width = llvm::RoundUpToAlignment(Width, Align);
631 }
Chris Lattner030d8842007-07-19 22:06:24 +0000632 break;
633 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000634
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000635 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000636 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000637 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000638 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000639 // GCC extension: alignof(void) = 8 bits.
640 Width = 0;
641 Align = 8;
642 break;
643
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000645 Width = Target.getBoolWidth();
646 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000647 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000648 case BuiltinType::Char_S:
649 case BuiltinType::Char_U:
650 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000651 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000652 Width = Target.getCharWidth();
653 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000654 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000655 case BuiltinType::WChar:
656 Width = Target.getWCharWidth();
657 Align = Target.getWCharAlign();
658 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000659 case BuiltinType::Char16:
660 Width = Target.getChar16Width();
661 Align = Target.getChar16Align();
662 break;
663 case BuiltinType::Char32:
664 Width = Target.getChar32Width();
665 Align = Target.getChar32Align();
666 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000667 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000669 Width = Target.getShortWidth();
670 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000671 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000672 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000674 Width = Target.getIntWidth();
675 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000676 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000677 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000678 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000679 Width = Target.getLongWidth();
680 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000681 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000682 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000684 Width = Target.getLongLongWidth();
685 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000687 case BuiltinType::Int128:
688 case BuiltinType::UInt128:
689 Width = 128;
690 Align = 128; // int128_t is 128-bit aligned on all targets.
691 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000692 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000693 Width = Target.getFloatWidth();
694 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000695 break;
696 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000697 Width = Target.getDoubleWidth();
698 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000699 break;
700 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000701 Width = Target.getLongDoubleWidth();
702 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000703 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000704 case BuiltinType::NullPtr:
705 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
706 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000707 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000708 case BuiltinType::ObjCId:
709 case BuiltinType::ObjCClass:
710 case BuiltinType::ObjCSel:
711 Width = Target.getPointerWidth(0);
712 Align = Target.getPointerAlign(0);
713 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000714 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000715 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000716 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000717 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000718 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000719 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000720 case Type::BlockPointer: {
721 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
722 Width = Target.getPointerWidth(AS);
723 Align = Target.getPointerAlign(AS);
724 break;
725 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000726 case Type::LValueReference:
727 case Type::RValueReference: {
728 // alignof and sizeof should never enter this code path here, so we go
729 // the pointer route.
730 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
731 Width = Target.getPointerWidth(AS);
732 Align = Target.getPointerAlign(AS);
733 break;
734 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000735 case Type::Pointer: {
736 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000737 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000738 Align = Target.getPointerAlign(AS);
739 break;
740 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000741 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000742 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000743 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000744 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000745 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000746 Align = PtrDiffInfo.second;
747 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000748 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000749 case Type::Complex: {
750 // Complex types have the same alignment as their elements, but twice the
751 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000752 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000753 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000754 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000755 Align = EltInfo.second;
756 break;
757 }
John McCallc12c5bb2010-05-15 11:32:37 +0000758 case Type::ObjCObject:
759 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000760 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000761 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000762 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
763 Width = Layout.getSize();
764 Align = Layout.getAlignment();
765 break;
766 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000767 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000768 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000769 const TagType *TT = cast<TagType>(T);
770
771 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000772 Width = 1;
773 Align = 1;
774 break;
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Daniel Dunbar1d751182008-11-08 05:48:37 +0000777 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000778 return getTypeInfo(ET->getDecl()->getIntegerType());
779
Daniel Dunbar1d751182008-11-08 05:48:37 +0000780 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000781 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
782 Width = Layout.getSize();
783 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000784 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000785 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000786
Chris Lattner9fcfe922009-10-22 05:17:15 +0000787 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000788 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
789 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000790
Douglas Gregor18857642009-04-30 17:32:17 +0000791 case Type::Typedef: {
792 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000793 std::pair<uint64_t, unsigned> Info
794 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
795 Align = std::max(Typedef->getMaxAlignment(), Info.second);
796 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000797 break;
Chris Lattner71763312008-04-06 22:05:18 +0000798 }
Douglas Gregor18857642009-04-30 17:32:17 +0000799
800 case Type::TypeOfExpr:
801 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
802 .getTypePtr());
803
804 case Type::TypeOf:
805 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
806
Anders Carlsson395b4752009-06-24 19:06:50 +0000807 case Type::Decltype:
808 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
809 .getTypePtr());
810
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000811 case Type::Elaborated:
812 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Douglas Gregor18857642009-04-30 17:32:17 +0000814 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000815 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000816 "Cannot request the size of a dependent type");
817 // FIXME: this is likely to be wrong once we support template
818 // aliases, since a template alias could refer to a typedef that
819 // has an __aligned__ attribute on it.
820 return getTypeInfo(getCanonicalType(T));
821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Chris Lattner464175b2007-07-18 17:52:12 +0000823 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000824 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000825}
826
Ken Dyckbdc601b2009-12-22 14:23:30 +0000827/// getTypeSizeInChars - Return the size of the specified type, in characters.
828/// This method does not work on incomplete types.
829CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000830 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000831}
832CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000833 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000834}
835
Ken Dyck16e20cc2010-01-26 17:25:18 +0000836/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000837/// characters. This method does not work on incomplete types.
838CharUnits ASTContext::getTypeAlignInChars(QualType T) {
839 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
840}
841CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
842 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
843}
844
Chris Lattner34ebde42009-01-27 18:08:34 +0000845/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
846/// type for the current target in bits. This can be different than the ABI
847/// alignment in cases where it is beneficial for performance to overalign
848/// a data type.
849unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
850 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000851
852 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000853 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000854 T = CT->getElementType().getTypePtr();
855 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
856 T->isSpecificBuiltinType(BuiltinType::LongLong))
857 return std::max(ABIAlign, (unsigned)getTypeSize(T));
858
Chris Lattner34ebde42009-01-27 18:08:34 +0000859 return ABIAlign;
860}
861
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000862/// ShallowCollectObjCIvars -
863/// Collect all ivars, including those synthesized, in the current class.
864///
865void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000866 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000867 // FIXME. This need be removed but there are two many places which
868 // assume const-ness of ObjCInterfaceDecl
869 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
870 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
871 Iv= Iv->getNextIvar())
872 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000873}
874
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000875/// DeepCollectObjCIvars -
876/// This routine first collects all declared, but not synthesized, ivars in
877/// super class and then collects all ivars, including those synthesized for
878/// current class. This routine is used for implementation of current class
879/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000880///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000881void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
882 bool leafClass,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000883 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000884 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
885 DeepCollectObjCIvars(SuperClass, false, Ivars);
886 if (!leafClass) {
887 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
888 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000889 Ivars.push_back(*I);
890 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000891 else
892 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000893}
894
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000895/// CollectInheritedProtocols - Collect all protocols in current class and
896/// those inherited by it.
897void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000898 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000899 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
900 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
901 PE = OI->protocol_end(); P != PE; ++P) {
902 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000903 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000904 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000905 PE = Proto->protocol_end(); P != PE; ++P) {
906 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000907 CollectInheritedProtocols(*P, Protocols);
908 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000909 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000910
911 // Categories of this Interface.
912 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
913 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
914 CollectInheritedProtocols(CDeclChain, Protocols);
915 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
916 while (SD) {
917 CollectInheritedProtocols(SD, Protocols);
918 SD = SD->getSuperClass();
919 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000920 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000921 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
922 PE = OC->protocol_end(); P != PE; ++P) {
923 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000924 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000925 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
926 PE = Proto->protocol_end(); P != PE; ++P)
927 CollectInheritedProtocols(*P, Protocols);
928 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000929 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000930 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
931 PE = OP->protocol_end(); P != PE; ++P) {
932 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000933 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000934 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
935 PE = Proto->protocol_end(); P != PE; ++P)
936 CollectInheritedProtocols(*P, Protocols);
937 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000938 }
939}
940
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000941unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
942 unsigned count = 0;
943 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000944 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
945 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000946 count += CDecl->ivar_size();
947
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000948 // Count ivar defined in this class's implementation. This
949 // includes synthesized ivars.
950 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000951 count += ImplDecl->ivar_size();
952
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000953 return count;
954}
955
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000956/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
957ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
958 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
959 I = ObjCImpls.find(D);
960 if (I != ObjCImpls.end())
961 return cast<ObjCImplementationDecl>(I->second);
962 return 0;
963}
964/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
965ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
966 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
967 I = ObjCImpls.find(D);
968 if (I != ObjCImpls.end())
969 return cast<ObjCCategoryImplDecl>(I->second);
970 return 0;
971}
972
973/// \brief Set the implementation of ObjCInterfaceDecl.
974void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
975 ObjCImplementationDecl *ImplD) {
976 assert(IFaceD && ImplD && "Passed null params");
977 ObjCImpls[IFaceD] = ImplD;
978}
979/// \brief Set the implementation of ObjCCategoryDecl.
980void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
981 ObjCCategoryImplDecl *ImplD) {
982 assert(CatD && ImplD && "Passed null params");
983 ObjCImpls[CatD] = ImplD;
984}
985
John McCalla93c9342009-12-07 02:54:59 +0000986/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000987///
John McCalla93c9342009-12-07 02:54:59 +0000988/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000989/// the TypeLoc wrappers.
990///
991/// \param T the type that will be the basis for type source info. This type
992/// should refer to how the declarator was written in source code, not to
993/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000994TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000995 unsigned DataSize) {
996 if (!DataSize)
997 DataSize = TypeLoc::getFullDataSizeForType(T);
998 else
999 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001000 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001001
John McCalla93c9342009-12-07 02:54:59 +00001002 TypeSourceInfo *TInfo =
1003 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1004 new (TInfo) TypeSourceInfo(T);
1005 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001006}
1007
John McCalla93c9342009-12-07 02:54:59 +00001008TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001009 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001010 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001011 DI->getTypeLoc().initialize(L);
1012 return DI;
1013}
1014
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001015const ASTRecordLayout &
1016ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1017 return getObjCLayout(D, 0);
1018}
1019
1020const ASTRecordLayout &
1021ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1022 return getObjCLayout(D->getClassInterface(), D);
1023}
1024
Chris Lattnera7674d82007-07-13 22:13:22 +00001025//===----------------------------------------------------------------------===//
1026// Type creation/memoization methods
1027//===----------------------------------------------------------------------===//
1028
John McCall0953e762009-09-24 19:53:00 +00001029QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1030 unsigned Fast = Quals.getFastQualifiers();
1031 Quals.removeFastQualifiers();
1032
1033 // Check if we've already instantiated this type.
1034 llvm::FoldingSetNodeID ID;
1035 ExtQuals::Profile(ID, TypeNode, Quals);
1036 void *InsertPos = 0;
1037 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1038 assert(EQ->getQualifiers() == Quals);
1039 QualType T = QualType(EQ, Fast);
1040 return T;
1041 }
1042
John McCall6b304a02009-09-24 23:30:46 +00001043 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001044 ExtQualNodes.InsertNode(New, InsertPos);
1045 QualType T = QualType(New, Fast);
1046 return T;
1047}
1048
1049QualType ASTContext::getVolatileType(QualType T) {
1050 QualType CanT = getCanonicalType(T);
1051 if (CanT.isVolatileQualified()) return T;
1052
1053 QualifierCollector Quals;
1054 const Type *TypeNode = Quals.strip(T);
1055 Quals.addVolatile();
1056
1057 return getExtQualType(TypeNode, Quals);
1058}
1059
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001060QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001061 QualType CanT = getCanonicalType(T);
1062 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001063 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001064
John McCall0953e762009-09-24 19:53:00 +00001065 // If we are composing extended qualifiers together, merge together
1066 // into one ExtQuals node.
1067 QualifierCollector Quals;
1068 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001069
John McCall0953e762009-09-24 19:53:00 +00001070 // If this type already has an address space specified, it cannot get
1071 // another one.
1072 assert(!Quals.hasAddressSpace() &&
1073 "Type cannot be in multiple addr spaces!");
1074 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001075
John McCall0953e762009-09-24 19:53:00 +00001076 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001077}
1078
Chris Lattnerb7d25532009-02-18 22:53:11 +00001079QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001080 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001081 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001082 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001083 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001085 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001086 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001087 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001088 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1089 return getPointerType(ResultType);
1090 }
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
John McCall0953e762009-09-24 19:53:00 +00001093 // If we are composing extended qualifiers together, merge together
1094 // into one ExtQuals node.
1095 QualifierCollector Quals;
1096 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
John McCall0953e762009-09-24 19:53:00 +00001098 // If this type already has an ObjCGC specified, it cannot get
1099 // another one.
1100 assert(!Quals.hasObjCGCAttr() &&
1101 "Type cannot have multiple ObjCGCs!");
1102 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
John McCall0953e762009-09-24 19:53:00 +00001104 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001105}
Chris Lattnera7674d82007-07-13 22:13:22 +00001106
Rafael Espindola264ba482010-03-30 20:24:48 +00001107static QualType getExtFunctionType(ASTContext& Context, QualType T,
1108 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001109 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001110 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1111 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001112 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001113 if (ResultType == Pointee)
1114 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001115
1116 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001117 } else if (const BlockPointerType *BlockPointer
1118 = T->getAs<BlockPointerType>()) {
1119 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001120 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001121 if (ResultType == Pointee)
1122 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001123
1124 ResultType = Context.getBlockPointerType(ResultType);
1125 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001126 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001127 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001128
Douglas Gregor43c79c22009-12-09 00:47:37 +00001129 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001130 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001131 Info);
John McCall0953e762009-09-24 19:53:00 +00001132 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001133 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001134 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001135 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1136 FPT->getNumArgs(), FPT->isVariadic(),
1137 FPT->getTypeQuals(),
1138 FPT->hasExceptionSpec(),
1139 FPT->hasAnyExceptionSpec(),
1140 FPT->getNumExceptions(),
1141 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001142 Info);
John McCall0953e762009-09-24 19:53:00 +00001143 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001144 } else
1145 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001146
1147 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1148}
1149
1150QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001151 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001152 return getExtFunctionType(*this, T,
1153 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001154}
1155
1156QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001157 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001158 return getExtFunctionType(*this, T,
1159 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001160}
1161
Rafael Espindola425ef722010-03-30 22:15:11 +00001162QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1163 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1164 return getExtFunctionType(*this, T,
1165 Info.withRegParm(RegParm));
1166}
1167
Reid Spencer5f016e22007-07-11 17:01:13 +00001168/// getComplexType - Return the uniqued reference to the type for a complex
1169/// number with the specified element type.
1170QualType ASTContext::getComplexType(QualType T) {
1171 // Unique pointers, to guarantee there is only one pointer of a particular
1172 // structure.
1173 llvm::FoldingSetNodeID ID;
1174 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 void *InsertPos = 0;
1177 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1178 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // If the pointee type isn't canonical, this won't be a canonical type either,
1181 // so fill in the canonical type field.
1182 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001183 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001184 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 // Get the new insert position for the node we care about.
1187 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001188 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 }
John McCall6b304a02009-09-24 23:30:46 +00001190 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 Types.push_back(New);
1192 ComplexTypes.InsertNode(New, InsertPos);
1193 return QualType(New, 0);
1194}
1195
Reid Spencer5f016e22007-07-11 17:01:13 +00001196/// getPointerType - Return the uniqued reference to the type for a pointer to
1197/// the specified type.
1198QualType ASTContext::getPointerType(QualType T) {
1199 // Unique pointers, to guarantee there is only one pointer of a particular
1200 // structure.
1201 llvm::FoldingSetNodeID ID;
1202 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 void *InsertPos = 0;
1205 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1206 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 // If the pointee type isn't canonical, this won't be a canonical type either,
1209 // so fill in the canonical type field.
1210 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001211 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001212 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 // Get the new insert position for the node we care about.
1215 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001216 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 }
John McCall6b304a02009-09-24 23:30:46 +00001218 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 Types.push_back(New);
1220 PointerTypes.InsertNode(New, InsertPos);
1221 return QualType(New, 0);
1222}
1223
Mike Stump1eb44332009-09-09 15:08:12 +00001224/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001225/// a pointer to the specified block.
1226QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001227 assert(T->isFunctionType() && "block of function types only");
1228 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001229 // structure.
1230 llvm::FoldingSetNodeID ID;
1231 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Steve Naroff5618bd42008-08-27 16:04:49 +00001233 void *InsertPos = 0;
1234 if (BlockPointerType *PT =
1235 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1236 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001237
1238 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001239 // type either so fill in the canonical type field.
1240 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001241 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001242 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Steve Naroff5618bd42008-08-27 16:04:49 +00001244 // Get the new insert position for the node we care about.
1245 BlockPointerType *NewIP =
1246 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001247 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001248 }
John McCall6b304a02009-09-24 23:30:46 +00001249 BlockPointerType *New
1250 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001251 Types.push_back(New);
1252 BlockPointerTypes.InsertNode(New, InsertPos);
1253 return QualType(New, 0);
1254}
1255
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001256/// getLValueReferenceType - Return the uniqued reference to the type for an
1257/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001258QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 // Unique pointers, to guarantee there is only one pointer of a particular
1260 // structure.
1261 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001262 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263
1264 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001265 if (LValueReferenceType *RT =
1266 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001268
John McCall54e14c42009-10-22 22:37:11 +00001269 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1270
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 // If the referencee type isn't canonical, this won't be a canonical type
1272 // either, so fill in the canonical type field.
1273 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001274 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1275 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1276 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001277
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001279 LValueReferenceType *NewIP =
1280 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001281 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 }
1283
John McCall6b304a02009-09-24 23:30:46 +00001284 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001285 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1286 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001288 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001289
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001290 return QualType(New, 0);
1291}
1292
1293/// getRValueReferenceType - Return the uniqued reference to the type for an
1294/// rvalue reference to the specified type.
1295QualType ASTContext::getRValueReferenceType(QualType T) {
1296 // Unique pointers, to guarantee there is only one pointer of a particular
1297 // structure.
1298 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001299 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001300
1301 void *InsertPos = 0;
1302 if (RValueReferenceType *RT =
1303 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1304 return QualType(RT, 0);
1305
John McCall54e14c42009-10-22 22:37:11 +00001306 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1307
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001308 // If the referencee type isn't canonical, this won't be a canonical type
1309 // either, so fill in the canonical type field.
1310 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001311 if (InnerRef || !T.isCanonical()) {
1312 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1313 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001314
1315 // Get the new insert position for the node we care about.
1316 RValueReferenceType *NewIP =
1317 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1318 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1319 }
1320
John McCall6b304a02009-09-24 23:30:46 +00001321 RValueReferenceType *New
1322 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001323 Types.push_back(New);
1324 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 return QualType(New, 0);
1326}
1327
Sebastian Redlf30208a2009-01-24 21:16:55 +00001328/// getMemberPointerType - Return the uniqued reference to the type for a
1329/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001330QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001331 // Unique pointers, to guarantee there is only one pointer of a particular
1332 // structure.
1333 llvm::FoldingSetNodeID ID;
1334 MemberPointerType::Profile(ID, T, Cls);
1335
1336 void *InsertPos = 0;
1337 if (MemberPointerType *PT =
1338 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1339 return QualType(PT, 0);
1340
1341 // If the pointee or class type isn't canonical, this won't be a canonical
1342 // type either, so fill in the canonical type field.
1343 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001344 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001345 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1346
1347 // Get the new insert position for the node we care about.
1348 MemberPointerType *NewIP =
1349 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1350 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1351 }
John McCall6b304a02009-09-24 23:30:46 +00001352 MemberPointerType *New
1353 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001354 Types.push_back(New);
1355 MemberPointerTypes.InsertNode(New, InsertPos);
1356 return QualType(New, 0);
1357}
1358
Mike Stump1eb44332009-09-09 15:08:12 +00001359/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001360/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001361QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001362 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001363 ArrayType::ArraySizeModifier ASM,
1364 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001365 assert((EltTy->isDependentType() ||
1366 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001367 "Constant array of VLAs is illegal!");
1368
Chris Lattner38aeec72009-05-13 04:12:56 +00001369 // Convert the array size into a canonical width matching the pointer size for
1370 // the target.
1371 llvm::APInt ArySize(ArySizeIn);
1372 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001375 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001378 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001379 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 // If the element type isn't canonical, this won't be a canonical type either,
1383 // so fill in the canonical type field.
1384 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001385 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001386 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001387 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001389 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001391 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
John McCall6b304a02009-09-24 23:30:46 +00001394 ConstantArrayType *New = new(*this,TypeAlignment)
1395 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001396 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 Types.push_back(New);
1398 return QualType(New, 0);
1399}
1400
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001401/// getVariableArrayType - Returns a non-unique reference to the type for a
1402/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001403QualType ASTContext::getVariableArrayType(QualType EltTy,
1404 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001405 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001406 unsigned EltTypeQuals,
1407 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001408 // Since we don't unique expressions, it isn't possible to unique VLA's
1409 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001410 QualType CanonType;
1411
1412 if (!EltTy.isCanonical()) {
1413 if (NumElts)
1414 NumElts->Retain();
1415 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1416 EltTypeQuals, Brackets);
1417 }
1418
John McCall6b304a02009-09-24 23:30:46 +00001419 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001420 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001421
1422 VariableArrayTypes.push_back(New);
1423 Types.push_back(New);
1424 return QualType(New, 0);
1425}
1426
Douglas Gregor898574e2008-12-05 23:32:09 +00001427/// getDependentSizedArrayType - Returns a non-unique reference to
1428/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001429/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001430QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1431 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001432 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001433 unsigned EltTypeQuals,
1434 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001435 assert((!NumElts || NumElts->isTypeDependent() ||
1436 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001437 "Size must be type- or value-dependent!");
1438
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001439 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001440 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001441 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001442
1443 if (NumElts) {
1444 // Dependently-sized array types that do not have a specified
1445 // number of elements will have their sizes deduced from an
1446 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001447 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1448 EltTypeQuals, NumElts);
1449
1450 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1451 }
1452
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001453 DependentSizedArrayType *New;
1454 if (Canon) {
1455 // We already have a canonical version of this array type; use it as
1456 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001457 New = new (*this, TypeAlignment)
1458 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1459 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001460 } else {
1461 QualType CanonEltTy = getCanonicalType(EltTy);
1462 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001463 New = new (*this, TypeAlignment)
1464 DependentSizedArrayType(*this, EltTy, QualType(),
1465 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001466
Douglas Gregor789b1f62010-02-04 18:10:26 +00001467 if (NumElts) {
1468 DependentSizedArrayType *CanonCheck
1469 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1470 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1471 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001472 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001473 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001474 } else {
1475 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1476 ASM, EltTypeQuals,
1477 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001478 New = new (*this, TypeAlignment)
1479 DependentSizedArrayType(*this, EltTy, Canon,
1480 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001481 }
1482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Douglas Gregor898574e2008-12-05 23:32:09 +00001484 Types.push_back(New);
1485 return QualType(New, 0);
1486}
1487
Eli Friedmanc5773c42008-02-15 18:16:39 +00001488QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1489 ArrayType::ArraySizeModifier ASM,
1490 unsigned EltTypeQuals) {
1491 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001492 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001493
1494 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001495 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001496 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1497 return QualType(ATP, 0);
1498
1499 // If the element type isn't canonical, this won't be a canonical type
1500 // either, so fill in the canonical type field.
1501 QualType Canonical;
1502
John McCall467b27b2009-10-22 20:10:53 +00001503 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001504 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001505 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001506
1507 // Get the new insert position for the node we care about.
1508 IncompleteArrayType *NewIP =
1509 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001510 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001511 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001512
John McCall6b304a02009-09-24 23:30:46 +00001513 IncompleteArrayType *New = new (*this, TypeAlignment)
1514 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001515
1516 IncompleteArrayTypes.InsertNode(New, InsertPos);
1517 Types.push_back(New);
1518 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001519}
1520
Steve Naroff73322922007-07-18 18:00:27 +00001521/// getVectorType - Return the unique reference to a vector type of
1522/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001523QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001524 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Chris Lattnerf52ab252008-04-06 22:59:24 +00001527 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001528 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // Check if we've already instantiated a vector of this type.
1531 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001532 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1533
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 void *InsertPos = 0;
1535 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1536 return QualType(VTP, 0);
1537
1538 // If the element type isn't canonical, this won't be a canonical type either,
1539 // so fill in the canonical type field.
1540 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001541 if (!vecType.isCanonical()) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00001542 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1543 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 // Get the new insert position for the node we care about.
1546 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001547 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 }
John McCall6b304a02009-09-24 23:30:46 +00001549 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001550 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 VectorTypes.InsertNode(New, InsertPos);
1552 Types.push_back(New);
1553 return QualType(New, 0);
1554}
1555
Nate Begeman213541a2008-04-18 23:10:10 +00001556/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001557/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001558QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001559 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Chris Lattnerf52ab252008-04-06 22:59:24 +00001561 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001562 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Steve Naroff73322922007-07-18 18:00:27 +00001564 // Check if we've already instantiated a vector of this type.
1565 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001566 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1567 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001568 void *InsertPos = 0;
1569 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1570 return QualType(VTP, 0);
1571
1572 // If the element type isn't canonical, this won't be a canonical type either,
1573 // so fill in the canonical type field.
1574 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001575 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001576 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Steve Naroff73322922007-07-18 18:00:27 +00001578 // Get the new insert position for the node we care about.
1579 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001580 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001581 }
John McCall6b304a02009-09-24 23:30:46 +00001582 ExtVectorType *New = new (*this, TypeAlignment)
1583 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001584 VectorTypes.InsertNode(New, InsertPos);
1585 Types.push_back(New);
1586 return QualType(New, 0);
1587}
1588
Mike Stump1eb44332009-09-09 15:08:12 +00001589QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001590 Expr *SizeExpr,
1591 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001592 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001593 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001594 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001596 void *InsertPos = 0;
1597 DependentSizedExtVectorType *Canon
1598 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1599 DependentSizedExtVectorType *New;
1600 if (Canon) {
1601 // We already have a canonical version of this array type; use it as
1602 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001603 New = new (*this, TypeAlignment)
1604 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1605 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001606 } else {
1607 QualType CanonVecTy = getCanonicalType(vecType);
1608 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001609 New = new (*this, TypeAlignment)
1610 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1611 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001612
1613 DependentSizedExtVectorType *CanonCheck
1614 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1615 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1616 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001617 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1618 } else {
1619 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1620 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001621 New = new (*this, TypeAlignment)
1622 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001623 }
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001626 Types.push_back(New);
1627 return QualType(New, 0);
1628}
1629
Douglas Gregor72564e72009-02-26 23:50:07 +00001630/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001631///
Rafael Espindola264ba482010-03-30 20:24:48 +00001632QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1633 const FunctionType::ExtInfo &Info) {
1634 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 // Unique functions, to guarantee there is only one function of a particular
1636 // structure.
1637 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001638 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001641 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001642 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001646 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001647 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001648 Canonical =
1649 getFunctionNoProtoType(getCanonicalType(ResultTy),
1650 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001653 FunctionNoProtoType *NewIP =
1654 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001655 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
John McCall6b304a02009-09-24 23:30:46 +00001658 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001659 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001661 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 return QualType(New, 0);
1663}
1664
1665/// getFunctionType - Return a normal function type with a typed argument
1666/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001667QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001668 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001669 unsigned TypeQuals, bool hasExceptionSpec,
1670 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001671 const QualType *ExArray,
1672 const FunctionType::ExtInfo &Info) {
1673 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 // Unique functions, to guarantee there is only one function of a particular
1675 // structure.
1676 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001677 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001678 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001679 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680
1681 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001682 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001683 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001685
1686 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001687 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001689 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 isCanonical = false;
1691
1692 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001693 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001695 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 llvm::SmallVector<QualType, 16> CanonicalArgs;
1697 CanonicalArgs.reserve(NumArgs);
1698 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001699 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001700
Chris Lattnerf52ab252008-04-06 22:59:24 +00001701 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001702 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001703 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001704 false, 0, 0,
1705 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001706
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001708 FunctionProtoType *NewIP =
1709 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001710 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001712
Douglas Gregor72564e72009-02-26 23:50:07 +00001713 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001714 // for two variable size arrays (for parameter and exception types) at the
1715 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001716 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001717 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1718 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001719 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001720 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001721 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001722 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001724 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 return QualType(FTP, 0);
1726}
1727
John McCall3cb0ebd2010-03-10 03:28:59 +00001728#ifndef NDEBUG
1729static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1730 if (!isa<CXXRecordDecl>(D)) return false;
1731 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1732 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1733 return true;
1734 if (RD->getDescribedClassTemplate() &&
1735 !isa<ClassTemplateSpecializationDecl>(RD))
1736 return true;
1737 return false;
1738}
1739#endif
1740
1741/// getInjectedClassNameType - Return the unique reference to the
1742/// injected class name type for the specified templated declaration.
1743QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1744 QualType TST) {
1745 assert(NeedsInjectedClassNameType(Decl));
1746 if (Decl->TypeForDecl) {
1747 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001748 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001749 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1750 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1751 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1752 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001753 Decl->TypeForDecl =
1754 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001755 Types.push_back(Decl->TypeForDecl);
1756 }
1757 return QualType(Decl->TypeForDecl, 0);
1758}
1759
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001760/// getTypeDeclType - Return the unique reference to the type for the
1761/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001762QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001763 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001764 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001765
John McCall19c85762010-02-16 03:57:14 +00001766 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001767 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001768
John McCallbecb8d52010-03-10 06:48:02 +00001769 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1770 "Template type parameter types are always available.");
1771
John McCall19c85762010-02-16 03:57:14 +00001772 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001773 assert(!Record->getPreviousDeclaration() &&
1774 "struct/union has previous declaration");
1775 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001776 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001777 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001778 assert(!Enum->getPreviousDeclaration() &&
1779 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001780 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001781 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001782 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1783 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001784 } else
John McCallbecb8d52010-03-10 06:48:02 +00001785 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001786
John McCallbecb8d52010-03-10 06:48:02 +00001787 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001788 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001789}
1790
Reid Spencer5f016e22007-07-11 17:01:13 +00001791/// getTypedefType - Return the unique reference to the type for the
1792/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001793QualType
1794ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001797 if (Canonical.isNull())
1798 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001799 Decl->TypeForDecl = new(*this, TypeAlignment)
1800 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 Types.push_back(Decl->TypeForDecl);
1802 return QualType(Decl->TypeForDecl, 0);
1803}
1804
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001805QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1806 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1807
1808 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1809 if (PrevDecl->TypeForDecl)
1810 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1811
1812 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1813 Types.push_back(Decl->TypeForDecl);
1814 return QualType(Decl->TypeForDecl, 0);
1815}
1816
1817QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1818 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1819
1820 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1821 if (PrevDecl->TypeForDecl)
1822 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1823
1824 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1825 Types.push_back(Decl->TypeForDecl);
1826 return QualType(Decl->TypeForDecl, 0);
1827}
1828
John McCall49a832b2009-10-18 09:09:24 +00001829/// \brief Retrieve a substitution-result type.
1830QualType
1831ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1832 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001833 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001834 && "replacement types must always be canonical");
1835
1836 llvm::FoldingSetNodeID ID;
1837 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1838 void *InsertPos = 0;
1839 SubstTemplateTypeParmType *SubstParm
1840 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1841
1842 if (!SubstParm) {
1843 SubstParm = new (*this, TypeAlignment)
1844 SubstTemplateTypeParmType(Parm, Replacement);
1845 Types.push_back(SubstParm);
1846 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1847 }
1848
1849 return QualType(SubstParm, 0);
1850}
1851
Douglas Gregorfab9d672009-02-05 23:33:38 +00001852/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001853/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001854/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001855QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001856 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001857 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001858 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001859 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001860 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001861 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001862 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1863
1864 if (TypeParm)
1865 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregorefed5c82010-06-16 15:23:05 +00001867 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001868 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001869 TypeParm = new (*this, TypeAlignment)
1870 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001871
1872 TemplateTypeParmType *TypeCheck
1873 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1874 assert(!TypeCheck && "Template type parameter canonical type broken");
1875 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001876 } else
John McCall6b304a02009-09-24 23:30:46 +00001877 TypeParm = new (*this, TypeAlignment)
1878 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001879
1880 Types.push_back(TypeParm);
1881 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1882
1883 return QualType(TypeParm, 0);
1884}
1885
John McCall3cb0ebd2010-03-10 03:28:59 +00001886TypeSourceInfo *
1887ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1888 SourceLocation NameLoc,
1889 const TemplateArgumentListInfo &Args,
1890 QualType CanonType) {
1891 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1892
1893 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1894 TemplateSpecializationTypeLoc TL
1895 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1896 TL.setTemplateNameLoc(NameLoc);
1897 TL.setLAngleLoc(Args.getLAngleLoc());
1898 TL.setRAngleLoc(Args.getRAngleLoc());
1899 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1900 TL.setArgLocInfo(i, Args[i].getLocInfo());
1901 return DI;
1902}
1903
Mike Stump1eb44332009-09-09 15:08:12 +00001904QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001905ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001906 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001907 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001908 unsigned NumArgs = Args.size();
1909
John McCall833ca992009-10-29 08:12:44 +00001910 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1911 ArgVec.reserve(NumArgs);
1912 for (unsigned i = 0; i != NumArgs; ++i)
1913 ArgVec.push_back(Args[i].getArgument());
1914
John McCall31f17ec2010-04-27 00:57:59 +00001915 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001916 Canon);
John McCall833ca992009-10-29 08:12:44 +00001917}
1918
1919QualType
1920ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001921 const TemplateArgument *Args,
1922 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001923 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001924 if (!Canon.isNull())
1925 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001926 else
1927 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001928
Douglas Gregor1275ae02009-07-28 23:00:59 +00001929 // Allocate the (non-canonical) template specialization type, but don't
1930 // try to unique it: these types typically have location information that
1931 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001932 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001933 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001934 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001935 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001936 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001937 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001938 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Douglas Gregor55f6b142009-02-09 18:46:07 +00001940 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001941 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001942}
1943
Mike Stump1eb44332009-09-09 15:08:12 +00001944QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001945ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1946 const TemplateArgument *Args,
1947 unsigned NumArgs) {
1948 // Build the canonical template specialization type.
1949 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1950 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1951 CanonArgs.reserve(NumArgs);
1952 for (unsigned I = 0; I != NumArgs; ++I)
1953 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1954
1955 // Determine whether this canonical template specialization type already
1956 // exists.
1957 llvm::FoldingSetNodeID ID;
1958 TemplateSpecializationType::Profile(ID, CanonTemplate,
1959 CanonArgs.data(), NumArgs, *this);
1960
1961 void *InsertPos = 0;
1962 TemplateSpecializationType *Spec
1963 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1964
1965 if (!Spec) {
1966 // Allocate a new canonical template specialization type.
1967 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1968 sizeof(TemplateArgument) * NumArgs),
1969 TypeAlignment);
1970 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1971 CanonArgs.data(), NumArgs,
1972 QualType());
1973 Types.push_back(Spec);
1974 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1975 }
1976
1977 assert(Spec->isDependentType() &&
1978 "Non-dependent template-id type must have a canonical type");
1979 return QualType(Spec, 0);
1980}
1981
1982QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001983ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1984 NestedNameSpecifier *NNS,
1985 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001986 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001987 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001988
1989 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001990 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001991 if (T)
1992 return QualType(T, 0);
1993
Douglas Gregor789b1f62010-02-04 18:10:26 +00001994 QualType Canon = NamedType;
1995 if (!Canon.isCanonical()) {
1996 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001997 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1998 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001999 (void)CheckT;
2000 }
2001
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002002 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002003 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002004 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002005 return QualType(T, 0);
2006}
2007
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002008QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2009 NestedNameSpecifier *NNS,
2010 const IdentifierInfo *Name,
2011 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002012 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2013
2014 if (Canon.isNull()) {
2015 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002016 ElaboratedTypeKeyword CanonKeyword = Keyword;
2017 if (Keyword == ETK_None)
2018 CanonKeyword = ETK_Typename;
2019
2020 if (CanonNNS != NNS || CanonKeyword != Keyword)
2021 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002022 }
2023
2024 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002025 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002026
2027 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002028 DependentNameType *T
2029 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002030 if (T)
2031 return QualType(T, 0);
2032
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002033 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002034 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002035 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002036 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002037}
2038
Mike Stump1eb44332009-09-09 15:08:12 +00002039QualType
John McCall33500952010-06-11 00:33:02 +00002040ASTContext::getDependentTemplateSpecializationType(
2041 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002042 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002043 const IdentifierInfo *Name,
2044 const TemplateArgumentListInfo &Args) {
2045 // TODO: avoid this copy
2046 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2047 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2048 ArgCopy.push_back(Args[I].getArgument());
2049 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2050 ArgCopy.size(),
2051 ArgCopy.data());
2052}
2053
2054QualType
2055ASTContext::getDependentTemplateSpecializationType(
2056 ElaboratedTypeKeyword Keyword,
2057 NestedNameSpecifier *NNS,
2058 const IdentifierInfo *Name,
2059 unsigned NumArgs,
2060 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002061 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2062
Douglas Gregor789b1f62010-02-04 18:10:26 +00002063 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002064 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2065 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002066
2067 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002068 DependentTemplateSpecializationType *T
2069 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002070 if (T)
2071 return QualType(T, 0);
2072
John McCall33500952010-06-11 00:33:02 +00002073 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002074
John McCall33500952010-06-11 00:33:02 +00002075 ElaboratedTypeKeyword CanonKeyword = Keyword;
2076 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2077
2078 bool AnyNonCanonArgs = false;
2079 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2080 for (unsigned I = 0; I != NumArgs; ++I) {
2081 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2082 if (!CanonArgs[I].structurallyEquals(Args[I]))
2083 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002084 }
2085
John McCall33500952010-06-11 00:33:02 +00002086 QualType Canon;
2087 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2088 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2089 Name, NumArgs,
2090 CanonArgs.data());
2091
2092 // Find the insert position again.
2093 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2094 }
2095
2096 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2097 sizeof(TemplateArgument) * NumArgs),
2098 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002099 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002100 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002101 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002102 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002103 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002104}
2105
Chris Lattner88cb27a2008-04-07 04:56:42 +00002106/// CmpProtocolNames - Comparison predicate for sorting protocols
2107/// alphabetically.
2108static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2109 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002110 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002111}
2112
John McCallc12c5bb2010-05-15 11:32:37 +00002113static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002114 unsigned NumProtocols) {
2115 if (NumProtocols == 0) return true;
2116
2117 for (unsigned i = 1; i != NumProtocols; ++i)
2118 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2119 return false;
2120 return true;
2121}
2122
2123static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002124 unsigned &NumProtocols) {
2125 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Chris Lattner88cb27a2008-04-07 04:56:42 +00002127 // Sort protocols, keyed by name.
2128 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2129
2130 // Remove duplicates.
2131 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2132 NumProtocols = ProtocolsEnd-Protocols;
2133}
2134
John McCallc12c5bb2010-05-15 11:32:37 +00002135QualType ASTContext::getObjCObjectType(QualType BaseType,
2136 ObjCProtocolDecl * const *Protocols,
2137 unsigned NumProtocols) {
2138 // If the base type is an interface and there aren't any protocols
2139 // to add, then the interface type will do just fine.
2140 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2141 return BaseType;
2142
2143 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002144 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002145 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002146 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002147 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2148 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002149
John McCallc12c5bb2010-05-15 11:32:37 +00002150 // Build the canonical type, which has the canonical base type and
2151 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002152 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002153 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2154 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2155 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002156 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2157 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002158 unsigned UniqueCount = NumProtocols;
2159
John McCall54e14c42009-10-22 22:37:11 +00002160 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002161 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2162 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002163 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002164 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2165 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002166 }
2167
2168 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002169 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 }
2171
2172 unsigned Size = sizeof(ObjCObjectTypeImpl);
2173 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2174 void *Mem = Allocate(Size, TypeAlignment);
2175 ObjCObjectTypeImpl *T =
2176 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2177
2178 Types.push_back(T);
2179 ObjCObjectTypes.InsertNode(T, InsertPos);
2180 return QualType(T, 0);
2181}
2182
2183/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2184/// the given object type.
2185QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2186 llvm::FoldingSetNodeID ID;
2187 ObjCObjectPointerType::Profile(ID, ObjectT);
2188
2189 void *InsertPos = 0;
2190 if (ObjCObjectPointerType *QT =
2191 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2192 return QualType(QT, 0);
2193
2194 // Find the canonical object type.
2195 QualType Canonical;
2196 if (!ObjectT.isCanonical()) {
2197 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2198
2199 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002200 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2201 }
2202
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002203 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002204 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2205 ObjCObjectPointerType *QType =
2206 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002208 Types.push_back(QType);
2209 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002210 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002211}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002212
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002213/// getObjCInterfaceType - Return the unique reference to the type for the
2214/// specified ObjC interface decl. The list of protocols is optional.
2215QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2216 if (Decl->TypeForDecl)
2217 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002219 // FIXME: redeclarations?
2220 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2221 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2222 Decl->TypeForDecl = T;
2223 Types.push_back(T);
2224 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002225}
2226
Douglas Gregor72564e72009-02-26 23:50:07 +00002227/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2228/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002229/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002230/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002231/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002232QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002233 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002234 if (tofExpr->isTypeDependent()) {
2235 llvm::FoldingSetNodeID ID;
2236 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Douglas Gregorb1975722009-07-30 23:18:24 +00002238 void *InsertPos = 0;
2239 DependentTypeOfExprType *Canon
2240 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2241 if (Canon) {
2242 // We already have a "canonical" version of an identical, dependent
2243 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002244 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002245 QualType((TypeOfExprType*)Canon, 0));
2246 }
2247 else {
2248 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002249 Canon
2250 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002251 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2252 toe = Canon;
2253 }
2254 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002255 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002256 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002257 }
Steve Naroff9752f252007-08-01 18:02:17 +00002258 Types.push_back(toe);
2259 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002260}
2261
Steve Naroff9752f252007-08-01 18:02:17 +00002262/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2263/// TypeOfType AST's. The only motivation to unique these nodes would be
2264/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002265/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002266/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002267QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002268 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002269 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002270 Types.push_back(tot);
2271 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002272}
2273
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002274/// getDecltypeForExpr - Given an expr, will return the decltype for that
2275/// expression, according to the rules in C++0x [dcl.type.simple]p4
2276static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002277 if (e->isTypeDependent())
2278 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002280 // If e is an id expression or a class member access, decltype(e) is defined
2281 // as the type of the entity named by e.
2282 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2283 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2284 return VD->getType();
2285 }
2286 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2287 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2288 return FD->getType();
2289 }
2290 // If e is a function call or an invocation of an overloaded operator,
2291 // (parentheses around e are ignored), decltype(e) is defined as the
2292 // return type of that function.
2293 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2294 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002296 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002297
2298 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002299 // defined as T&, otherwise decltype(e) is defined as T.
2300 if (e->isLvalue(Context) == Expr::LV_Valid)
2301 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002303 return T;
2304}
2305
Anders Carlsson395b4752009-06-24 19:06:50 +00002306/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2307/// DecltypeType AST's. The only motivation to unique these nodes would be
2308/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002309/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002310/// on canonical type's (which are always unique).
2311QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002312 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002313 if (e->isTypeDependent()) {
2314 llvm::FoldingSetNodeID ID;
2315 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002317 void *InsertPos = 0;
2318 DependentDecltypeType *Canon
2319 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2320 if (Canon) {
2321 // We already have a "canonical" version of an equivalent, dependent
2322 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002323 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002324 QualType((DecltypeType*)Canon, 0));
2325 }
2326 else {
2327 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002328 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002329 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2330 dt = Canon;
2331 }
2332 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002333 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002334 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002335 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002336 Types.push_back(dt);
2337 return QualType(dt, 0);
2338}
2339
Reid Spencer5f016e22007-07-11 17:01:13 +00002340/// getTagDeclType - Return the unique reference to the type for the
2341/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002342QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002343 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002344 // FIXME: What is the design on getTagDeclType when it requires casting
2345 // away const? mutable?
2346 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002347}
2348
Mike Stump1eb44332009-09-09 15:08:12 +00002349/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2350/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2351/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002352CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002353 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002354}
2355
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002356/// getSignedWCharType - Return the type of "signed wchar_t".
2357/// Used when in C++, as a GCC extension.
2358QualType ASTContext::getSignedWCharType() const {
2359 // FIXME: derive from "Target" ?
2360 return WCharTy;
2361}
2362
2363/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2364/// Used when in C++, as a GCC extension.
2365QualType ASTContext::getUnsignedWCharType() const {
2366 // FIXME: derive from "Target" ?
2367 return UnsignedIntTy;
2368}
2369
Chris Lattner8b9023b2007-07-13 03:05:23 +00002370/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2371/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2372QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002373 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002374}
2375
Chris Lattnere6327742008-04-02 05:18:44 +00002376//===----------------------------------------------------------------------===//
2377// Type Operators
2378//===----------------------------------------------------------------------===//
2379
John McCall54e14c42009-10-22 22:37:11 +00002380CanQualType ASTContext::getCanonicalParamType(QualType T) {
2381 // Push qualifiers into arrays, and then discard any remaining
2382 // qualifiers.
2383 T = getCanonicalType(T);
2384 const Type *Ty = T.getTypePtr();
2385
2386 QualType Result;
2387 if (isa<ArrayType>(Ty)) {
2388 Result = getArrayDecayedType(QualType(Ty,0));
2389 } else if (isa<FunctionType>(Ty)) {
2390 Result = getPointerType(QualType(Ty, 0));
2391 } else {
2392 Result = QualType(Ty, 0);
2393 }
2394
2395 return CanQualType::CreateUnsafe(Result);
2396}
2397
Chris Lattner77c96472008-04-06 22:41:35 +00002398/// getCanonicalType - Return the canonical (structural) type corresponding to
2399/// the specified potentially non-canonical type. The non-canonical version
2400/// of a type may have many "decorated" versions of types. Decorators can
2401/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2402/// to be free of any of these, allowing two canonical types to be compared
2403/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002404CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002405 QualifierCollector Quals;
2406 const Type *Ptr = Quals.strip(T);
2407 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002408
John McCall0953e762009-09-24 19:53:00 +00002409 // The canonical internal type will be the canonical type *except*
2410 // that we push type qualifiers down through array types.
2411
2412 // If there are no new qualifiers to push down, stop here.
2413 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002414 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002415
John McCall0953e762009-09-24 19:53:00 +00002416 // If the type qualifiers are on an array type, get the canonical
2417 // type of the array with the qualifiers applied to the element
2418 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002419 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2420 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002421 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002423 // Get the canonical version of the element with the extra qualifiers on it.
2424 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002425 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002426 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002428 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002429 return CanQualType::CreateUnsafe(
2430 getConstantArrayType(NewEltTy, CAT->getSize(),
2431 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002432 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002433 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002434 return CanQualType::CreateUnsafe(
2435 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002436 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Douglas Gregor898574e2008-12-05 23:32:09 +00002438 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002439 return CanQualType::CreateUnsafe(
2440 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002441 DSAT->getSizeExpr() ?
2442 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002443 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002444 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002445 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002446
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002447 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002448 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002449 VAT->getSizeExpr() ?
2450 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002451 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002452 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002453 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002454}
2455
Chandler Carruth28e318c2009-12-29 07:16:59 +00002456QualType ASTContext::getUnqualifiedArrayType(QualType T,
2457 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002458 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002459 const ArrayType *AT = getAsArrayType(T);
2460 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002461 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002462 }
2463
Chandler Carruth28e318c2009-12-29 07:16:59 +00002464 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002465 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002466 if (Elt == UnqualElt)
2467 return T;
2468
Douglas Gregor9dadd942010-05-17 18:45:21 +00002469 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002470 return getConstantArrayType(UnqualElt, CAT->getSize(),
2471 CAT->getSizeModifier(), 0);
2472 }
2473
Douglas Gregor9dadd942010-05-17 18:45:21 +00002474 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002475 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2476 }
2477
Douglas Gregor9dadd942010-05-17 18:45:21 +00002478 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2479 return getVariableArrayType(UnqualElt,
2480 VAT->getSizeExpr() ?
2481 VAT->getSizeExpr()->Retain() : 0,
2482 VAT->getSizeModifier(),
2483 VAT->getIndexTypeCVRQualifiers(),
2484 VAT->getBracketsRange());
2485 }
2486
2487 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002488 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2489 DSAT->getSizeModifier(), 0,
2490 SourceRange());
2491}
2492
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002493/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2494/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2495/// they point to and return true. If T1 and T2 aren't pointer types
2496/// or pointer-to-member types, or if they are not similar at this
2497/// level, returns false and leaves T1 and T2 unchanged. Top-level
2498/// qualifiers on T1 and T2 are ignored. This function will typically
2499/// be called in a loop that successively "unwraps" pointer and
2500/// pointer-to-member types to compare them at each level.
2501bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2502 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2503 *T2PtrType = T2->getAs<PointerType>();
2504 if (T1PtrType && T2PtrType) {
2505 T1 = T1PtrType->getPointeeType();
2506 T2 = T2PtrType->getPointeeType();
2507 return true;
2508 }
2509
2510 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2511 *T2MPType = T2->getAs<MemberPointerType>();
2512 if (T1MPType && T2MPType &&
2513 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2514 QualType(T2MPType->getClass(), 0))) {
2515 T1 = T1MPType->getPointeeType();
2516 T2 = T2MPType->getPointeeType();
2517 return true;
2518 }
2519
2520 if (getLangOptions().ObjC1) {
2521 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2522 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2523 if (T1OPType && T2OPType) {
2524 T1 = T1OPType->getPointeeType();
2525 T2 = T2OPType->getPointeeType();
2526 return true;
2527 }
2528 }
2529
2530 // FIXME: Block pointers, too?
2531
2532 return false;
2533}
2534
Abramo Bagnara25777432010-08-11 22:01:17 +00002535DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2536 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002537 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002538 // DNInfo work in progress: CHECKME: what about DNLoc?
2539 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2540
John McCall80ad16f2009-11-24 18:42:40 +00002541 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002542 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002543 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002544 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2545 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002546 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002547 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2548 // DNInfo work in progress: FIXME: source locations?
2549 DeclarationNameLoc DNLoc;
2550 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2551 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2552 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002553 }
2554 }
2555
John McCall0bd6feb2009-12-02 08:04:21 +00002556 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2557 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002558 // DNInfo work in progress: CHECKME: what about DNLoc?
2559 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002560}
2561
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002562TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002563 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2564 if (TemplateTemplateParmDecl *TTP
2565 = dyn_cast<TemplateTemplateParmDecl>(Template))
2566 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2567
2568 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002569 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002570 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002571
John McCall0bd6feb2009-12-02 08:04:21 +00002572 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002573
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002574 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2575 assert(DTN && "Non-dependent template names must refer to template decls.");
2576 return DTN->CanonicalTemplateName;
2577}
2578
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002579bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2580 X = getCanonicalTemplateName(X);
2581 Y = getCanonicalTemplateName(Y);
2582 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2583}
2584
Mike Stump1eb44332009-09-09 15:08:12 +00002585TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002586ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2587 switch (Arg.getKind()) {
2588 case TemplateArgument::Null:
2589 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregor1275ae02009-07-28 23:00:59 +00002591 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002592 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Douglas Gregor1275ae02009-07-28 23:00:59 +00002594 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002595 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Douglas Gregor788cd062009-11-11 01:00:40 +00002597 case TemplateArgument::Template:
2598 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2599
Douglas Gregor1275ae02009-07-28 23:00:59 +00002600 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002601 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002602 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Douglas Gregor1275ae02009-07-28 23:00:59 +00002604 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002605 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Douglas Gregor1275ae02009-07-28 23:00:59 +00002607 case TemplateArgument::Pack: {
2608 // FIXME: Allocate in ASTContext
2609 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2610 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002611 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002612 AEnd = Arg.pack_end();
2613 A != AEnd; (void)++A, ++Idx)
2614 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregor1275ae02009-07-28 23:00:59 +00002616 TemplateArgument Result;
2617 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2618 return Result;
2619 }
2620 }
2621
2622 // Silence GCC warning
2623 assert(false && "Unhandled template argument kind");
2624 return TemplateArgument();
2625}
2626
Douglas Gregord57959a2009-03-27 23:10:48 +00002627NestedNameSpecifier *
2628ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002629 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002630 return 0;
2631
2632 switch (NNS->getKind()) {
2633 case NestedNameSpecifier::Identifier:
2634 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002635 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002636 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2637 NNS->getAsIdentifier());
2638
2639 case NestedNameSpecifier::Namespace:
2640 // A namespace is canonical; build a nested-name-specifier with
2641 // this namespace and no prefix.
2642 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2643
2644 case NestedNameSpecifier::TypeSpec:
2645 case NestedNameSpecifier::TypeSpecWithTemplate: {
2646 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002647 return NestedNameSpecifier::Create(*this, 0,
2648 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002649 T.getTypePtr());
2650 }
2651
2652 case NestedNameSpecifier::Global:
2653 // The global specifier is canonical and unique.
2654 return NNS;
2655 }
2656
2657 // Required to silence a GCC warning
2658 return 0;
2659}
2660
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002661
2662const ArrayType *ASTContext::getAsArrayType(QualType T) {
2663 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002664 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002665 // Handle the common positive case fast.
2666 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2667 return AT;
2668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
John McCall0953e762009-09-24 19:53:00 +00002670 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002671 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002672 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002673 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002674
John McCall0953e762009-09-24 19:53:00 +00002675 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002676 // implements C99 6.7.3p8: "If the specification of an array type includes
2677 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002679 // If we get here, we either have type qualifiers on the type, or we have
2680 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002681 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002682
John McCall0953e762009-09-24 19:53:00 +00002683 QualifierCollector Qs;
2684 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002686 // If we have a simple case, just return now.
2687 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002688 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002689 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002691 // Otherwise, we have an array and we have qualifiers on it. Push the
2692 // qualifiers into the array element type and return a new array type.
2693 // Get the canonical version of the element with the extra qualifiers on it.
2694 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002695 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002697 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2698 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2699 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002700 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002701 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2702 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2703 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002704 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002705
Mike Stump1eb44332009-09-09 15:08:12 +00002706 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002707 = dyn_cast<DependentSizedArrayType>(ATy))
2708 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002709 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002710 DSAT->getSizeExpr() ?
2711 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002712 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002713 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002714 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002716 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002717 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002718 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002719 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002720 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002721 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002722 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002723}
2724
2725
Chris Lattnere6327742008-04-02 05:18:44 +00002726/// getArrayDecayedType - Return the properly qualified result of decaying the
2727/// specified array type to a pointer. This operation is non-trivial when
2728/// handling typedefs etc. The canonical type of "T" must be an array type,
2729/// this returns a pointer to a properly qualified element of the array.
2730///
2731/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2732QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002733 // Get the element type with 'getAsArrayType' so that we don't lose any
2734 // typedefs in the element type of the array. This also handles propagation
2735 // of type qualifiers from the array type into the element type if present
2736 // (C99 6.7.3p8).
2737 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2738 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002740 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002741
2742 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002743 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002744}
2745
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002746QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002747 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002748 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2749 QT = AT->getElementType();
2750 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002751}
2752
Anders Carlssonfbbce492009-09-25 01:23:32 +00002753QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2754 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Anders Carlssonfbbce492009-09-25 01:23:32 +00002756 if (const ArrayType *AT = getAsArrayType(ElemTy))
2757 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Anders Carlsson6183a992008-12-21 03:44:36 +00002759 return ElemTy;
2760}
2761
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002762/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002763uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002764ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2765 uint64_t ElementCount = 1;
2766 do {
2767 ElementCount *= CA->getSize().getZExtValue();
2768 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2769 } while (CA);
2770 return ElementCount;
2771}
2772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773/// getFloatingRank - Return a relative rank for floating point types.
2774/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002775static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002776 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002778
John McCall183700f2009-09-21 23:43:11 +00002779 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2780 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002781 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 case BuiltinType::Float: return FloatRank;
2783 case BuiltinType::Double: return DoubleRank;
2784 case BuiltinType::LongDouble: return LongDoubleRank;
2785 }
2786}
2787
Mike Stump1eb44332009-09-09 15:08:12 +00002788/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2789/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002790/// 'typeDomain' is a real floating point or complex type.
2791/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002792QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2793 QualType Domain) const {
2794 FloatingRank EltRank = getFloatingRank(Size);
2795 if (Domain->isComplexType()) {
2796 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002797 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002798 case FloatRank: return FloatComplexTy;
2799 case DoubleRank: return DoubleComplexTy;
2800 case LongDoubleRank: return LongDoubleComplexTy;
2801 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 }
Chris Lattner1361b112008-04-06 23:58:54 +00002803
2804 assert(Domain->isRealFloatingType() && "Unknown domain!");
2805 switch (EltRank) {
2806 default: assert(0 && "getFloatingRank(): illegal value for rank");
2807 case FloatRank: return FloatTy;
2808 case DoubleRank: return DoubleTy;
2809 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002810 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002811}
2812
Chris Lattner7cfeb082008-04-06 23:55:33 +00002813/// getFloatingTypeOrder - Compare the rank of the two specified floating
2814/// point types, ignoring the domain of the type (i.e. 'double' ==
2815/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002816/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002817int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2818 FloatingRank LHSR = getFloatingRank(LHS);
2819 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Chris Lattnera75cea32008-04-06 23:38:49 +00002821 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002822 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002823 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002824 return 1;
2825 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826}
2827
Chris Lattnerf52ab252008-04-06 22:59:24 +00002828/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2829/// routine will assert if passed a built-in type that isn't an integer or enum,
2830/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002831unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002832 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002833 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002834 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002835
Eli Friedmana3426752009-07-05 23:44:27 +00002836 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2837 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2838
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002839 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2840 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2841
2842 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2843 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2844
Chris Lattnerf52ab252008-04-06 22:59:24 +00002845 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002846 default: assert(0 && "getIntegerRank(): not a built-in integer");
2847 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002848 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002849 case BuiltinType::Char_S:
2850 case BuiltinType::Char_U:
2851 case BuiltinType::SChar:
2852 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002853 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002854 case BuiltinType::Short:
2855 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002856 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002857 case BuiltinType::Int:
2858 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002859 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002860 case BuiltinType::Long:
2861 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002862 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002863 case BuiltinType::LongLong:
2864 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002865 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002866 case BuiltinType::Int128:
2867 case BuiltinType::UInt128:
2868 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002869 }
2870}
2871
Eli Friedman04e83572009-08-20 04:21:42 +00002872/// \brief Whether this is a promotable bitfield reference according
2873/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2874///
2875/// \returns the type this bit-field will promote to, or NULL if no
2876/// promotion occurs.
2877QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002878 if (E->isTypeDependent() || E->isValueDependent())
2879 return QualType();
2880
Eli Friedman04e83572009-08-20 04:21:42 +00002881 FieldDecl *Field = E->getBitField();
2882 if (!Field)
2883 return QualType();
2884
2885 QualType FT = Field->getType();
2886
2887 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2888 uint64_t BitWidth = BitWidthAP.getZExtValue();
2889 uint64_t IntSize = getTypeSize(IntTy);
2890 // GCC extension compatibility: if the bit-field size is less than or equal
2891 // to the size of int, it gets promoted no matter what its type is.
2892 // For instance, unsigned long bf : 4 gets promoted to signed int.
2893 if (BitWidth < IntSize)
2894 return IntTy;
2895
2896 if (BitWidth == IntSize)
2897 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2898
2899 // Types bigger than int are not subject to promotions, and therefore act
2900 // like the base type.
2901 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2902 // is ridiculous.
2903 return QualType();
2904}
2905
Eli Friedmana95d7572009-08-19 07:44:53 +00002906/// getPromotedIntegerType - Returns the type that Promotable will
2907/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2908/// integer type.
2909QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2910 assert(!Promotable.isNull());
2911 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002912 if (const EnumType *ET = Promotable->getAs<EnumType>())
2913 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002914 if (Promotable->isSignedIntegerType())
2915 return IntTy;
2916 uint64_t PromotableSize = getTypeSize(Promotable);
2917 uint64_t IntSize = getTypeSize(IntTy);
2918 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2919 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2920}
2921
Mike Stump1eb44332009-09-09 15:08:12 +00002922/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002923/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002924/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002925int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002926 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2927 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002928 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Chris Lattnerf52ab252008-04-06 22:59:24 +00002930 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2931 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Chris Lattner7cfeb082008-04-06 23:55:33 +00002933 unsigned LHSRank = getIntegerRank(LHSC);
2934 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Chris Lattner7cfeb082008-04-06 23:55:33 +00002936 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2937 if (LHSRank == RHSRank) return 0;
2938 return LHSRank > RHSRank ? 1 : -1;
2939 }
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Chris Lattner7cfeb082008-04-06 23:55:33 +00002941 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2942 if (LHSUnsigned) {
2943 // If the unsigned [LHS] type is larger, return it.
2944 if (LHSRank >= RHSRank)
2945 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Chris Lattner7cfeb082008-04-06 23:55:33 +00002947 // If the signed type can represent all values of the unsigned type, it
2948 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002949 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002950 return -1;
2951 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002952
Chris Lattner7cfeb082008-04-06 23:55:33 +00002953 // If the unsigned [RHS] type is larger, return it.
2954 if (RHSRank >= LHSRank)
2955 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Chris Lattner7cfeb082008-04-06 23:55:33 +00002957 // If the signed type can represent all values of the unsigned type, it
2958 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002959 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002960 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002961}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002962
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002963static RecordDecl *
2964CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2965 SourceLocation L, IdentifierInfo *Id) {
2966 if (Ctx.getLangOptions().CPlusPlus)
2967 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2968 else
2969 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2970}
2971
Mike Stump1eb44332009-09-09 15:08:12 +00002972// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002973QualType ASTContext::getCFConstantStringType() {
2974 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002975 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002976 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002977 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002978 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002979
Anders Carlssonf06273f2007-11-19 00:25:30 +00002980 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002981
Anders Carlsson71993dd2007-08-17 05:31:46 +00002982 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002983 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002984 // int flags;
2985 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002986 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002987 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002988 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002989 FieldTypes[3] = LongTy;
2990
Anders Carlsson71993dd2007-08-17 05:31:46 +00002991 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002992 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002993 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002994 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002995 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002996 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002997 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002998 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002999 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003000 }
3001
Douglas Gregor838db382010-02-11 01:19:42 +00003002 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003003 }
Mike Stump1eb44332009-09-09 15:08:12 +00003004
Anders Carlsson71993dd2007-08-17 05:31:46 +00003005 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003006}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003007
Douglas Gregor319ac892009-04-23 22:29:11 +00003008void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003009 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003010 assert(Rec && "Invalid CFConstantStringType");
3011 CFConstantStringTypeDecl = Rec->getDecl();
3012}
3013
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003014// getNSConstantStringType - Return the type used for constant NSStrings.
3015QualType ASTContext::getNSConstantStringType() {
3016 if (!NSConstantStringTypeDecl) {
3017 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003018 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003019 &Idents.get("__builtin_NSString"));
3020 NSConstantStringTypeDecl->startDefinition();
3021
3022 QualType FieldTypes[3];
3023
3024 // const int *isa;
3025 FieldTypes[0] = getPointerType(IntTy.withConst());
3026 // const char *str;
3027 FieldTypes[1] = getPointerType(CharTy.withConst());
3028 // unsigned int length;
3029 FieldTypes[2] = UnsignedIntTy;
3030
3031 // Create fields
3032 for (unsigned i = 0; i < 3; ++i) {
3033 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3034 SourceLocation(), 0,
3035 FieldTypes[i], /*TInfo=*/0,
3036 /*BitWidth=*/0,
3037 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003038 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003039 NSConstantStringTypeDecl->addDecl(Field);
3040 }
3041
3042 NSConstantStringTypeDecl->completeDefinition();
3043 }
3044
3045 return getTagDeclType(NSConstantStringTypeDecl);
3046}
3047
3048void ASTContext::setNSConstantStringType(QualType T) {
3049 const RecordType *Rec = T->getAs<RecordType>();
3050 assert(Rec && "Invalid NSConstantStringType");
3051 NSConstantStringTypeDecl = Rec->getDecl();
3052}
3053
Mike Stump1eb44332009-09-09 15:08:12 +00003054QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003055 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003056 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003057 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003058 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003059 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003061 QualType FieldTypes[] = {
3062 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003063 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003064 getPointerType(UnsignedLongTy),
3065 getConstantArrayType(UnsignedLongTy,
3066 llvm::APInt(32, 5), ArrayType::Normal, 0)
3067 };
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Douglas Gregor44b43212008-12-11 16:49:14 +00003069 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003070 FieldDecl *Field = FieldDecl::Create(*this,
3071 ObjCFastEnumerationStateTypeDecl,
3072 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003073 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003074 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003075 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003076 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003077 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003078 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003079 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003080 if (CXXRecordDecl *CXXRD =
3081 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003082 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Douglas Gregor838db382010-02-11 01:19:42 +00003084 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003085 }
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003087 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3088}
3089
Mike Stumpadaaad32009-10-20 02:12:22 +00003090QualType ASTContext::getBlockDescriptorType() {
3091 if (BlockDescriptorType)
3092 return getTagDeclType(BlockDescriptorType);
3093
3094 RecordDecl *T;
3095 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003096 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003097 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003098 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003099
3100 QualType FieldTypes[] = {
3101 UnsignedLongTy,
3102 UnsignedLongTy,
3103 };
3104
3105 const char *FieldNames[] = {
3106 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003107 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003108 };
3109
3110 for (size_t i = 0; i < 2; ++i) {
3111 FieldDecl *Field = FieldDecl::Create(*this,
3112 T,
3113 SourceLocation(),
3114 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003115 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003116 /*BitWidth=*/0,
3117 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003118 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003119 T->addDecl(Field);
3120 }
3121
Douglas Gregor838db382010-02-11 01:19:42 +00003122 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003123
3124 BlockDescriptorType = T;
3125
3126 return getTagDeclType(BlockDescriptorType);
3127}
3128
3129void ASTContext::setBlockDescriptorType(QualType T) {
3130 const RecordType *Rec = T->getAs<RecordType>();
3131 assert(Rec && "Invalid BlockDescriptorType");
3132 BlockDescriptorType = Rec->getDecl();
3133}
3134
Mike Stump083c25e2009-10-22 00:49:09 +00003135QualType ASTContext::getBlockDescriptorExtendedType() {
3136 if (BlockDescriptorExtendedType)
3137 return getTagDeclType(BlockDescriptorExtendedType);
3138
3139 RecordDecl *T;
3140 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003141 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003142 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003143 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003144
3145 QualType FieldTypes[] = {
3146 UnsignedLongTy,
3147 UnsignedLongTy,
3148 getPointerType(VoidPtrTy),
3149 getPointerType(VoidPtrTy)
3150 };
3151
3152 const char *FieldNames[] = {
3153 "reserved",
3154 "Size",
3155 "CopyFuncPtr",
3156 "DestroyFuncPtr"
3157 };
3158
3159 for (size_t i = 0; i < 4; ++i) {
3160 FieldDecl *Field = FieldDecl::Create(*this,
3161 T,
3162 SourceLocation(),
3163 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003164 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003165 /*BitWidth=*/0,
3166 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003167 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003168 T->addDecl(Field);
3169 }
3170
Douglas Gregor838db382010-02-11 01:19:42 +00003171 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003172
3173 BlockDescriptorExtendedType = T;
3174
3175 return getTagDeclType(BlockDescriptorExtendedType);
3176}
3177
3178void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3179 const RecordType *Rec = T->getAs<RecordType>();
3180 assert(Rec && "Invalid BlockDescriptorType");
3181 BlockDescriptorExtendedType = Rec->getDecl();
3182}
3183
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003184bool ASTContext::BlockRequiresCopying(QualType Ty) {
3185 if (Ty->isBlockPointerType())
3186 return true;
3187 if (isObjCNSObjectType(Ty))
3188 return true;
3189 if (Ty->isObjCObjectPointerType())
3190 return true;
3191 return false;
3192}
3193
Daniel Dunbar4087f272010-08-17 22:39:59 +00003194QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003195 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003196 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003197 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003198 // unsigned int __flags;
3199 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003200 // void *__copy_helper; // as needed
3201 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003202 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003203 // } *
3204
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003205 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3206
3207 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003208 llvm::SmallString<36> Name;
3209 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3210 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003211 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003212 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003213 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003214 T->startDefinition();
3215 QualType Int32Ty = IntTy;
3216 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3217 QualType FieldTypes[] = {
3218 getPointerType(VoidPtrTy),
3219 getPointerType(getTagDeclType(T)),
3220 Int32Ty,
3221 Int32Ty,
3222 getPointerType(VoidPtrTy),
3223 getPointerType(VoidPtrTy),
3224 Ty
3225 };
3226
Daniel Dunbar4087f272010-08-17 22:39:59 +00003227 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003228 "__isa",
3229 "__forwarding",
3230 "__flags",
3231 "__size",
3232 "__copy_helper",
3233 "__destroy_helper",
3234 DeclName,
3235 };
3236
3237 for (size_t i = 0; i < 7; ++i) {
3238 if (!HasCopyAndDispose && i >=4 && i <= 5)
3239 continue;
3240 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3241 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003242 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003243 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003244 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003245 T->addDecl(Field);
3246 }
3247
Douglas Gregor838db382010-02-11 01:19:42 +00003248 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003249
3250 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003251}
3252
3253
3254QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003255 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003256 llvm::SmallVectorImpl<const Expr *> &Layout) {
3257
Mike Stumpadaaad32009-10-20 02:12:22 +00003258 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003259 llvm::SmallString<36> Name;
3260 llvm::raw_svector_ostream(Name) << "__block_literal_"
3261 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003262 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003263 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003264 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003265 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003266 QualType FieldTypes[] = {
3267 getPointerType(VoidPtrTy),
3268 IntTy,
3269 IntTy,
3270 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003271 (BlockHasCopyDispose ?
3272 getPointerType(getBlockDescriptorExtendedType()) :
3273 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003274 };
3275
3276 const char *FieldNames[] = {
3277 "__isa",
3278 "__flags",
3279 "__reserved",
3280 "__FuncPtr",
3281 "__descriptor"
3282 };
3283
3284 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003285 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003286 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003287 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003288 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003289 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003290 T->addDecl(Field);
3291 }
3292
John McCallea1471e2010-05-20 01:18:31 +00003293 for (unsigned i = 0; i < Layout.size(); ++i) {
3294 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003295
John McCallea1471e2010-05-20 01:18:31 +00003296 QualType FieldType = E->getType();
3297 IdentifierInfo *FieldName = 0;
3298 if (isa<CXXThisExpr>(E)) {
3299 FieldName = &Idents.get("this");
3300 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3301 const ValueDecl *D = BDRE->getDecl();
3302 FieldName = D->getIdentifier();
3303 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003304 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003305 } else {
3306 // Padding.
3307 assert(isa<ConstantArrayType>(FieldType) &&
3308 isa<DeclRefExpr>(E) &&
3309 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3310 "doesn't match characteristics of padding decl");
3311 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003312
3313 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003314 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003315 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003316 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003317 T->addDecl(Field);
3318 }
3319
Douglas Gregor838db382010-02-11 01:19:42 +00003320 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003321
3322 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003323}
3324
Douglas Gregor319ac892009-04-23 22:29:11 +00003325void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003326 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003327 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3328 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3329}
3330
Anders Carlssone8c49532007-10-29 06:33:42 +00003331// This returns true if a type has been typedefed to BOOL:
3332// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003333static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003334 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003335 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3336 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003338 return false;
3339}
3340
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003341/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003342/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003343CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003344 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003346 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003347 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003348 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003349 // Treat arrays as pointers, since that's how they're passed in.
3350 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003351 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003352 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003353}
3354
3355static inline
3356std::string charUnitsToString(const CharUnits &CU) {
3357 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003358}
3359
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003360/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003361/// declaration.
3362void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3363 std::string& S) {
3364 const BlockDecl *Decl = Expr->getBlockDecl();
3365 QualType BlockTy =
3366 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3367 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003368 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003369 // Compute size of all parameters.
3370 // Start with computing size of a pointer in number of bytes.
3371 // FIXME: There might(should) be a better way of doing this computation!
3372 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003373 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3374 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003375 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003376 E = Decl->param_end(); PI != E; ++PI) {
3377 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003378 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003379 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003380 ParmOffset += sz;
3381 }
3382 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003383 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003384 // Block pointer and offset.
3385 S += "@?0";
3386 ParmOffset = PtrSize;
3387
3388 // Argument types.
3389 ParmOffset = PtrSize;
3390 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3391 Decl->param_end(); PI != E; ++PI) {
3392 ParmVarDecl *PVDecl = *PI;
3393 QualType PType = PVDecl->getOriginalType();
3394 if (const ArrayType *AT =
3395 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3396 // Use array's original type only if it has known number of
3397 // elements.
3398 if (!isa<ConstantArrayType>(AT))
3399 PType = PVDecl->getType();
3400 } else if (PType->isFunctionType())
3401 PType = PVDecl->getType();
3402 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003403 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003404 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003405 }
3406}
3407
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003408/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003409/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003410void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003411 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003412 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003413 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003414 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003415 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003416 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003417 // Compute size of all parameters.
3418 // Start with computing size of a pointer in number of bytes.
3419 // FIXME: There might(should) be a better way of doing this computation!
3420 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003421 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003422 // The first two arguments (self and _cmd) are pointers; account for
3423 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003424 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003425 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003426 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003427 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003428 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003429 assert (sz.isPositive() &&
3430 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003431 ParmOffset += sz;
3432 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003433 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003434 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003435 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003437 // Argument types.
3438 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003439 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003440 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003441 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003442 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003443 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003444 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3445 // Use array's original type only if it has known number of
3446 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003447 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003448 PType = PVDecl->getType();
3449 } else if (PType->isFunctionType())
3450 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003451 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003452 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003453 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003454 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003455 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003456 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003457 }
3458}
3459
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003460/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003461/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003462/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3463/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003464/// Property attributes are stored as a comma-delimited C string. The simple
3465/// attributes readonly and bycopy are encoded as single characters. The
3466/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3467/// encoded as single characters, followed by an identifier. Property types
3468/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003469/// these attributes are defined by the following enumeration:
3470/// @code
3471/// enum PropertyAttributes {
3472/// kPropertyReadOnly = 'R', // property is read-only.
3473/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3474/// kPropertyByref = '&', // property is a reference to the value last assigned
3475/// kPropertyDynamic = 'D', // property is dynamic
3476/// kPropertyGetter = 'G', // followed by getter selector name
3477/// kPropertySetter = 'S', // followed by setter selector name
3478/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3479/// kPropertyType = 't' // followed by old-style type encoding.
3480/// kPropertyWeak = 'W' // 'weak' property
3481/// kPropertyStrong = 'P' // property GC'able
3482/// kPropertyNonAtomic = 'N' // property non-atomic
3483/// };
3484/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003485void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003486 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003487 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003488 // Collect information from the property implementation decl(s).
3489 bool Dynamic = false;
3490 ObjCPropertyImplDecl *SynthesizePID = 0;
3491
3492 // FIXME: Duplicated code due to poor abstraction.
3493 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003494 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003495 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3496 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003497 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003498 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003499 ObjCPropertyImplDecl *PID = *i;
3500 if (PID->getPropertyDecl() == PD) {
3501 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3502 Dynamic = true;
3503 } else {
3504 SynthesizePID = PID;
3505 }
3506 }
3507 }
3508 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003509 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003510 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003511 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003512 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003513 ObjCPropertyImplDecl *PID = *i;
3514 if (PID->getPropertyDecl() == PD) {
3515 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3516 Dynamic = true;
3517 } else {
3518 SynthesizePID = PID;
3519 }
3520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003522 }
3523 }
3524
3525 // FIXME: This is not very efficient.
3526 S = "T";
3527
3528 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003529 // GCC has some special rules regarding encoding of properties which
3530 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003531 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003532 true /* outermost type */,
3533 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003534
3535 if (PD->isReadOnly()) {
3536 S += ",R";
3537 } else {
3538 switch (PD->getSetterKind()) {
3539 case ObjCPropertyDecl::Assign: break;
3540 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003541 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003542 }
3543 }
3544
3545 // It really isn't clear at all what this means, since properties
3546 // are "dynamic by default".
3547 if (Dynamic)
3548 S += ",D";
3549
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003550 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3551 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003553 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3554 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003555 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003556 }
3557
3558 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3559 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003560 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003561 }
3562
3563 if (SynthesizePID) {
3564 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3565 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003566 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003567 }
3568
3569 // FIXME: OBJCGC: weak & strong
3570}
3571
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003572/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003573/// Another legacy compatibility encoding: 32-bit longs are encoded as
3574/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003575/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3576///
3577void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003578 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003579 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003580 if (BT->getKind() == BuiltinType::ULong &&
3581 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003582 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003583 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003584 if (BT->getKind() == BuiltinType::Long &&
3585 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003586 PointeeTy = IntTy;
3587 }
3588 }
3589}
3590
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003591void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003592 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003593 // We follow the behavior of gcc, expanding structures which are
3594 // directly pointed to, and expanding embedded structures. Note that
3595 // these rules are sufficient to prevent recursive encoding of the
3596 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003597 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003598 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003599}
3600
David Chisnall64fd7e82010-06-04 01:10:52 +00003601static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3602 switch (T->getAs<BuiltinType>()->getKind()) {
3603 default: assert(0 && "Unhandled builtin type kind");
3604 case BuiltinType::Void: return 'v';
3605 case BuiltinType::Bool: return 'B';
3606 case BuiltinType::Char_U:
3607 case BuiltinType::UChar: return 'C';
3608 case BuiltinType::UShort: return 'S';
3609 case BuiltinType::UInt: return 'I';
3610 case BuiltinType::ULong:
3611 return
3612 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3613 case BuiltinType::UInt128: return 'T';
3614 case BuiltinType::ULongLong: return 'Q';
3615 case BuiltinType::Char_S:
3616 case BuiltinType::SChar: return 'c';
3617 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003618 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003619 case BuiltinType::Int: return 'i';
3620 case BuiltinType::Long:
3621 return
3622 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3623 case BuiltinType::LongLong: return 'q';
3624 case BuiltinType::Int128: return 't';
3625 case BuiltinType::Float: return 'f';
3626 case BuiltinType::Double: return 'd';
3627 case BuiltinType::LongDouble: return 'd';
3628 }
3629}
3630
Mike Stump1eb44332009-09-09 15:08:12 +00003631static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003632 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003633 const Expr *E = FD->getBitWidth();
3634 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3635 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003636 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003637 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3638 // The GNU runtime requires more information; bitfields are encoded as b,
3639 // then the offset (in bits) of the first element, then the type of the
3640 // bitfield, then the size in bits. For example, in this structure:
3641 //
3642 // struct
3643 // {
3644 // int integer;
3645 // int flags:2;
3646 // };
3647 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3648 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3649 // information is not especially sensible, but we're stuck with it for
3650 // compatibility with GCC, although providing it breaks anything that
3651 // actually uses runtime introspection and wants to work on both runtimes...
3652 if (!Ctx->getLangOptions().NeXTRuntime) {
3653 const RecordDecl *RD = FD->getParent();
3654 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3655 // FIXME: This same linear search is also used in ExprConstant - it might
3656 // be better if the FieldDecl stored its offset. We'd be increasing the
3657 // size of the object slightly, but saving some time every time it is used.
3658 unsigned i = 0;
3659 for (RecordDecl::field_iterator Field = RD->field_begin(),
3660 FieldEnd = RD->field_end();
3661 Field != FieldEnd; (void)++Field, ++i) {
3662 if (*Field == FD)
3663 break;
3664 }
3665 S += llvm::utostr(RL.getFieldOffset(i));
3666 S += ObjCEncodingForPrimitiveKind(Context, T);
3667 }
3668 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003669 S += llvm::utostr(N);
3670}
3671
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003672// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003673void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3674 bool ExpandPointedToStructures,
3675 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003676 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003677 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003678 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003679 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003680 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003681 return EncodeBitField(this, S, T, FD);
3682 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003683 return;
3684 }
Mike Stump1eb44332009-09-09 15:08:12 +00003685
John McCall183700f2009-09-21 23:43:11 +00003686 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003687 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003688 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003689 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003690 return;
3691 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003692
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003693 // encoding for pointer or r3eference types.
3694 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003695 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003696 if (PT->isObjCSelType()) {
3697 S += ':';
3698 return;
3699 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003700 PointeeTy = PT->getPointeeType();
3701 }
3702 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3703 PointeeTy = RT->getPointeeType();
3704 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003705 bool isReadOnly = false;
3706 // For historical/compatibility reasons, the read-only qualifier of the
3707 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3708 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003709 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003710 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003711 if (OutermostType && T.isConstQualified()) {
3712 isReadOnly = true;
3713 S += 'r';
3714 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003715 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003716 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003717 while (P->getAs<PointerType>())
3718 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003719 if (P.isConstQualified()) {
3720 isReadOnly = true;
3721 S += 'r';
3722 }
3723 }
3724 if (isReadOnly) {
3725 // Another legacy compatibility encoding. Some ObjC qualifier and type
3726 // combinations need to be rearranged.
3727 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003728 if (llvm::StringRef(S).endswith("nr"))
3729 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003730 }
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003732 if (PointeeTy->isCharType()) {
3733 // char pointer types should be encoded as '*' unless it is a
3734 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003735 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003736 S += '*';
3737 return;
3738 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003739 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003740 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3741 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3742 S += '#';
3743 return;
3744 }
3745 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3746 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3747 S += '@';
3748 return;
3749 }
3750 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003751 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003752 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003753 getLegacyIntegralTypeEncoding(PointeeTy);
3754
Mike Stump1eb44332009-09-09 15:08:12 +00003755 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003756 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003757 return;
3758 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003759
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003760 if (const ArrayType *AT =
3761 // Ignore type qualifiers etc.
3762 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003763 if (isa<IncompleteArrayType>(AT)) {
3764 // Incomplete arrays are encoded as a pointer to the array element.
3765 S += '^';
3766
Mike Stump1eb44332009-09-09 15:08:12 +00003767 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003768 false, ExpandStructures, FD);
3769 } else {
3770 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Anders Carlsson559a8332009-02-22 01:38:57 +00003772 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3773 S += llvm::utostr(CAT->getSize().getZExtValue());
3774 else {
3775 //Variable length arrays are encoded as a regular array with 0 elements.
3776 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3777 S += '0';
3778 }
Mike Stump1eb44332009-09-09 15:08:12 +00003779
3780 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003781 false, ExpandStructures, FD);
3782 S += ']';
3783 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003784 return;
3785 }
Mike Stump1eb44332009-09-09 15:08:12 +00003786
John McCall183700f2009-09-21 23:43:11 +00003787 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003788 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003789 return;
3790 }
Mike Stump1eb44332009-09-09 15:08:12 +00003791
Ted Kremenek6217b802009-07-29 21:53:49 +00003792 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003793 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003794 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003795 // Anonymous structures print as '?'
3796 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3797 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003798 if (ClassTemplateSpecializationDecl *Spec
3799 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3800 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3801 std::string TemplateArgsStr
3802 = TemplateSpecializationType::PrintTemplateArgumentList(
3803 TemplateArgs.getFlatArgumentList(),
3804 TemplateArgs.flat_size(),
3805 (*this).PrintingPolicy);
3806
3807 S += TemplateArgsStr;
3808 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003809 } else {
3810 S += '?';
3811 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003812 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003813 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003814 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3815 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003816 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003817 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003818 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003819 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003820 S += '"';
3821 }
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003823 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003824 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003825 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003826 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003827 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003828 QualType qt = Field->getType();
3829 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003830 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003831 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003832 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003833 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003834 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003835 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003836 return;
3837 }
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003839 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003840 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003841 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003842 else
3843 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003844 return;
3845 }
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003847 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003848 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003849 return;
3850 }
Mike Stump1eb44332009-09-09 15:08:12 +00003851
John McCallc12c5bb2010-05-15 11:32:37 +00003852 // Ignore protocol qualifiers when mangling at this level.
3853 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3854 T = OT->getBaseType();
3855
John McCall0953e762009-09-24 19:53:00 +00003856 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003857 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003858 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003859 S += '{';
3860 const IdentifierInfo *II = OI->getIdentifier();
3861 S += II->getName();
3862 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003863 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3864 DeepCollectObjCIvars(OI, true, Ivars);
3865 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3866 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3867 if (Field->isBitField())
3868 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003869 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003870 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003871 }
3872 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003873 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003874 }
Mike Stump1eb44332009-09-09 15:08:12 +00003875
John McCall183700f2009-09-21 23:43:11 +00003876 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003877 if (OPT->isObjCIdType()) {
3878 S += '@';
3879 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003880 }
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Steve Naroff27d20a22009-10-28 22:03:49 +00003882 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3883 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3884 // Since this is a binary compatibility issue, need to consult with runtime
3885 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003886 S += '#';
3887 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003888 }
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003890 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003891 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003892 ExpandPointedToStructures,
3893 ExpandStructures, FD);
3894 if (FD || EncodingProperty) {
3895 // Note that we do extended encoding of protocol qualifer list
3896 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003897 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003898 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3899 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003900 S += '<';
3901 S += (*I)->getNameAsString();
3902 S += '>';
3903 }
3904 S += '"';
3905 }
3906 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003907 }
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003909 QualType PointeeTy = OPT->getPointeeType();
3910 if (!EncodingProperty &&
3911 isa<TypedefType>(PointeeTy.getTypePtr())) {
3912 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003913 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003914 // {...};
3915 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003916 getObjCEncodingForTypeImpl(PointeeTy, S,
3917 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003918 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003919 return;
3920 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003921
3922 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003923 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003924 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003925 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003926 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3927 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003928 S += '<';
3929 S += (*I)->getNameAsString();
3930 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003931 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003932 S += '"';
3933 }
3934 return;
3935 }
Mike Stump1eb44332009-09-09 15:08:12 +00003936
John McCall532ec7b2010-05-17 23:56:34 +00003937 // gcc just blithely ignores member pointers.
3938 // TODO: maybe there should be a mangling for these
3939 if (T->getAs<MemberPointerType>())
3940 return;
3941
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003942 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003943}
3944
Mike Stump1eb44332009-09-09 15:08:12 +00003945void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003946 std::string& S) const {
3947 if (QT & Decl::OBJC_TQ_In)
3948 S += 'n';
3949 if (QT & Decl::OBJC_TQ_Inout)
3950 S += 'N';
3951 if (QT & Decl::OBJC_TQ_Out)
3952 S += 'o';
3953 if (QT & Decl::OBJC_TQ_Bycopy)
3954 S += 'O';
3955 if (QT & Decl::OBJC_TQ_Byref)
3956 S += 'R';
3957 if (QT & Decl::OBJC_TQ_Oneway)
3958 S += 'V';
3959}
3960
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003961void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003962 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003964 BuiltinVaListType = T;
3965}
3966
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003967void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003968 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003969}
3970
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003971void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003972 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003973}
3974
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003975void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003976 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003977}
3978
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003979void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003980 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003981}
3982
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003983void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003984 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003985 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003987 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003988}
3989
John McCall0bd6feb2009-12-02 08:04:21 +00003990/// \brief Retrieve the template name that corresponds to a non-empty
3991/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003992TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3993 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003994 unsigned size = End - Begin;
3995 assert(size > 1 && "set is not overloaded!");
3996
3997 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3998 size * sizeof(FunctionTemplateDecl*));
3999 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4000
4001 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004002 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004003 NamedDecl *D = *I;
4004 assert(isa<FunctionTemplateDecl>(D) ||
4005 (isa<UsingShadowDecl>(D) &&
4006 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4007 *Storage++ = D;
4008 }
4009
4010 return TemplateName(OT);
4011}
4012
Douglas Gregor7532dc62009-03-30 22:58:21 +00004013/// \brief Retrieve the template name that represents a qualified
4014/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004015TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004016 bool TemplateKeyword,
4017 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004018 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004019 llvm::FoldingSetNodeID ID;
4020 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4021
4022 void *InsertPos = 0;
4023 QualifiedTemplateName *QTN =
4024 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4025 if (!QTN) {
4026 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4027 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4028 }
4029
4030 return TemplateName(QTN);
4031}
4032
4033/// \brief Retrieve the template name that represents a dependent
4034/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004035TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004036 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004037 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004038 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004039
4040 llvm::FoldingSetNodeID ID;
4041 DependentTemplateName::Profile(ID, NNS, Name);
4042
4043 void *InsertPos = 0;
4044 DependentTemplateName *QTN =
4045 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4046
4047 if (QTN)
4048 return TemplateName(QTN);
4049
4050 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4051 if (CanonNNS == NNS) {
4052 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4053 } else {
4054 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4055 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004056 DependentTemplateName *CheckQTN =
4057 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4058 assert(!CheckQTN && "Dependent type name canonicalization broken");
4059 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004060 }
4061
4062 DependentTemplateNames.InsertNode(QTN, InsertPos);
4063 return TemplateName(QTN);
4064}
4065
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004066/// \brief Retrieve the template name that represents a dependent
4067/// template name such as \c MetaFun::template operator+.
4068TemplateName
4069ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4070 OverloadedOperatorKind Operator) {
4071 assert((!NNS || NNS->isDependent()) &&
4072 "Nested name specifier must be dependent");
4073
4074 llvm::FoldingSetNodeID ID;
4075 DependentTemplateName::Profile(ID, NNS, Operator);
4076
4077 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004078 DependentTemplateName *QTN
4079 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004080
4081 if (QTN)
4082 return TemplateName(QTN);
4083
4084 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4085 if (CanonNNS == NNS) {
4086 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4087 } else {
4088 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4089 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004090
4091 DependentTemplateName *CheckQTN
4092 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4093 assert(!CheckQTN && "Dependent template name canonicalization broken");
4094 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004095 }
4096
4097 DependentTemplateNames.InsertNode(QTN, InsertPos);
4098 return TemplateName(QTN);
4099}
4100
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004101/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004102/// TargetInfo, produce the corresponding type. The unsigned @p Type
4103/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004104CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004105 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004106 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004107 case TargetInfo::SignedShort: return ShortTy;
4108 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4109 case TargetInfo::SignedInt: return IntTy;
4110 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4111 case TargetInfo::SignedLong: return LongTy;
4112 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4113 case TargetInfo::SignedLongLong: return LongLongTy;
4114 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4115 }
4116
4117 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004118 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004119}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004120
4121//===----------------------------------------------------------------------===//
4122// Type Predicates.
4123//===----------------------------------------------------------------------===//
4124
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004125/// isObjCNSObjectType - Return true if this is an NSObject object using
4126/// NSObject attribute on a c-style pointer type.
4127/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004128/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004129///
4130bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4131 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4132 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004133 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004134 return true;
4135 }
Mike Stump1eb44332009-09-09 15:08:12 +00004136 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004137}
4138
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004139/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4140/// garbage collection attribute.
4141///
John McCall0953e762009-09-24 19:53:00 +00004142Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4143 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004144 if (getLangOptions().ObjC1 &&
4145 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004146 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004147 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004148 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004149 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004150 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004151 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004152 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004153 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004154 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004155 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004156 // Non-pointers have none gc'able attribute regardless of the attribute
4157 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004158 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004159 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004160 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004161 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004162}
4163
Chris Lattner6ac46a42008-04-07 06:51:04 +00004164//===----------------------------------------------------------------------===//
4165// Type Compatibility Testing
4166//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004167
Mike Stump1eb44332009-09-09 15:08:12 +00004168/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004169/// compatible.
4170static bool areCompatVectorTypes(const VectorType *LHS,
4171 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004172 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004173 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004174 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004175}
4176
Douglas Gregor255210e2010-08-06 10:14:59 +00004177bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4178 QualType SecondVec) {
4179 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4180 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4181
4182 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4183 return true;
4184
4185 // AltiVec vectors types are identical to equivalent GCC vector types
4186 const VectorType *First = FirstVec->getAs<VectorType>();
4187 const VectorType *Second = SecondVec->getAs<VectorType>();
4188 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4189 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4190 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4191 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4192 hasSameType(First->getElementType(), Second->getElementType()) &&
4193 (First->getNumElements() == Second->getNumElements()))
4194 return true;
4195
4196 return false;
4197}
4198
Steve Naroff4084c302009-07-23 01:01:38 +00004199//===----------------------------------------------------------------------===//
4200// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4201//===----------------------------------------------------------------------===//
4202
4203/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4204/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004205bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4206 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004207 if (lProto == rProto)
4208 return true;
4209 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4210 E = rProto->protocol_end(); PI != E; ++PI)
4211 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4212 return true;
4213 return false;
4214}
4215
Steve Naroff4084c302009-07-23 01:01:38 +00004216/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4217/// return true if lhs's protocols conform to rhs's protocol; false
4218/// otherwise.
4219bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4220 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4221 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4222 return false;
4223}
4224
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004225/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4226/// Class<p1, ...>.
4227bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4228 QualType rhs) {
4229 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4230 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4231 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4232
4233 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4234 E = lhsQID->qual_end(); I != E; ++I) {
4235 bool match = false;
4236 ObjCProtocolDecl *lhsProto = *I;
4237 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4238 E = rhsOPT->qual_end(); J != E; ++J) {
4239 ObjCProtocolDecl *rhsProto = *J;
4240 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4241 match = true;
4242 break;
4243 }
4244 }
4245 if (!match)
4246 return false;
4247 }
4248 return true;
4249}
4250
Steve Naroff4084c302009-07-23 01:01:38 +00004251/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4252/// ObjCQualifiedIDType.
4253bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4254 bool compare) {
4255 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004256 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004257 lhs->isObjCIdType() || lhs->isObjCClassType())
4258 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004259 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004260 rhs->isObjCIdType() || rhs->isObjCClassType())
4261 return true;
4262
4263 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004264 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Steve Naroff4084c302009-07-23 01:01:38 +00004266 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Steve Naroff4084c302009-07-23 01:01:38 +00004268 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004269 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004270 // make sure we check the class hierarchy.
4271 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4272 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4273 E = lhsQID->qual_end(); I != E; ++I) {
4274 // when comparing an id<P> on lhs with a static type on rhs,
4275 // see if static class implements all of id's protocols, directly or
4276 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004277 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004278 return false;
4279 }
4280 }
4281 // If there are no qualifiers and no interface, we have an 'id'.
4282 return true;
4283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004285 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4286 E = lhsQID->qual_end(); I != E; ++I) {
4287 ObjCProtocolDecl *lhsProto = *I;
4288 bool match = false;
4289
4290 // when comparing an id<P> on lhs with a static type on rhs,
4291 // see if static class implements all of id's protocols, directly or
4292 // through its super class and categories.
4293 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4294 E = rhsOPT->qual_end(); J != E; ++J) {
4295 ObjCProtocolDecl *rhsProto = *J;
4296 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4297 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4298 match = true;
4299 break;
4300 }
4301 }
Mike Stump1eb44332009-09-09 15:08:12 +00004302 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004303 // make sure we check the class hierarchy.
4304 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4305 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4306 E = lhsQID->qual_end(); I != E; ++I) {
4307 // when comparing an id<P> on lhs with a static type on rhs,
4308 // see if static class implements all of id's protocols, directly or
4309 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004310 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004311 match = true;
4312 break;
4313 }
4314 }
4315 }
4316 if (!match)
4317 return false;
4318 }
Mike Stump1eb44332009-09-09 15:08:12 +00004319
Steve Naroff4084c302009-07-23 01:01:38 +00004320 return true;
4321 }
Mike Stump1eb44332009-09-09 15:08:12 +00004322
Steve Naroff4084c302009-07-23 01:01:38 +00004323 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4324 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4325
Mike Stump1eb44332009-09-09 15:08:12 +00004326 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004327 lhs->getAsObjCInterfacePointerType()) {
4328 if (lhsOPT->qual_empty()) {
4329 bool match = false;
4330 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4331 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4332 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004333 // when comparing an id<P> on rhs with a static type on lhs,
4334 // static class must implement all of id's protocols directly or
4335 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004336 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004337 match = true;
4338 break;
4339 }
4340 }
4341 if (!match)
4342 return false;
4343 }
4344 return true;
4345 }
Mike Stump1eb44332009-09-09 15:08:12 +00004346 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004347 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4348 E = lhsOPT->qual_end(); I != E; ++I) {
4349 ObjCProtocolDecl *lhsProto = *I;
4350 bool match = false;
4351
4352 // when comparing an id<P> on lhs with a static type on rhs,
4353 // see if static class implements all of id's protocols, directly or
4354 // through its super class and categories.
4355 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4356 E = rhsQID->qual_end(); J != E; ++J) {
4357 ObjCProtocolDecl *rhsProto = *J;
4358 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4359 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4360 match = true;
4361 break;
4362 }
4363 }
4364 if (!match)
4365 return false;
4366 }
4367 return true;
4368 }
4369 return false;
4370}
4371
Eli Friedman3d815e72008-08-22 00:56:42 +00004372/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004373/// compatible for assignment from RHS to LHS. This handles validation of any
4374/// protocol qualifiers on the LHS or RHS.
4375///
Steve Naroff14108da2009-07-10 23:34:53 +00004376bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4377 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004378 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4379 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4380
Steve Naroffde2e22d2009-07-15 18:40:39 +00004381 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004382 if (LHS->isObjCUnqualifiedIdOrClass() ||
4383 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004384 return true;
4385
John McCallc12c5bb2010-05-15 11:32:37 +00004386 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004387 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4388 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004389 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004390
4391 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4392 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4393 QualType(RHSOPT,0));
4394
John McCallc12c5bb2010-05-15 11:32:37 +00004395 // If we have 2 user-defined types, fall into that path.
4396 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004397 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004398
Steve Naroff4084c302009-07-23 01:01:38 +00004399 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004400}
4401
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004402/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4403/// for providing type-safty for objective-c pointers used to pass/return
4404/// arguments in block literals. When passed as arguments, passing 'A*' where
4405/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4406/// not OK. For the return type, the opposite is not OK.
4407bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4408 const ObjCObjectPointerType *LHSOPT,
4409 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004410 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004411 return true;
4412
4413 if (LHSOPT->isObjCBuiltinType()) {
4414 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4415 }
4416
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004417 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004418 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4419 QualType(RHSOPT,0),
4420 false);
4421
4422 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4423 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4424 if (LHS && RHS) { // We have 2 user-defined types.
4425 if (LHS != RHS) {
4426 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4427 return false;
4428 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4429 return true;
4430 }
4431 else
4432 return true;
4433 }
4434 return false;
4435}
4436
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004437/// getIntersectionOfProtocols - This routine finds the intersection of set
4438/// of protocols inherited from two distinct objective-c pointer objects.
4439/// It is used to build composite qualifier list of the composite type of
4440/// the conditional expression involving two objective-c pointer objects.
4441static
4442void getIntersectionOfProtocols(ASTContext &Context,
4443 const ObjCObjectPointerType *LHSOPT,
4444 const ObjCObjectPointerType *RHSOPT,
4445 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4446
John McCallc12c5bb2010-05-15 11:32:37 +00004447 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4448 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4449 assert(LHS->getInterface() && "LHS must have an interface base");
4450 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004451
4452 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4453 unsigned LHSNumProtocols = LHS->getNumProtocols();
4454 if (LHSNumProtocols > 0)
4455 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4456 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004458 Context.CollectInheritedProtocols(LHS->getInterface(),
4459 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004460 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4461 LHSInheritedProtocols.end());
4462 }
4463
4464 unsigned RHSNumProtocols = RHS->getNumProtocols();
4465 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004466 ObjCProtocolDecl **RHSProtocols =
4467 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004468 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4469 if (InheritedProtocolSet.count(RHSProtocols[i]))
4470 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4471 }
4472 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004473 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004474 Context.CollectInheritedProtocols(RHS->getInterface(),
4475 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004476 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4477 RHSInheritedProtocols.begin(),
4478 E = RHSInheritedProtocols.end(); I != E; ++I)
4479 if (InheritedProtocolSet.count((*I)))
4480 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004481 }
4482}
4483
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004484/// areCommonBaseCompatible - Returns common base class of the two classes if
4485/// one found. Note that this is O'2 algorithm. But it will be called as the
4486/// last type comparison in a ?-exp of ObjC pointer types before a
4487/// warning is issued. So, its invokation is extremely rare.
4488QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004489 const ObjCObjectPointerType *Lptr,
4490 const ObjCObjectPointerType *Rptr) {
4491 const ObjCObjectType *LHS = Lptr->getObjectType();
4492 const ObjCObjectType *RHS = Rptr->getObjectType();
4493 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4494 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4495 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004496 return QualType();
4497
John McCallc12c5bb2010-05-15 11:32:37 +00004498 while ((LDecl = LDecl->getSuperClass())) {
4499 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004500 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004501 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4502 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4503
4504 QualType Result = QualType(LHS, 0);
4505 if (!Protocols.empty())
4506 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4507 Result = getObjCObjectPointerType(Result);
4508 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004509 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004510 }
4511
4512 return QualType();
4513}
4514
John McCallc12c5bb2010-05-15 11:32:37 +00004515bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4516 const ObjCObjectType *RHS) {
4517 assert(LHS->getInterface() && "LHS is not an interface type");
4518 assert(RHS->getInterface() && "RHS is not an interface type");
4519
Chris Lattner6ac46a42008-04-07 06:51:04 +00004520 // Verify that the base decls are compatible: the RHS must be a subclass of
4521 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004522 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004524
Chris Lattner6ac46a42008-04-07 06:51:04 +00004525 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4526 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004527 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004528 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Chris Lattner6ac46a42008-04-07 06:51:04 +00004530 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4531 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004532 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004533 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004534
John McCallc12c5bb2010-05-15 11:32:37 +00004535 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4536 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004537 LHSPI != LHSPE; LHSPI++) {
4538 bool RHSImplementsProtocol = false;
4539
4540 // If the RHS doesn't implement the protocol on the left, the types
4541 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004542 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4543 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004544 RHSPI != RHSPE; RHSPI++) {
4545 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004546 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004547 break;
4548 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004549 }
4550 // FIXME: For better diagnostics, consider passing back the protocol name.
4551 if (!RHSImplementsProtocol)
4552 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004553 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004554 // The RHS implements all protocols listed on the LHS.
4555 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004556}
4557
Steve Naroff389bf462009-02-12 17:52:19 +00004558bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4559 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004560 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4561 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004562
Steve Naroff14108da2009-07-10 23:34:53 +00004563 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004564 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004565
4566 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4567 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004568}
4569
Douglas Gregor569c3162010-08-07 11:51:51 +00004570bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4571 return canAssignObjCInterfaces(
4572 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4573 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4574}
4575
Mike Stump1eb44332009-09-09 15:08:12 +00004576/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004577/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004578/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004579/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004580bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4581 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004582 if (getLangOptions().CPlusPlus)
4583 return hasSameType(LHS, RHS);
4584
Douglas Gregor447234d2010-07-29 15:18:02 +00004585 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004586}
4587
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004588bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4589 return !mergeTypes(LHS, RHS, true).isNull();
4590}
4591
4592QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004593 bool OfBlockPointer,
4594 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004595 const FunctionType *lbase = lhs->getAs<FunctionType>();
4596 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004597 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4598 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004599 bool allLTypes = true;
4600 bool allRTypes = true;
4601
4602 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004603 QualType retType;
4604 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004605 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4606 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004607 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004608 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4609 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004610 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004611
4612 if (Unqualified)
4613 retType = retType.getUnqualifiedType();
4614
4615 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4616 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4617 if (Unqualified) {
4618 LRetType = LRetType.getUnqualifiedType();
4619 RRetType = RRetType.getUnqualifiedType();
4620 }
4621
4622 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004623 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004624 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004625 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004626 // FIXME: double check this
4627 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4628 // rbase->getRegParmAttr() != 0 &&
4629 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004630 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4631 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004632 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4633 lbaseInfo.getRegParm();
4634 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4635 if (NoReturn != lbaseInfo.getNoReturn() ||
4636 RegParm != lbaseInfo.getRegParm())
4637 allLTypes = false;
4638 if (NoReturn != rbaseInfo.getNoReturn() ||
4639 RegParm != rbaseInfo.getRegParm())
4640 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004641 CallingConv lcc = lbaseInfo.getCC();
4642 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004643 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004644 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004645 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Eli Friedman3d815e72008-08-22 00:56:42 +00004647 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004648 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4649 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004650 unsigned lproto_nargs = lproto->getNumArgs();
4651 unsigned rproto_nargs = rproto->getNumArgs();
4652
4653 // Compatible functions must have the same number of arguments
4654 if (lproto_nargs != rproto_nargs)
4655 return QualType();
4656
4657 // Variadic and non-variadic functions aren't compatible
4658 if (lproto->isVariadic() != rproto->isVariadic())
4659 return QualType();
4660
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004661 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4662 return QualType();
4663
Eli Friedman3d815e72008-08-22 00:56:42 +00004664 // Check argument compatibility
4665 llvm::SmallVector<QualType, 10> types;
4666 for (unsigned i = 0; i < lproto_nargs; i++) {
4667 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4668 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004669 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4670 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004671 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004672
4673 if (Unqualified)
4674 argtype = argtype.getUnqualifiedType();
4675
Eli Friedman3d815e72008-08-22 00:56:42 +00004676 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004677 if (Unqualified) {
4678 largtype = largtype.getUnqualifiedType();
4679 rargtype = rargtype.getUnqualifiedType();
4680 }
4681
Chris Lattner61710852008-10-05 17:34:18 +00004682 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4683 allLTypes = false;
4684 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4685 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004686 }
4687 if (allLTypes) return lhs;
4688 if (allRTypes) return rhs;
4689 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004690 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004691 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004692 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004693 }
4694
4695 if (lproto) allRTypes = false;
4696 if (rproto) allLTypes = false;
4697
Douglas Gregor72564e72009-02-26 23:50:07 +00004698 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004699 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004700 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004701 if (proto->isVariadic()) return QualType();
4702 // Check that the types are compatible with the types that
4703 // would result from default argument promotions (C99 6.7.5.3p15).
4704 // The only types actually affected are promotable integer
4705 // types and floats, which would be passed as a different
4706 // type depending on whether the prototype is visible.
4707 unsigned proto_nargs = proto->getNumArgs();
4708 for (unsigned i = 0; i < proto_nargs; ++i) {
4709 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004710
4711 // Look at the promotion type of enum types, since that is the type used
4712 // to pass enum values.
4713 if (const EnumType *Enum = argTy->getAs<EnumType>())
4714 argTy = Enum->getDecl()->getPromotionType();
4715
Eli Friedman3d815e72008-08-22 00:56:42 +00004716 if (argTy->isPromotableIntegerType() ||
4717 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4718 return QualType();
4719 }
4720
4721 if (allLTypes) return lhs;
4722 if (allRTypes) return rhs;
4723 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004724 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004725 proto->getTypeQuals(),
4726 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004727 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004728 }
4729
4730 if (allLTypes) return lhs;
4731 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004732 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004733 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004734}
4735
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004736QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004737 bool OfBlockPointer,
4738 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004739 // C++ [expr]: If an expression initially has the type "reference to T", the
4740 // type is adjusted to "T" prior to any further analysis, the expression
4741 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004742 // expression is an lvalue unless the reference is an rvalue reference and
4743 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004744 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4745 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004746
4747 if (Unqualified) {
4748 LHS = LHS.getUnqualifiedType();
4749 RHS = RHS.getUnqualifiedType();
4750 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004751
Eli Friedman3d815e72008-08-22 00:56:42 +00004752 QualType LHSCan = getCanonicalType(LHS),
4753 RHSCan = getCanonicalType(RHS);
4754
4755 // If two types are identical, they are compatible.
4756 if (LHSCan == RHSCan)
4757 return LHS;
4758
John McCall0953e762009-09-24 19:53:00 +00004759 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004760 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4761 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004762 if (LQuals != RQuals) {
4763 // If any of these qualifiers are different, we have a type
4764 // mismatch.
4765 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4766 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4767 return QualType();
4768
4769 // Exactly one GC qualifier difference is allowed: __strong is
4770 // okay if the other type has no GC qualifier but is an Objective
4771 // C object pointer (i.e. implicitly strong by default). We fix
4772 // this by pretending that the unqualified type was actually
4773 // qualified __strong.
4774 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4775 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4776 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4777
4778 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4779 return QualType();
4780
4781 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4782 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4783 }
4784 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4785 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4786 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004787 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004788 }
4789
4790 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004791
Eli Friedman852d63b2009-06-01 01:22:52 +00004792 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4793 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004794
Chris Lattner1adb8832008-01-14 05:45:46 +00004795 // We want to consider the two function types to be the same for these
4796 // comparisons, just force one to the other.
4797 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4798 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004799
4800 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004801 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4802 LHSClass = Type::ConstantArray;
4803 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4804 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004805
John McCallc12c5bb2010-05-15 11:32:37 +00004806 // ObjCInterfaces are just specialized ObjCObjects.
4807 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4808 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4809
Nate Begeman213541a2008-04-18 23:10:10 +00004810 // Canonicalize ExtVector -> Vector.
4811 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4812 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Chris Lattnera36a61f2008-04-07 05:43:21 +00004814 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004815 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004816 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004817 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004818 // Compatibility is based on the underlying type, not the promotion
4819 // type.
John McCall183700f2009-09-21 23:43:11 +00004820 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004821 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4822 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004823 }
John McCall183700f2009-09-21 23:43:11 +00004824 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004825 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4826 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004827 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004828
Eli Friedman3d815e72008-08-22 00:56:42 +00004829 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004830 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004831
Steve Naroff4a746782008-01-09 22:43:08 +00004832 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004833 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004834#define TYPE(Class, Base)
4835#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004836#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004837#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4838#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4839#include "clang/AST/TypeNodes.def"
4840 assert(false && "Non-canonical and dependent types shouldn't get here");
4841 return QualType();
4842
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004843 case Type::LValueReference:
4844 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004845 case Type::MemberPointer:
4846 assert(false && "C++ should never be in mergeTypes");
4847 return QualType();
4848
John McCallc12c5bb2010-05-15 11:32:37 +00004849 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004850 case Type::IncompleteArray:
4851 case Type::VariableArray:
4852 case Type::FunctionProto:
4853 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004854 assert(false && "Types are eliminated above");
4855 return QualType();
4856
Chris Lattner1adb8832008-01-14 05:45:46 +00004857 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004858 {
4859 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004860 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4861 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004862 if (Unqualified) {
4863 LHSPointee = LHSPointee.getUnqualifiedType();
4864 RHSPointee = RHSPointee.getUnqualifiedType();
4865 }
4866 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4867 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004868 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004869 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004870 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004871 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004872 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004873 return getPointerType(ResultType);
4874 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004875 case Type::BlockPointer:
4876 {
4877 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004878 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4879 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004880 if (Unqualified) {
4881 LHSPointee = LHSPointee.getUnqualifiedType();
4882 RHSPointee = RHSPointee.getUnqualifiedType();
4883 }
4884 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4885 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004886 if (ResultType.isNull()) return QualType();
4887 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4888 return LHS;
4889 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4890 return RHS;
4891 return getBlockPointerType(ResultType);
4892 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004893 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004894 {
4895 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4896 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4897 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4898 return QualType();
4899
4900 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4901 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004902 if (Unqualified) {
4903 LHSElem = LHSElem.getUnqualifiedType();
4904 RHSElem = RHSElem.getUnqualifiedType();
4905 }
4906
4907 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004908 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004909 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4910 return LHS;
4911 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4912 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004913 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4914 ArrayType::ArraySizeModifier(), 0);
4915 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4916 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004917 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4918 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004919 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4920 return LHS;
4921 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4922 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004923 if (LVAT) {
4924 // FIXME: This isn't correct! But tricky to implement because
4925 // the array's size has to be the size of LHS, but the type
4926 // has to be different.
4927 return LHS;
4928 }
4929 if (RVAT) {
4930 // FIXME: This isn't correct! But tricky to implement because
4931 // the array's size has to be the size of RHS, but the type
4932 // has to be different.
4933 return RHS;
4934 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004935 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4936 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004937 return getIncompleteArrayType(ResultType,
4938 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004939 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004940 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00004941 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00004942 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004943 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004944 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004945 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004946 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004947 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004948 case Type::Complex:
4949 // Distinct complex types are incompatible.
4950 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004951 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004952 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004953 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4954 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004955 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004956 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004957 case Type::ObjCObject: {
4958 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004959 // FIXME: This should be type compatibility, e.g. whether
4960 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004961 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4962 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4963 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004964 return LHS;
4965
Eli Friedman3d815e72008-08-22 00:56:42 +00004966 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004967 }
Steve Naroff14108da2009-07-10 23:34:53 +00004968 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004969 if (OfBlockPointer) {
4970 if (canAssignObjCInterfacesInBlockPointer(
4971 LHS->getAs<ObjCObjectPointerType>(),
4972 RHS->getAs<ObjCObjectPointerType>()))
4973 return LHS;
4974 return QualType();
4975 }
John McCall183700f2009-09-21 23:43:11 +00004976 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4977 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004978 return LHS;
4979
Steve Naroffbc76dd02008-12-10 22:14:21 +00004980 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004981 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004982 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004983
4984 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004985}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004986
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004987/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4988/// 'RHS' attributes and returns the merged version; including for function
4989/// return types.
4990QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4991 QualType LHSCan = getCanonicalType(LHS),
4992 RHSCan = getCanonicalType(RHS);
4993 // If two types are identical, they are compatible.
4994 if (LHSCan == RHSCan)
4995 return LHS;
4996 if (RHSCan->isFunctionType()) {
4997 if (!LHSCan->isFunctionType())
4998 return QualType();
4999 QualType OldReturnType =
5000 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5001 QualType NewReturnType =
5002 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5003 QualType ResReturnType =
5004 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5005 if (ResReturnType.isNull())
5006 return QualType();
5007 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5008 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5009 // In either case, use OldReturnType to build the new function type.
5010 const FunctionType *F = LHS->getAs<FunctionType>();
5011 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5012 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5013 QualType ResultType
5014 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5015 FPT->getNumArgs(), FPT->isVariadic(),
5016 FPT->getTypeQuals(),
5017 FPT->hasExceptionSpec(),
5018 FPT->hasAnyExceptionSpec(),
5019 FPT->getNumExceptions(),
5020 FPT->exception_begin(),
5021 Info);
5022 return ResultType;
5023 }
5024 }
5025 return QualType();
5026 }
5027
5028 // If the qualifiers are different, the types can still be merged.
5029 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5030 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5031 if (LQuals != RQuals) {
5032 // If any of these qualifiers are different, we have a type mismatch.
5033 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5034 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5035 return QualType();
5036
5037 // Exactly one GC qualifier difference is allowed: __strong is
5038 // okay if the other type has no GC qualifier but is an Objective
5039 // C object pointer (i.e. implicitly strong by default). We fix
5040 // this by pretending that the unqualified type was actually
5041 // qualified __strong.
5042 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5043 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5044 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5045
5046 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5047 return QualType();
5048
5049 if (GC_L == Qualifiers::Strong)
5050 return LHS;
5051 if (GC_R == Qualifiers::Strong)
5052 return RHS;
5053 return QualType();
5054 }
5055
5056 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5057 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5058 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5059 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5060 if (ResQT == LHSBaseQT)
5061 return LHS;
5062 if (ResQT == RHSBaseQT)
5063 return RHS;
5064 }
5065 return QualType();
5066}
5067
Chris Lattner5426bf62008-04-07 07:01:58 +00005068//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005069// Integer Predicates
5070//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005071
Eli Friedmanad74a752008-06-28 06:23:08 +00005072unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005073 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005074 return 1;
John McCall842aef82009-12-09 09:09:27 +00005075 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005076 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005077 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005078 return (unsigned)getTypeSize(T);
5079}
5080
5081QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005082 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005083
5084 // Turn <4 x signed int> -> <4 x unsigned int>
5085 if (const VectorType *VTy = T->getAs<VectorType>())
5086 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005087 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005088
5089 // For enums, we return the unsigned version of the base type.
5090 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005091 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005092
5093 const BuiltinType *BTy = T->getAs<BuiltinType>();
5094 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005095 switch (BTy->getKind()) {
5096 case BuiltinType::Char_S:
5097 case BuiltinType::SChar:
5098 return UnsignedCharTy;
5099 case BuiltinType::Short:
5100 return UnsignedShortTy;
5101 case BuiltinType::Int:
5102 return UnsignedIntTy;
5103 case BuiltinType::Long:
5104 return UnsignedLongTy;
5105 case BuiltinType::LongLong:
5106 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005107 case BuiltinType::Int128:
5108 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005109 default:
5110 assert(0 && "Unexpected signed integer type");
5111 return QualType();
5112 }
5113}
5114
Douglas Gregor2cf26342009-04-09 22:27:44 +00005115ExternalASTSource::~ExternalASTSource() { }
5116
5117void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005118
5119
5120//===----------------------------------------------------------------------===//
5121// Builtin Type Computation
5122//===----------------------------------------------------------------------===//
5123
5124/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5125/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005126static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005127 ASTContext::GetBuiltinTypeError &Error,
5128 bool AllowTypeModifiers = true) {
5129 // Modifiers.
5130 int HowLong = 0;
5131 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005132
Chris Lattner86df27b2009-06-14 00:45:47 +00005133 // Read the modifiers first.
5134 bool Done = false;
5135 while (!Done) {
5136 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005137 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005138 case 'S':
5139 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5140 assert(!Signed && "Can't use 'S' modifier multiple times!");
5141 Signed = true;
5142 break;
5143 case 'U':
5144 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5145 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5146 Unsigned = true;
5147 break;
5148 case 'L':
5149 assert(HowLong <= 2 && "Can't have LLLL modifier");
5150 ++HowLong;
5151 break;
5152 }
5153 }
5154
5155 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005156
Chris Lattner86df27b2009-06-14 00:45:47 +00005157 // Read the base type.
5158 switch (*Str++) {
5159 default: assert(0 && "Unknown builtin type letter!");
5160 case 'v':
5161 assert(HowLong == 0 && !Signed && !Unsigned &&
5162 "Bad modifiers used with 'v'!");
5163 Type = Context.VoidTy;
5164 break;
5165 case 'f':
5166 assert(HowLong == 0 && !Signed && !Unsigned &&
5167 "Bad modifiers used with 'f'!");
5168 Type = Context.FloatTy;
5169 break;
5170 case 'd':
5171 assert(HowLong < 2 && !Signed && !Unsigned &&
5172 "Bad modifiers used with 'd'!");
5173 if (HowLong)
5174 Type = Context.LongDoubleTy;
5175 else
5176 Type = Context.DoubleTy;
5177 break;
5178 case 's':
5179 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5180 if (Unsigned)
5181 Type = Context.UnsignedShortTy;
5182 else
5183 Type = Context.ShortTy;
5184 break;
5185 case 'i':
5186 if (HowLong == 3)
5187 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5188 else if (HowLong == 2)
5189 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5190 else if (HowLong == 1)
5191 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5192 else
5193 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5194 break;
5195 case 'c':
5196 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5197 if (Signed)
5198 Type = Context.SignedCharTy;
5199 else if (Unsigned)
5200 Type = Context.UnsignedCharTy;
5201 else
5202 Type = Context.CharTy;
5203 break;
5204 case 'b': // boolean
5205 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5206 Type = Context.BoolTy;
5207 break;
5208 case 'z': // size_t.
5209 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5210 Type = Context.getSizeType();
5211 break;
5212 case 'F':
5213 Type = Context.getCFConstantStringType();
5214 break;
5215 case 'a':
5216 Type = Context.getBuiltinVaListType();
5217 assert(!Type.isNull() && "builtin va list type not initialized!");
5218 break;
5219 case 'A':
5220 // This is a "reference" to a va_list; however, what exactly
5221 // this means depends on how va_list is defined. There are two
5222 // different kinds of va_list: ones passed by value, and ones
5223 // passed by reference. An example of a by-value va_list is
5224 // x86, where va_list is a char*. An example of by-ref va_list
5225 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5226 // we want this argument to be a char*&; for x86-64, we want
5227 // it to be a __va_list_tag*.
5228 Type = Context.getBuiltinVaListType();
5229 assert(!Type.isNull() && "builtin va list type not initialized!");
5230 if (Type->isArrayType()) {
5231 Type = Context.getArrayDecayedType(Type);
5232 } else {
5233 Type = Context.getLValueReferenceType(Type);
5234 }
5235 break;
5236 case 'V': {
5237 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005238 unsigned NumElements = strtoul(Str, &End, 10);
5239 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005240
Chris Lattner86df27b2009-06-14 00:45:47 +00005241 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Chris Lattner86df27b2009-06-14 00:45:47 +00005243 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005244 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005245 Type = Context.getVectorType(ElementType, NumElements,
5246 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005247 break;
5248 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005249 case 'X': {
5250 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5251 Type = Context.getComplexType(ElementType);
5252 break;
5253 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005254 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005255 Type = Context.getFILEType();
5256 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005257 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005258 return QualType();
5259 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005260 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005261 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005262 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005263 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005264 else
5265 Type = Context.getjmp_bufType();
5266
Mike Stumpfd612db2009-07-28 23:47:15 +00005267 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005268 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005269 return QualType();
5270 }
5271 break;
Mike Stump782fa302009-07-28 02:25:19 +00005272 }
Mike Stump1eb44332009-09-09 15:08:12 +00005273
Chris Lattner86df27b2009-06-14 00:45:47 +00005274 if (!AllowTypeModifiers)
5275 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005276
Chris Lattner86df27b2009-06-14 00:45:47 +00005277 Done = false;
5278 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005279 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005280 default: Done = true; --Str; break;
5281 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005282 case '&':
John McCall187ab372010-03-12 04:21:28 +00005283 {
5284 // Both pointers and references can have their pointee types
5285 // qualified with an address space.
5286 char *End;
5287 unsigned AddrSpace = strtoul(Str, &End, 10);
5288 if (End != Str && AddrSpace != 0) {
5289 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5290 Str = End;
5291 }
5292 }
5293 if (c == '*')
5294 Type = Context.getPointerType(Type);
5295 else
5296 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005297 break;
5298 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5299 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005300 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005301 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005302 case 'D':
5303 Type = Context.getVolatileType(Type);
5304 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005305 }
5306 }
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Chris Lattner86df27b2009-06-14 00:45:47 +00005308 return Type;
5309}
5310
5311/// GetBuiltinType - Return the type for the specified builtin.
5312QualType ASTContext::GetBuiltinType(unsigned id,
5313 GetBuiltinTypeError &Error) {
5314 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005315
Chris Lattner86df27b2009-06-14 00:45:47 +00005316 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005317
Chris Lattner86df27b2009-06-14 00:45:47 +00005318 Error = GE_None;
5319 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5320 if (Error != GE_None)
5321 return QualType();
5322 while (TypeStr[0] && TypeStr[0] != '.') {
5323 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5324 if (Error != GE_None)
5325 return QualType();
5326
5327 // Do array -> pointer decay. The builtin should use the decayed type.
5328 if (Ty->isArrayType())
5329 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Chris Lattner86df27b2009-06-14 00:45:47 +00005331 ArgTypes.push_back(Ty);
5332 }
5333
5334 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5335 "'.' should only occur at end of builtin type list!");
5336
5337 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5338 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5339 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005340
5341 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005342 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005343 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005344 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005345}
Eli Friedmana95d7572009-08-19 07:44:53 +00005346
5347QualType
5348ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5349 // Perform the usual unary conversions. We do this early so that
5350 // integral promotions to "int" can allow us to exit early, in the
5351 // lhs == rhs check. Also, for conversion purposes, we ignore any
5352 // qualifiers. For example, "const float" and "float" are
5353 // equivalent.
5354 if (lhs->isPromotableIntegerType())
5355 lhs = getPromotedIntegerType(lhs);
5356 else
5357 lhs = lhs.getUnqualifiedType();
5358 if (rhs->isPromotableIntegerType())
5359 rhs = getPromotedIntegerType(rhs);
5360 else
5361 rhs = rhs.getUnqualifiedType();
5362
5363 // If both types are identical, no conversion is needed.
5364 if (lhs == rhs)
5365 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005366
Eli Friedmana95d7572009-08-19 07:44:53 +00005367 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5368 // The caller can deal with this (e.g. pointer + int).
5369 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5370 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005371
5372 // At this point, we have two different arithmetic types.
5373
Eli Friedmana95d7572009-08-19 07:44:53 +00005374 // Handle complex types first (C99 6.3.1.8p1).
5375 if (lhs->isComplexType() || rhs->isComplexType()) {
5376 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005377 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005378 // convert the rhs to the lhs complex type.
5379 return lhs;
5380 }
Mike Stump1eb44332009-09-09 15:08:12 +00005381 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005382 // convert the lhs to the rhs complex type.
5383 return rhs;
5384 }
5385 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005386 // When both operands are complex, the shorter operand is converted to the
5387 // type of the longer, and that is the type of the result. This corresponds
5388 // to what is done when combining two real floating-point operands.
5389 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005390 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005391 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005392 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005393 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005394 // "double _Complex" is promoted to "long double _Complex".
5395 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005396
5397 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005398 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005399 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005400 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005401 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005402 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5403 // domains match. This is a requirement for our implementation, C99
5404 // does not require this promotion.
5405 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5406 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5407 return rhs;
5408 } else { // handle "_Complex double, double".
5409 return lhs;
5410 }
5411 }
5412 return lhs; // The domain/size match exactly.
5413 }
5414 // Now handle "real" floating types (i.e. float, double, long double).
5415 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5416 // if we have an integer operand, the result is the real floating type.
5417 if (rhs->isIntegerType()) {
5418 // convert rhs to the lhs floating point type.
5419 return lhs;
5420 }
5421 if (rhs->isComplexIntegerType()) {
5422 // convert rhs to the complex floating point type.
5423 return getComplexType(lhs);
5424 }
5425 if (lhs->isIntegerType()) {
5426 // convert lhs to the rhs floating point type.
5427 return rhs;
5428 }
Mike Stump1eb44332009-09-09 15:08:12 +00005429 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005430 // convert lhs to the complex floating point type.
5431 return getComplexType(rhs);
5432 }
5433 // We have two real floating types, float/complex combos were handled above.
5434 // Convert the smaller operand to the bigger result.
5435 int result = getFloatingTypeOrder(lhs, rhs);
5436 if (result > 0) // convert the rhs
5437 return lhs;
5438 assert(result < 0 && "illegal float comparison");
5439 return rhs; // convert the lhs
5440 }
5441 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5442 // Handle GCC complex int extension.
5443 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5444 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5445
5446 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005447 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005448 rhsComplexInt->getElementType()) >= 0)
5449 return lhs; // convert the rhs
5450 return rhs;
5451 } else if (lhsComplexInt && rhs->isIntegerType()) {
5452 // convert the rhs to the lhs complex type.
5453 return lhs;
5454 } else if (rhsComplexInt && lhs->isIntegerType()) {
5455 // convert the lhs to the rhs complex type.
5456 return rhs;
5457 }
5458 }
5459 // Finally, we have two differing integer types.
5460 // The rules for this case are in C99 6.3.1.8
5461 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005462 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5463 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005464 QualType destType;
5465 if (lhsSigned == rhsSigned) {
5466 // Same signedness; use the higher-ranked type
5467 destType = compare >= 0 ? lhs : rhs;
5468 } else if (compare != (lhsSigned ? 1 : -1)) {
5469 // The unsigned type has greater than or equal rank to the
5470 // signed type, so use the unsigned type
5471 destType = lhsSigned ? rhs : lhs;
5472 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5473 // The two types are different widths; if we are here, that
5474 // means the signed type is larger than the unsigned type, so
5475 // use the signed type.
5476 destType = lhsSigned ? lhs : rhs;
5477 } else {
5478 // The signed type is higher-ranked than the unsigned type,
5479 // but isn't actually any bigger (like unsigned int and long
5480 // on most 32-bit systems). Use the unsigned type corresponding
5481 // to the signed type.
5482 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5483 }
5484 return destType;
5485}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005486
5487GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5488 GVALinkage External = GVA_StrongExternal;
5489
5490 Linkage L = FD->getLinkage();
5491 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5492 FD->getType()->getLinkage() == UniqueExternalLinkage)
5493 L = UniqueExternalLinkage;
5494
5495 switch (L) {
5496 case NoLinkage:
5497 case InternalLinkage:
5498 case UniqueExternalLinkage:
5499 return GVA_Internal;
5500
5501 case ExternalLinkage:
5502 switch (FD->getTemplateSpecializationKind()) {
5503 case TSK_Undeclared:
5504 case TSK_ExplicitSpecialization:
5505 External = GVA_StrongExternal;
5506 break;
5507
5508 case TSK_ExplicitInstantiationDefinition:
5509 return GVA_ExplicitTemplateInstantiation;
5510
5511 case TSK_ExplicitInstantiationDeclaration:
5512 case TSK_ImplicitInstantiation:
5513 External = GVA_TemplateInstantiation;
5514 break;
5515 }
5516 }
5517
5518 if (!FD->isInlined())
5519 return External;
5520
5521 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5522 // GNU or C99 inline semantics. Determine whether this symbol should be
5523 // externally visible.
5524 if (FD->isInlineDefinitionExternallyVisible())
5525 return External;
5526
5527 // C99 inline semantics, where the symbol is not externally visible.
5528 return GVA_C99Inline;
5529 }
5530
5531 // C++0x [temp.explicit]p9:
5532 // [ Note: The intent is that an inline function that is the subject of
5533 // an explicit instantiation declaration will still be implicitly
5534 // instantiated when used so that the body can be considered for
5535 // inlining, but that no out-of-line copy of the inline function would be
5536 // generated in the translation unit. -- end note ]
5537 if (FD->getTemplateSpecializationKind()
5538 == TSK_ExplicitInstantiationDeclaration)
5539 return GVA_C99Inline;
5540
5541 return GVA_CXXInline;
5542}
5543
5544GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5545 // If this is a static data member, compute the kind of template
5546 // specialization. Otherwise, this variable is not part of a
5547 // template.
5548 TemplateSpecializationKind TSK = TSK_Undeclared;
5549 if (VD->isStaticDataMember())
5550 TSK = VD->getTemplateSpecializationKind();
5551
5552 Linkage L = VD->getLinkage();
5553 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5554 VD->getType()->getLinkage() == UniqueExternalLinkage)
5555 L = UniqueExternalLinkage;
5556
5557 switch (L) {
5558 case NoLinkage:
5559 case InternalLinkage:
5560 case UniqueExternalLinkage:
5561 return GVA_Internal;
5562
5563 case ExternalLinkage:
5564 switch (TSK) {
5565 case TSK_Undeclared:
5566 case TSK_ExplicitSpecialization:
5567 return GVA_StrongExternal;
5568
5569 case TSK_ExplicitInstantiationDeclaration:
5570 llvm_unreachable("Variable should not be instantiated");
5571 // Fall through to treat this like any other instantiation.
5572
5573 case TSK_ExplicitInstantiationDefinition:
5574 return GVA_ExplicitTemplateInstantiation;
5575
5576 case TSK_ImplicitInstantiation:
5577 return GVA_TemplateInstantiation;
5578 }
5579 }
5580
5581 return GVA_StrongExternal;
5582}
5583
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005584bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005585 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5586 if (!VD->isFileVarDecl())
5587 return false;
5588 } else if (!isa<FunctionDecl>(D))
5589 return false;
5590
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005591 // Weak references don't produce any output by themselves.
5592 if (D->hasAttr<WeakRefAttr>())
5593 return false;
5594
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005595 // Aliases and used decls are required.
5596 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5597 return true;
5598
5599 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5600 // Forward declarations aren't required.
5601 if (!FD->isThisDeclarationADefinition())
5602 return false;
5603
5604 // Constructors and destructors are required.
5605 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5606 return true;
5607
5608 // The key function for a class is required.
5609 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5610 const CXXRecordDecl *RD = MD->getParent();
5611 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5612 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5613 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5614 return true;
5615 }
5616 }
5617
5618 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5619
5620 // static, static inline, always_inline, and extern inline functions can
5621 // always be deferred. Normal inline functions can be deferred in C99/C++.
5622 // Implicit template instantiations can also be deferred in C++.
5623 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5624 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5625 return false;
5626 return true;
5627 }
5628
5629 const VarDecl *VD = cast<VarDecl>(D);
5630 assert(VD->isFileVarDecl() && "Expected file scoped var");
5631
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005632 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5633 return false;
5634
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005635 // Structs that have non-trivial constructors or destructors are required.
5636
5637 // FIXME: Handle references.
5638 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5639 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005640 if (RD->hasDefinition() &&
5641 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005642 return true;
5643 }
5644 }
5645
5646 GVALinkage L = GetGVALinkageForVariable(VD);
5647 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5648 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5649 return false;
5650 }
5651
5652 return true;
5653}
Charles Davis071cc7d2010-08-16 03:33:14 +00005654
5655CXXABI::~CXXABI() {}