blob: 4591a0f3c55c6837632537a83f082ad2f656f1d9 [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)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000900 // We can use protocol_iterator here instead of
901 // all_referenced_protocol_iterator since we are walking all categories.
902 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
903 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000904 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000905 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000906 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000907 PE = Proto->protocol_end(); P != PE; ++P) {
908 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000909 CollectInheritedProtocols(*P, Protocols);
910 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000911 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000912
913 // Categories of this Interface.
914 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
915 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
916 CollectInheritedProtocols(CDeclChain, Protocols);
917 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
918 while (SD) {
919 CollectInheritedProtocols(SD, Protocols);
920 SD = SD->getSuperClass();
921 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000922 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000923 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000924 PE = OC->protocol_end(); P != PE; ++P) {
925 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000926 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000927 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
928 PE = Proto->protocol_end(); P != PE; ++P)
929 CollectInheritedProtocols(*P, Protocols);
930 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000931 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000932 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
933 PE = OP->protocol_end(); P != PE; ++P) {
934 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000935 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
937 PE = Proto->protocol_end(); P != PE; ++P)
938 CollectInheritedProtocols(*P, Protocols);
939 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000940 }
941}
942
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000943unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
944 unsigned count = 0;
945 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000946 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
947 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000948 count += CDecl->ivar_size();
949
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000950 // Count ivar defined in this class's implementation. This
951 // includes synthesized ivars.
952 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000953 count += ImplDecl->ivar_size();
954
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000955 return count;
956}
957
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000958/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
959ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
960 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
961 I = ObjCImpls.find(D);
962 if (I != ObjCImpls.end())
963 return cast<ObjCImplementationDecl>(I->second);
964 return 0;
965}
966/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
967ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
968 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
969 I = ObjCImpls.find(D);
970 if (I != ObjCImpls.end())
971 return cast<ObjCCategoryImplDecl>(I->second);
972 return 0;
973}
974
975/// \brief Set the implementation of ObjCInterfaceDecl.
976void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
977 ObjCImplementationDecl *ImplD) {
978 assert(IFaceD && ImplD && "Passed null params");
979 ObjCImpls[IFaceD] = ImplD;
980}
981/// \brief Set the implementation of ObjCCategoryDecl.
982void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
983 ObjCCategoryImplDecl *ImplD) {
984 assert(CatD && ImplD && "Passed null params");
985 ObjCImpls[CatD] = ImplD;
986}
987
John McCalla93c9342009-12-07 02:54:59 +0000988/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000989///
John McCalla93c9342009-12-07 02:54:59 +0000990/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000991/// the TypeLoc wrappers.
992///
993/// \param T the type that will be the basis for type source info. This type
994/// should refer to how the declarator was written in source code, not to
995/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000996TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000997 unsigned DataSize) {
998 if (!DataSize)
999 DataSize = TypeLoc::getFullDataSizeForType(T);
1000 else
1001 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001002 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001003
John McCalla93c9342009-12-07 02:54:59 +00001004 TypeSourceInfo *TInfo =
1005 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1006 new (TInfo) TypeSourceInfo(T);
1007 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001008}
1009
John McCalla93c9342009-12-07 02:54:59 +00001010TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001011 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001012 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001013 DI->getTypeLoc().initialize(L);
1014 return DI;
1015}
1016
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001017const ASTRecordLayout &
1018ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1019 return getObjCLayout(D, 0);
1020}
1021
1022const ASTRecordLayout &
1023ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1024 return getObjCLayout(D->getClassInterface(), D);
1025}
1026
Chris Lattnera7674d82007-07-13 22:13:22 +00001027//===----------------------------------------------------------------------===//
1028// Type creation/memoization methods
1029//===----------------------------------------------------------------------===//
1030
John McCall0953e762009-09-24 19:53:00 +00001031QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1032 unsigned Fast = Quals.getFastQualifiers();
1033 Quals.removeFastQualifiers();
1034
1035 // Check if we've already instantiated this type.
1036 llvm::FoldingSetNodeID ID;
1037 ExtQuals::Profile(ID, TypeNode, Quals);
1038 void *InsertPos = 0;
1039 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1040 assert(EQ->getQualifiers() == Quals);
1041 QualType T = QualType(EQ, Fast);
1042 return T;
1043 }
1044
John McCall6b304a02009-09-24 23:30:46 +00001045 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001046 ExtQualNodes.InsertNode(New, InsertPos);
1047 QualType T = QualType(New, Fast);
1048 return T;
1049}
1050
1051QualType ASTContext::getVolatileType(QualType T) {
1052 QualType CanT = getCanonicalType(T);
1053 if (CanT.isVolatileQualified()) return T;
1054
1055 QualifierCollector Quals;
1056 const Type *TypeNode = Quals.strip(T);
1057 Quals.addVolatile();
1058
1059 return getExtQualType(TypeNode, Quals);
1060}
1061
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001062QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001063 QualType CanT = getCanonicalType(T);
1064 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001065 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001066
John McCall0953e762009-09-24 19:53:00 +00001067 // If we are composing extended qualifiers together, merge together
1068 // into one ExtQuals node.
1069 QualifierCollector Quals;
1070 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
John McCall0953e762009-09-24 19:53:00 +00001072 // If this type already has an address space specified, it cannot get
1073 // another one.
1074 assert(!Quals.hasAddressSpace() &&
1075 "Type cannot be in multiple addr spaces!");
1076 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001077
John McCall0953e762009-09-24 19:53:00 +00001078 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001079}
1080
Chris Lattnerb7d25532009-02-18 22:53:11 +00001081QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001082 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001083 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001084 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001085 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001087 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001088 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001089 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001090 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1091 return getPointerType(ResultType);
1092 }
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
John McCall0953e762009-09-24 19:53:00 +00001095 // If we are composing extended qualifiers together, merge together
1096 // into one ExtQuals node.
1097 QualifierCollector Quals;
1098 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001099
John McCall0953e762009-09-24 19:53:00 +00001100 // If this type already has an ObjCGC specified, it cannot get
1101 // another one.
1102 assert(!Quals.hasObjCGCAttr() &&
1103 "Type cannot have multiple ObjCGCs!");
1104 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
John McCall0953e762009-09-24 19:53:00 +00001106 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001107}
Chris Lattnera7674d82007-07-13 22:13:22 +00001108
Rafael Espindola264ba482010-03-30 20:24:48 +00001109static QualType getExtFunctionType(ASTContext& Context, QualType T,
1110 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001111 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001112 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1113 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001114 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001115 if (ResultType == Pointee)
1116 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001117
1118 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001119 } else if (const BlockPointerType *BlockPointer
1120 = T->getAs<BlockPointerType>()) {
1121 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001122 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001123 if (ResultType == Pointee)
1124 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001125
1126 ResultType = Context.getBlockPointerType(ResultType);
Douglas Gregorafac01d2010-09-01 16:29:03 +00001127 } else if (const MemberPointerType *MemberPointer
1128 = T->getAs<MemberPointerType>()) {
1129 QualType Pointee = MemberPointer->getPointeeType();
1130 ResultType = getExtFunctionType(Context, Pointee, Info);
1131 if (ResultType == Pointee)
1132 return T;
1133
1134 ResultType = Context.getMemberPointerType(ResultType,
1135 MemberPointer->getClass());
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001136 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001137 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001138 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001139
Douglas Gregor43c79c22009-12-09 00:47:37 +00001140 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001141 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001142 Info);
John McCall0953e762009-09-24 19:53:00 +00001143 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001144 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001145 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001146 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1147 FPT->getNumArgs(), FPT->isVariadic(),
1148 FPT->getTypeQuals(),
1149 FPT->hasExceptionSpec(),
1150 FPT->hasAnyExceptionSpec(),
1151 FPT->getNumExceptions(),
1152 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001153 Info);
John McCall0953e762009-09-24 19:53:00 +00001154 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001155 } else
1156 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001157
1158 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1159}
1160
1161QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001162 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001163 return getExtFunctionType(*this, T,
1164 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001165}
1166
1167QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001168 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001169 return getExtFunctionType(*this, T,
1170 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001171}
1172
Rafael Espindola425ef722010-03-30 22:15:11 +00001173QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1174 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1175 return getExtFunctionType(*this, T,
1176 Info.withRegParm(RegParm));
1177}
1178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179/// getComplexType - Return the uniqued reference to the type for a complex
1180/// number with the specified element type.
1181QualType ASTContext::getComplexType(QualType T) {
1182 // Unique pointers, to guarantee there is only one pointer of a particular
1183 // structure.
1184 llvm::FoldingSetNodeID ID;
1185 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 void *InsertPos = 0;
1188 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1189 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 // If the pointee type isn't canonical, this won't be a canonical type either,
1192 // so fill in the canonical type field.
1193 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001194 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001195 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 // Get the new insert position for the node we care about.
1198 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001199 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 }
John McCall6b304a02009-09-24 23:30:46 +00001201 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 Types.push_back(New);
1203 ComplexTypes.InsertNode(New, InsertPos);
1204 return QualType(New, 0);
1205}
1206
Reid Spencer5f016e22007-07-11 17:01:13 +00001207/// getPointerType - Return the uniqued reference to the type for a pointer to
1208/// the specified type.
1209QualType ASTContext::getPointerType(QualType T) {
1210 // Unique pointers, to guarantee there is only one pointer of a particular
1211 // structure.
1212 llvm::FoldingSetNodeID ID;
1213 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 void *InsertPos = 0;
1216 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1217 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // If the pointee type isn't canonical, this won't be a canonical type either,
1220 // so fill in the canonical type field.
1221 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001222 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001223 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 // Get the new insert position for the node we care about.
1226 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001227 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 }
John McCall6b304a02009-09-24 23:30:46 +00001229 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 Types.push_back(New);
1231 PointerTypes.InsertNode(New, InsertPos);
1232 return QualType(New, 0);
1233}
1234
Mike Stump1eb44332009-09-09 15:08:12 +00001235/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001236/// a pointer to the specified block.
1237QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001238 assert(T->isFunctionType() && "block of function types only");
1239 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001240 // structure.
1241 llvm::FoldingSetNodeID ID;
1242 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Steve Naroff5618bd42008-08-27 16:04:49 +00001244 void *InsertPos = 0;
1245 if (BlockPointerType *PT =
1246 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1247 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
1249 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001250 // type either so fill in the canonical type field.
1251 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001252 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001253 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Steve Naroff5618bd42008-08-27 16:04:49 +00001255 // Get the new insert position for the node we care about.
1256 BlockPointerType *NewIP =
1257 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001258 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001259 }
John McCall6b304a02009-09-24 23:30:46 +00001260 BlockPointerType *New
1261 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001262 Types.push_back(New);
1263 BlockPointerTypes.InsertNode(New, InsertPos);
1264 return QualType(New, 0);
1265}
1266
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001267/// getLValueReferenceType - Return the uniqued reference to the type for an
1268/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001269QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 // Unique pointers, to guarantee there is only one pointer of a particular
1271 // structure.
1272 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001273 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274
1275 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001276 if (LValueReferenceType *RT =
1277 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001279
John McCall54e14c42009-10-22 22:37:11 +00001280 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // If the referencee type isn't canonical, this won't be a canonical type
1283 // either, so fill in the canonical type field.
1284 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001285 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1286 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1287 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001290 LValueReferenceType *NewIP =
1291 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001292 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 }
1294
John McCall6b304a02009-09-24 23:30:46 +00001295 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001296 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1297 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001299 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001300
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001301 return QualType(New, 0);
1302}
1303
1304/// getRValueReferenceType - Return the uniqued reference to the type for an
1305/// rvalue reference to the specified type.
1306QualType ASTContext::getRValueReferenceType(QualType T) {
1307 // Unique pointers, to guarantee there is only one pointer of a particular
1308 // structure.
1309 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001310 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001311
1312 void *InsertPos = 0;
1313 if (RValueReferenceType *RT =
1314 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1315 return QualType(RT, 0);
1316
John McCall54e14c42009-10-22 22:37:11 +00001317 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1318
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001319 // If the referencee type isn't canonical, this won't be a canonical type
1320 // either, so fill in the canonical type field.
1321 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001322 if (InnerRef || !T.isCanonical()) {
1323 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1324 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001325
1326 // Get the new insert position for the node we care about.
1327 RValueReferenceType *NewIP =
1328 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1329 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1330 }
1331
John McCall6b304a02009-09-24 23:30:46 +00001332 RValueReferenceType *New
1333 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001334 Types.push_back(New);
1335 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 return QualType(New, 0);
1337}
1338
Sebastian Redlf30208a2009-01-24 21:16:55 +00001339/// getMemberPointerType - Return the uniqued reference to the type for a
1340/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001341QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001342 // Unique pointers, to guarantee there is only one pointer of a particular
1343 // structure.
1344 llvm::FoldingSetNodeID ID;
1345 MemberPointerType::Profile(ID, T, Cls);
1346
1347 void *InsertPos = 0;
1348 if (MemberPointerType *PT =
1349 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1350 return QualType(PT, 0);
1351
1352 // If the pointee or class type isn't canonical, this won't be a canonical
1353 // type either, so fill in the canonical type field.
1354 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001355 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001356 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1357
1358 // Get the new insert position for the node we care about.
1359 MemberPointerType *NewIP =
1360 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1361 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1362 }
John McCall6b304a02009-09-24 23:30:46 +00001363 MemberPointerType *New
1364 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001365 Types.push_back(New);
1366 MemberPointerTypes.InsertNode(New, InsertPos);
1367 return QualType(New, 0);
1368}
1369
Mike Stump1eb44332009-09-09 15:08:12 +00001370/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001371/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001372QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001373 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001374 ArrayType::ArraySizeModifier ASM,
1375 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001376 assert((EltTy->isDependentType() ||
1377 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001378 "Constant array of VLAs is illegal!");
1379
Chris Lattner38aeec72009-05-13 04:12:56 +00001380 // Convert the array size into a canonical width matching the pointer size for
1381 // the target.
1382 llvm::APInt ArySize(ArySizeIn);
1383 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001386 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001389 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 // If the element type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
1395 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001396 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001397 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001398 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001400 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001401 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001402 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 }
Mike Stump1eb44332009-09-09 15:08:12 +00001404
John McCall6b304a02009-09-24 23:30:46 +00001405 ConstantArrayType *New = new(*this,TypeAlignment)
1406 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001407 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 Types.push_back(New);
1409 return QualType(New, 0);
1410}
1411
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001412/// getVariableArrayType - Returns a non-unique reference to the type for a
1413/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001414QualType ASTContext::getVariableArrayType(QualType EltTy,
1415 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001416 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001417 unsigned EltTypeQuals,
1418 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001419 // Since we don't unique expressions, it isn't possible to unique VLA's
1420 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001421 QualType CanonType;
1422
1423 if (!EltTy.isCanonical()) {
1424 if (NumElts)
1425 NumElts->Retain();
1426 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1427 EltTypeQuals, Brackets);
1428 }
1429
John McCall6b304a02009-09-24 23:30:46 +00001430 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001431 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001432
1433 VariableArrayTypes.push_back(New);
1434 Types.push_back(New);
1435 return QualType(New, 0);
1436}
1437
Douglas Gregor898574e2008-12-05 23:32:09 +00001438/// getDependentSizedArrayType - Returns a non-unique reference to
1439/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001440/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001441QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1442 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001443 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001444 unsigned EltTypeQuals,
1445 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001446 assert((!NumElts || NumElts->isTypeDependent() ||
1447 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001448 "Size must be type- or value-dependent!");
1449
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001450 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001451 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001452 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001453
1454 if (NumElts) {
1455 // Dependently-sized array types that do not have a specified
1456 // number of elements will have their sizes deduced from an
1457 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001458 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1459 EltTypeQuals, NumElts);
1460
1461 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1462 }
1463
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001464 DependentSizedArrayType *New;
1465 if (Canon) {
1466 // We already have a canonical version of this array type; use it as
1467 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001468 New = new (*this, TypeAlignment)
1469 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1470 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001471 } else {
1472 QualType CanonEltTy = getCanonicalType(EltTy);
1473 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001474 New = new (*this, TypeAlignment)
1475 DependentSizedArrayType(*this, EltTy, QualType(),
1476 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001477
Douglas Gregor789b1f62010-02-04 18:10:26 +00001478 if (NumElts) {
1479 DependentSizedArrayType *CanonCheck
1480 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1481 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1482 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001483 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001484 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001485 } else {
1486 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1487 ASM, EltTypeQuals,
1488 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001489 New = new (*this, TypeAlignment)
1490 DependentSizedArrayType(*this, EltTy, Canon,
1491 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001492 }
1493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Douglas Gregor898574e2008-12-05 23:32:09 +00001495 Types.push_back(New);
1496 return QualType(New, 0);
1497}
1498
Eli Friedmanc5773c42008-02-15 18:16:39 +00001499QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1500 ArrayType::ArraySizeModifier ASM,
1501 unsigned EltTypeQuals) {
1502 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001503 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001504
1505 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001506 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001507 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1508 return QualType(ATP, 0);
1509
1510 // If the element type isn't canonical, this won't be a canonical type
1511 // either, so fill in the canonical type field.
1512 QualType Canonical;
1513
John McCall467b27b2009-10-22 20:10:53 +00001514 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001515 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001516 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001517
1518 // Get the new insert position for the node we care about.
1519 IncompleteArrayType *NewIP =
1520 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001521 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001522 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001523
John McCall6b304a02009-09-24 23:30:46 +00001524 IncompleteArrayType *New = new (*this, TypeAlignment)
1525 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001526
1527 IncompleteArrayTypes.InsertNode(New, InsertPos);
1528 Types.push_back(New);
1529 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001530}
1531
Steve Naroff73322922007-07-18 18:00:27 +00001532/// getVectorType - Return the unique reference to a vector type of
1533/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001534QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001535 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Chris Lattnerf52ab252008-04-06 22:59:24 +00001538 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001539 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 // Check if we've already instantiated a vector of this type.
1542 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001543 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 void *InsertPos = 0;
1546 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1547 return QualType(VTP, 0);
1548
1549 // If the element type isn't canonical, this won't be a canonical type either,
1550 // so fill in the canonical type field.
1551 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001552 if (!vecType.isCanonical()) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00001553 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1554 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // Get the new insert position for the node we care about.
1557 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001558 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 }
John McCall6b304a02009-09-24 23:30:46 +00001560 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001561 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 VectorTypes.InsertNode(New, InsertPos);
1563 Types.push_back(New);
1564 return QualType(New, 0);
1565}
1566
Nate Begeman213541a2008-04-18 23:10:10 +00001567/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001568/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001569QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001570 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Chris Lattnerf52ab252008-04-06 22:59:24 +00001572 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001573 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Steve Naroff73322922007-07-18 18:00:27 +00001575 // Check if we've already instantiated a vector of this type.
1576 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001577 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1578 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001579 void *InsertPos = 0;
1580 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1581 return QualType(VTP, 0);
1582
1583 // If the element type isn't canonical, this won't be a canonical type either,
1584 // so fill in the canonical type field.
1585 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001586 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001587 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Steve Naroff73322922007-07-18 18:00:27 +00001589 // Get the new insert position for the node we care about.
1590 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001591 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001592 }
John McCall6b304a02009-09-24 23:30:46 +00001593 ExtVectorType *New = new (*this, TypeAlignment)
1594 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001595 VectorTypes.InsertNode(New, InsertPos);
1596 Types.push_back(New);
1597 return QualType(New, 0);
1598}
1599
Mike Stump1eb44332009-09-09 15:08:12 +00001600QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001601 Expr *SizeExpr,
1602 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001603 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001604 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001605 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001607 void *InsertPos = 0;
1608 DependentSizedExtVectorType *Canon
1609 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1610 DependentSizedExtVectorType *New;
1611 if (Canon) {
1612 // We already have a canonical version of this array type; use it as
1613 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001614 New = new (*this, TypeAlignment)
1615 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1616 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001617 } else {
1618 QualType CanonVecTy = getCanonicalType(vecType);
1619 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001620 New = new (*this, TypeAlignment)
1621 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1622 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001623
1624 DependentSizedExtVectorType *CanonCheck
1625 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1626 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1627 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001628 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1629 } else {
1630 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1631 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001632 New = new (*this, TypeAlignment)
1633 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001634 }
1635 }
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001637 Types.push_back(New);
1638 return QualType(New, 0);
1639}
1640
Douglas Gregor72564e72009-02-26 23:50:07 +00001641/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001642///
Rafael Espindola264ba482010-03-30 20:24:48 +00001643QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1644 const FunctionType::ExtInfo &Info) {
1645 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // Unique functions, to guarantee there is only one function of a particular
1647 // structure.
1648 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001649 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001652 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001653 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001657 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001658 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001659 Canonical =
1660 getFunctionNoProtoType(getCanonicalType(ResultTy),
1661 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001664 FunctionNoProtoType *NewIP =
1665 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001666 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
John McCall6b304a02009-09-24 23:30:46 +00001669 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001670 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001672 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 return QualType(New, 0);
1674}
1675
1676/// getFunctionType - Return a normal function type with a typed argument
1677/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001678QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001679 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001680 unsigned TypeQuals, bool hasExceptionSpec,
1681 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001682 const QualType *ExArray,
1683 const FunctionType::ExtInfo &Info) {
1684 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // Unique functions, to guarantee there is only one function of a particular
1686 // structure.
1687 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001688 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001689 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001690 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001691
1692 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001693 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001694 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001696
1697 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001698 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001700 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 isCanonical = false;
1702
1703 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001704 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001706 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 llvm::SmallVector<QualType, 16> CanonicalArgs;
1708 CanonicalArgs.reserve(NumArgs);
1709 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001710 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001711
Chris Lattnerf52ab252008-04-06 22:59:24 +00001712 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001713 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001714 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001715 false, 0, 0,
1716 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001717
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001719 FunctionProtoType *NewIP =
1720 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001721 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001723
Douglas Gregor72564e72009-02-26 23:50:07 +00001724 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001725 // for two variable size arrays (for parameter and exception types) at the
1726 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001727 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001728 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1729 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001730 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001731 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001732 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001733 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001735 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 return QualType(FTP, 0);
1737}
1738
John McCall3cb0ebd2010-03-10 03:28:59 +00001739#ifndef NDEBUG
1740static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1741 if (!isa<CXXRecordDecl>(D)) return false;
1742 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1743 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1744 return true;
1745 if (RD->getDescribedClassTemplate() &&
1746 !isa<ClassTemplateSpecializationDecl>(RD))
1747 return true;
1748 return false;
1749}
1750#endif
1751
1752/// getInjectedClassNameType - Return the unique reference to the
1753/// injected class name type for the specified templated declaration.
1754QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1755 QualType TST) {
1756 assert(NeedsInjectedClassNameType(Decl));
1757 if (Decl->TypeForDecl) {
1758 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001759 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001760 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1761 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1762 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1763 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001764 Decl->TypeForDecl =
1765 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001766 Types.push_back(Decl->TypeForDecl);
1767 }
1768 return QualType(Decl->TypeForDecl, 0);
1769}
1770
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001771/// getTypeDeclType - Return the unique reference to the type for the
1772/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001773QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001774 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001775 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001776
John McCall19c85762010-02-16 03:57:14 +00001777 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001778 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001779
John McCallbecb8d52010-03-10 06:48:02 +00001780 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1781 "Template type parameter types are always available.");
1782
John McCall19c85762010-02-16 03:57:14 +00001783 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001784 assert(!Record->getPreviousDeclaration() &&
1785 "struct/union has previous declaration");
1786 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001787 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001788 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001789 assert(!Enum->getPreviousDeclaration() &&
1790 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001791 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001792 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001793 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1794 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001795 } else
John McCallbecb8d52010-03-10 06:48:02 +00001796 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001797
John McCallbecb8d52010-03-10 06:48:02 +00001798 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001799 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001800}
1801
Reid Spencer5f016e22007-07-11 17:01:13 +00001802/// getTypedefType - Return the unique reference to the type for the
1803/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001804QualType
1805ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001808 if (Canonical.isNull())
1809 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001810 Decl->TypeForDecl = new(*this, TypeAlignment)
1811 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 Types.push_back(Decl->TypeForDecl);
1813 return QualType(Decl->TypeForDecl, 0);
1814}
1815
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001816QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1817 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1818
1819 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1820 if (PrevDecl->TypeForDecl)
1821 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1822
1823 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1824 Types.push_back(Decl->TypeForDecl);
1825 return QualType(Decl->TypeForDecl, 0);
1826}
1827
1828QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1829 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1830
1831 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1832 if (PrevDecl->TypeForDecl)
1833 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1834
1835 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1836 Types.push_back(Decl->TypeForDecl);
1837 return QualType(Decl->TypeForDecl, 0);
1838}
1839
John McCall49a832b2009-10-18 09:09:24 +00001840/// \brief Retrieve a substitution-result type.
1841QualType
1842ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1843 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001844 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001845 && "replacement types must always be canonical");
1846
1847 llvm::FoldingSetNodeID ID;
1848 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1849 void *InsertPos = 0;
1850 SubstTemplateTypeParmType *SubstParm
1851 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1852
1853 if (!SubstParm) {
1854 SubstParm = new (*this, TypeAlignment)
1855 SubstTemplateTypeParmType(Parm, Replacement);
1856 Types.push_back(SubstParm);
1857 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1858 }
1859
1860 return QualType(SubstParm, 0);
1861}
1862
Douglas Gregorfab9d672009-02-05 23:33:38 +00001863/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001864/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001865/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001866QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001867 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001868 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001869 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001870 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001871 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001872 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001873 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1874
1875 if (TypeParm)
1876 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Douglas Gregorefed5c82010-06-16 15:23:05 +00001878 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001879 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001880 TypeParm = new (*this, TypeAlignment)
1881 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001882
1883 TemplateTypeParmType *TypeCheck
1884 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1885 assert(!TypeCheck && "Template type parameter canonical type broken");
1886 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001887 } else
John McCall6b304a02009-09-24 23:30:46 +00001888 TypeParm = new (*this, TypeAlignment)
1889 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001890
1891 Types.push_back(TypeParm);
1892 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1893
1894 return QualType(TypeParm, 0);
1895}
1896
John McCall3cb0ebd2010-03-10 03:28:59 +00001897TypeSourceInfo *
1898ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1899 SourceLocation NameLoc,
1900 const TemplateArgumentListInfo &Args,
1901 QualType CanonType) {
1902 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1903
1904 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1905 TemplateSpecializationTypeLoc TL
1906 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1907 TL.setTemplateNameLoc(NameLoc);
1908 TL.setLAngleLoc(Args.getLAngleLoc());
1909 TL.setRAngleLoc(Args.getRAngleLoc());
1910 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1911 TL.setArgLocInfo(i, Args[i].getLocInfo());
1912 return DI;
1913}
1914
Mike Stump1eb44332009-09-09 15:08:12 +00001915QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001916ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001917 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001918 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001919 unsigned NumArgs = Args.size();
1920
John McCall833ca992009-10-29 08:12:44 +00001921 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1922 ArgVec.reserve(NumArgs);
1923 for (unsigned i = 0; i != NumArgs; ++i)
1924 ArgVec.push_back(Args[i].getArgument());
1925
John McCall31f17ec2010-04-27 00:57:59 +00001926 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001927 Canon);
John McCall833ca992009-10-29 08:12:44 +00001928}
1929
1930QualType
1931ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001932 const TemplateArgument *Args,
1933 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001934 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001935 if (!Canon.isNull())
1936 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001937 else
1938 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001939
Douglas Gregor1275ae02009-07-28 23:00:59 +00001940 // Allocate the (non-canonical) template specialization type, but don't
1941 // try to unique it: these types typically have location information that
1942 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001943 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001944 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001945 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001946 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001947 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001948 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001949 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Douglas Gregor55f6b142009-02-09 18:46:07 +00001951 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001952 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001953}
1954
Mike Stump1eb44332009-09-09 15:08:12 +00001955QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001956ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1957 const TemplateArgument *Args,
1958 unsigned NumArgs) {
1959 // Build the canonical template specialization type.
1960 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1961 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1962 CanonArgs.reserve(NumArgs);
1963 for (unsigned I = 0; I != NumArgs; ++I)
1964 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1965
1966 // Determine whether this canonical template specialization type already
1967 // exists.
1968 llvm::FoldingSetNodeID ID;
1969 TemplateSpecializationType::Profile(ID, CanonTemplate,
1970 CanonArgs.data(), NumArgs, *this);
1971
1972 void *InsertPos = 0;
1973 TemplateSpecializationType *Spec
1974 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1975
1976 if (!Spec) {
1977 // Allocate a new canonical template specialization type.
1978 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1979 sizeof(TemplateArgument) * NumArgs),
1980 TypeAlignment);
1981 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1982 CanonArgs.data(), NumArgs,
1983 QualType());
1984 Types.push_back(Spec);
1985 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1986 }
1987
1988 assert(Spec->isDependentType() &&
1989 "Non-dependent template-id type must have a canonical type");
1990 return QualType(Spec, 0);
1991}
1992
1993QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001994ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1995 NestedNameSpecifier *NNS,
1996 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001997 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001998 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001999
2000 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002001 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002002 if (T)
2003 return QualType(T, 0);
2004
Douglas Gregor789b1f62010-02-04 18:10:26 +00002005 QualType Canon = NamedType;
2006 if (!Canon.isCanonical()) {
2007 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002008 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2009 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002010 (void)CheckT;
2011 }
2012
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002013 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002014 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002015 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002016 return QualType(T, 0);
2017}
2018
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002019QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2020 NestedNameSpecifier *NNS,
2021 const IdentifierInfo *Name,
2022 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002023 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2024
2025 if (Canon.isNull()) {
2026 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002027 ElaboratedTypeKeyword CanonKeyword = Keyword;
2028 if (Keyword == ETK_None)
2029 CanonKeyword = ETK_Typename;
2030
2031 if (CanonNNS != NNS || CanonKeyword != Keyword)
2032 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002033 }
2034
2035 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002036 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002037
2038 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002039 DependentNameType *T
2040 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002041 if (T)
2042 return QualType(T, 0);
2043
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002044 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002045 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002046 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002047 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002048}
2049
Mike Stump1eb44332009-09-09 15:08:12 +00002050QualType
John McCall33500952010-06-11 00:33:02 +00002051ASTContext::getDependentTemplateSpecializationType(
2052 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002053 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002054 const IdentifierInfo *Name,
2055 const TemplateArgumentListInfo &Args) {
2056 // TODO: avoid this copy
2057 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2058 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2059 ArgCopy.push_back(Args[I].getArgument());
2060 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2061 ArgCopy.size(),
2062 ArgCopy.data());
2063}
2064
2065QualType
2066ASTContext::getDependentTemplateSpecializationType(
2067 ElaboratedTypeKeyword Keyword,
2068 NestedNameSpecifier *NNS,
2069 const IdentifierInfo *Name,
2070 unsigned NumArgs,
2071 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002072 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2073
Douglas Gregor789b1f62010-02-04 18:10:26 +00002074 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002075 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2076 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002077
2078 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002079 DependentTemplateSpecializationType *T
2080 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002081 if (T)
2082 return QualType(T, 0);
2083
John McCall33500952010-06-11 00:33:02 +00002084 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002085
John McCall33500952010-06-11 00:33:02 +00002086 ElaboratedTypeKeyword CanonKeyword = Keyword;
2087 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2088
2089 bool AnyNonCanonArgs = false;
2090 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2091 for (unsigned I = 0; I != NumArgs; ++I) {
2092 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2093 if (!CanonArgs[I].structurallyEquals(Args[I]))
2094 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002095 }
2096
John McCall33500952010-06-11 00:33:02 +00002097 QualType Canon;
2098 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2099 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2100 Name, NumArgs,
2101 CanonArgs.data());
2102
2103 // Find the insert position again.
2104 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 }
2106
2107 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2108 sizeof(TemplateArgument) * NumArgs),
2109 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002110 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002111 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002112 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002113 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002114 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002115}
2116
Chris Lattner88cb27a2008-04-07 04:56:42 +00002117/// CmpProtocolNames - Comparison predicate for sorting protocols
2118/// alphabetically.
2119static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2120 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002121 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002122}
2123
John McCallc12c5bb2010-05-15 11:32:37 +00002124static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002125 unsigned NumProtocols) {
2126 if (NumProtocols == 0) return true;
2127
2128 for (unsigned i = 1; i != NumProtocols; ++i)
2129 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2130 return false;
2131 return true;
2132}
2133
2134static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002135 unsigned &NumProtocols) {
2136 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Chris Lattner88cb27a2008-04-07 04:56:42 +00002138 // Sort protocols, keyed by name.
2139 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2140
2141 // Remove duplicates.
2142 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2143 NumProtocols = ProtocolsEnd-Protocols;
2144}
2145
John McCallc12c5bb2010-05-15 11:32:37 +00002146QualType ASTContext::getObjCObjectType(QualType BaseType,
2147 ObjCProtocolDecl * const *Protocols,
2148 unsigned NumProtocols) {
2149 // If the base type is an interface and there aren't any protocols
2150 // to add, then the interface type will do just fine.
2151 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2152 return BaseType;
2153
2154 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002155 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002156 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002157 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002158 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2159 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002160
John McCallc12c5bb2010-05-15 11:32:37 +00002161 // Build the canonical type, which has the canonical base type and
2162 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002163 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002164 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2165 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2166 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002167 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2168 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002169 unsigned UniqueCount = NumProtocols;
2170
John McCall54e14c42009-10-22 22:37:11 +00002171 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002172 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2173 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002174 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002175 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2176 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002177 }
2178
2179 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002180 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2181 }
2182
2183 unsigned Size = sizeof(ObjCObjectTypeImpl);
2184 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2185 void *Mem = Allocate(Size, TypeAlignment);
2186 ObjCObjectTypeImpl *T =
2187 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2188
2189 Types.push_back(T);
2190 ObjCObjectTypes.InsertNode(T, InsertPos);
2191 return QualType(T, 0);
2192}
2193
2194/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2195/// the given object type.
2196QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2197 llvm::FoldingSetNodeID ID;
2198 ObjCObjectPointerType::Profile(ID, ObjectT);
2199
2200 void *InsertPos = 0;
2201 if (ObjCObjectPointerType *QT =
2202 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2203 return QualType(QT, 0);
2204
2205 // Find the canonical object type.
2206 QualType Canonical;
2207 if (!ObjectT.isCanonical()) {
2208 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2209
2210 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002211 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2212 }
2213
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002214 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002215 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2216 ObjCObjectPointerType *QType =
2217 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002219 Types.push_back(QType);
2220 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002221 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002222}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002223
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002224/// getObjCInterfaceType - Return the unique reference to the type for the
2225/// specified ObjC interface decl. The list of protocols is optional.
2226QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2227 if (Decl->TypeForDecl)
2228 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002230 // FIXME: redeclarations?
2231 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2232 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2233 Decl->TypeForDecl = T;
2234 Types.push_back(T);
2235 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002236}
2237
Douglas Gregor72564e72009-02-26 23:50:07 +00002238/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2239/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002240/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002241/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002242/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002243QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002244 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002245 if (tofExpr->isTypeDependent()) {
2246 llvm::FoldingSetNodeID ID;
2247 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Douglas Gregorb1975722009-07-30 23:18:24 +00002249 void *InsertPos = 0;
2250 DependentTypeOfExprType *Canon
2251 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2252 if (Canon) {
2253 // We already have a "canonical" version of an identical, dependent
2254 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002255 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002256 QualType((TypeOfExprType*)Canon, 0));
2257 }
2258 else {
2259 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002260 Canon
2261 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002262 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2263 toe = Canon;
2264 }
2265 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002266 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002267 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002268 }
Steve Naroff9752f252007-08-01 18:02:17 +00002269 Types.push_back(toe);
2270 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002271}
2272
Steve Naroff9752f252007-08-01 18:02:17 +00002273/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2274/// TypeOfType AST's. The only motivation to unique these nodes would be
2275/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002276/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002277/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002278QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002279 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002280 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002281 Types.push_back(tot);
2282 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002283}
2284
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002285/// getDecltypeForExpr - Given an expr, will return the decltype for that
2286/// expression, according to the rules in C++0x [dcl.type.simple]p4
2287static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002288 if (e->isTypeDependent())
2289 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002291 // If e is an id expression or a class member access, decltype(e) is defined
2292 // as the type of the entity named by e.
2293 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2294 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2295 return VD->getType();
2296 }
2297 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2298 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2299 return FD->getType();
2300 }
2301 // If e is a function call or an invocation of an overloaded operator,
2302 // (parentheses around e are ignored), decltype(e) is defined as the
2303 // return type of that function.
2304 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2305 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002307 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002308
2309 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002310 // defined as T&, otherwise decltype(e) is defined as T.
2311 if (e->isLvalue(Context) == Expr::LV_Valid)
2312 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002314 return T;
2315}
2316
Anders Carlsson395b4752009-06-24 19:06:50 +00002317/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2318/// DecltypeType AST's. The only motivation to unique these nodes would be
2319/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002320/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002321/// on canonical type's (which are always unique).
2322QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002323 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002324 if (e->isTypeDependent()) {
2325 llvm::FoldingSetNodeID ID;
2326 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002328 void *InsertPos = 0;
2329 DependentDecltypeType *Canon
2330 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2331 if (Canon) {
2332 // We already have a "canonical" version of an equivalent, dependent
2333 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002334 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002335 QualType((DecltypeType*)Canon, 0));
2336 }
2337 else {
2338 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002339 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002340 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2341 dt = Canon;
2342 }
2343 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002344 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002345 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002346 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002347 Types.push_back(dt);
2348 return QualType(dt, 0);
2349}
2350
Reid Spencer5f016e22007-07-11 17:01:13 +00002351/// getTagDeclType - Return the unique reference to the type for the
2352/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002353QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002354 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002355 // FIXME: What is the design on getTagDeclType when it requires casting
2356 // away const? mutable?
2357 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002358}
2359
Mike Stump1eb44332009-09-09 15:08:12 +00002360/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2361/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2362/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002363CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002364 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002365}
2366
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002367/// getSignedWCharType - Return the type of "signed wchar_t".
2368/// Used when in C++, as a GCC extension.
2369QualType ASTContext::getSignedWCharType() const {
2370 // FIXME: derive from "Target" ?
2371 return WCharTy;
2372}
2373
2374/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2375/// Used when in C++, as a GCC extension.
2376QualType ASTContext::getUnsignedWCharType() const {
2377 // FIXME: derive from "Target" ?
2378 return UnsignedIntTy;
2379}
2380
Chris Lattner8b9023b2007-07-13 03:05:23 +00002381/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2382/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2383QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002384 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002385}
2386
Chris Lattnere6327742008-04-02 05:18:44 +00002387//===----------------------------------------------------------------------===//
2388// Type Operators
2389//===----------------------------------------------------------------------===//
2390
John McCall54e14c42009-10-22 22:37:11 +00002391CanQualType ASTContext::getCanonicalParamType(QualType T) {
2392 // Push qualifiers into arrays, and then discard any remaining
2393 // qualifiers.
2394 T = getCanonicalType(T);
2395 const Type *Ty = T.getTypePtr();
2396
2397 QualType Result;
2398 if (isa<ArrayType>(Ty)) {
2399 Result = getArrayDecayedType(QualType(Ty,0));
2400 } else if (isa<FunctionType>(Ty)) {
2401 Result = getPointerType(QualType(Ty, 0));
2402 } else {
2403 Result = QualType(Ty, 0);
2404 }
2405
2406 return CanQualType::CreateUnsafe(Result);
2407}
2408
Chris Lattner77c96472008-04-06 22:41:35 +00002409/// getCanonicalType - Return the canonical (structural) type corresponding to
2410/// the specified potentially non-canonical type. The non-canonical version
2411/// of a type may have many "decorated" versions of types. Decorators can
2412/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2413/// to be free of any of these, allowing two canonical types to be compared
2414/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002415CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002416 QualifierCollector Quals;
2417 const Type *Ptr = Quals.strip(T);
2418 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002419
John McCall0953e762009-09-24 19:53:00 +00002420 // The canonical internal type will be the canonical type *except*
2421 // that we push type qualifiers down through array types.
2422
2423 // If there are no new qualifiers to push down, stop here.
2424 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002425 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002426
John McCall0953e762009-09-24 19:53:00 +00002427 // If the type qualifiers are on an array type, get the canonical
2428 // type of the array with the qualifiers applied to the element
2429 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002430 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2431 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002432 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002434 // Get the canonical version of the element with the extra qualifiers on it.
2435 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002436 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002437 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002439 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002440 return CanQualType::CreateUnsafe(
2441 getConstantArrayType(NewEltTy, CAT->getSize(),
2442 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002443 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002444 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002445 return CanQualType::CreateUnsafe(
2446 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002447 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregor898574e2008-12-05 23:32:09 +00002449 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002450 return CanQualType::CreateUnsafe(
2451 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002452 DSAT->getSizeExpr() ?
2453 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002454 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002455 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002456 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002457
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002458 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002459 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002460 VAT->getSizeExpr() ?
2461 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002462 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002463 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002464 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002465}
2466
Chandler Carruth28e318c2009-12-29 07:16:59 +00002467QualType ASTContext::getUnqualifiedArrayType(QualType T,
2468 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002469 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002470 const ArrayType *AT = getAsArrayType(T);
2471 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002472 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002473 }
2474
Chandler Carruth28e318c2009-12-29 07:16:59 +00002475 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002476 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002477 if (Elt == UnqualElt)
2478 return T;
2479
Douglas Gregor9dadd942010-05-17 18:45:21 +00002480 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002481 return getConstantArrayType(UnqualElt, CAT->getSize(),
2482 CAT->getSizeModifier(), 0);
2483 }
2484
Douglas Gregor9dadd942010-05-17 18:45:21 +00002485 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002486 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2487 }
2488
Douglas Gregor9dadd942010-05-17 18:45:21 +00002489 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2490 return getVariableArrayType(UnqualElt,
2491 VAT->getSizeExpr() ?
2492 VAT->getSizeExpr()->Retain() : 0,
2493 VAT->getSizeModifier(),
2494 VAT->getIndexTypeCVRQualifiers(),
2495 VAT->getBracketsRange());
2496 }
2497
2498 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002499 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2500 DSAT->getSizeModifier(), 0,
2501 SourceRange());
2502}
2503
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002504/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2505/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2506/// they point to and return true. If T1 and T2 aren't pointer types
2507/// or pointer-to-member types, or if they are not similar at this
2508/// level, returns false and leaves T1 and T2 unchanged. Top-level
2509/// qualifiers on T1 and T2 are ignored. This function will typically
2510/// be called in a loop that successively "unwraps" pointer and
2511/// pointer-to-member types to compare them at each level.
2512bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2513 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2514 *T2PtrType = T2->getAs<PointerType>();
2515 if (T1PtrType && T2PtrType) {
2516 T1 = T1PtrType->getPointeeType();
2517 T2 = T2PtrType->getPointeeType();
2518 return true;
2519 }
2520
2521 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2522 *T2MPType = T2->getAs<MemberPointerType>();
2523 if (T1MPType && T2MPType &&
2524 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2525 QualType(T2MPType->getClass(), 0))) {
2526 T1 = T1MPType->getPointeeType();
2527 T2 = T2MPType->getPointeeType();
2528 return true;
2529 }
2530
2531 if (getLangOptions().ObjC1) {
2532 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2533 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2534 if (T1OPType && T2OPType) {
2535 T1 = T1OPType->getPointeeType();
2536 T2 = T2OPType->getPointeeType();
2537 return true;
2538 }
2539 }
2540
2541 // FIXME: Block pointers, too?
2542
2543 return false;
2544}
2545
Abramo Bagnara25777432010-08-11 22:01:17 +00002546DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2547 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002548 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002549 // DNInfo work in progress: CHECKME: what about DNLoc?
2550 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2551
John McCall80ad16f2009-11-24 18:42:40 +00002552 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002553 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002554 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002555 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2556 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002557 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002558 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2559 // DNInfo work in progress: FIXME: source locations?
2560 DeclarationNameLoc DNLoc;
2561 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2562 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2563 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002564 }
2565 }
2566
John McCall0bd6feb2009-12-02 08:04:21 +00002567 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2568 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002569 // DNInfo work in progress: CHECKME: what about DNLoc?
2570 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002571}
2572
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002573TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002574 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2575 if (TemplateTemplateParmDecl *TTP
2576 = dyn_cast<TemplateTemplateParmDecl>(Template))
2577 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2578
2579 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002580 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002581 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002582
John McCall0bd6feb2009-12-02 08:04:21 +00002583 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002585 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2586 assert(DTN && "Non-dependent template names must refer to template decls.");
2587 return DTN->CanonicalTemplateName;
2588}
2589
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002590bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2591 X = getCanonicalTemplateName(X);
2592 Y = getCanonicalTemplateName(Y);
2593 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2594}
2595
Mike Stump1eb44332009-09-09 15:08:12 +00002596TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002597ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2598 switch (Arg.getKind()) {
2599 case TemplateArgument::Null:
2600 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Douglas Gregor1275ae02009-07-28 23:00:59 +00002602 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002603 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Douglas Gregor1275ae02009-07-28 23:00:59 +00002605 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002606 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Douglas Gregor788cd062009-11-11 01:00:40 +00002608 case TemplateArgument::Template:
2609 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2610
Douglas Gregor1275ae02009-07-28 23:00:59 +00002611 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002612 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002613 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002614
Douglas Gregor1275ae02009-07-28 23:00:59 +00002615 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002616 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Douglas Gregor1275ae02009-07-28 23:00:59 +00002618 case TemplateArgument::Pack: {
2619 // FIXME: Allocate in ASTContext
2620 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2621 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002622 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002623 AEnd = Arg.pack_end();
2624 A != AEnd; (void)++A, ++Idx)
2625 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Douglas Gregor1275ae02009-07-28 23:00:59 +00002627 TemplateArgument Result;
2628 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2629 return Result;
2630 }
2631 }
2632
2633 // Silence GCC warning
2634 assert(false && "Unhandled template argument kind");
2635 return TemplateArgument();
2636}
2637
Douglas Gregord57959a2009-03-27 23:10:48 +00002638NestedNameSpecifier *
2639ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002640 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002641 return 0;
2642
2643 switch (NNS->getKind()) {
2644 case NestedNameSpecifier::Identifier:
2645 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002646 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002647 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2648 NNS->getAsIdentifier());
2649
2650 case NestedNameSpecifier::Namespace:
2651 // A namespace is canonical; build a nested-name-specifier with
2652 // this namespace and no prefix.
2653 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2654
2655 case NestedNameSpecifier::TypeSpec:
2656 case NestedNameSpecifier::TypeSpecWithTemplate: {
2657 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002658 return NestedNameSpecifier::Create(*this, 0,
2659 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002660 T.getTypePtr());
2661 }
2662
2663 case NestedNameSpecifier::Global:
2664 // The global specifier is canonical and unique.
2665 return NNS;
2666 }
2667
2668 // Required to silence a GCC warning
2669 return 0;
2670}
2671
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002672
2673const ArrayType *ASTContext::getAsArrayType(QualType T) {
2674 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002675 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002676 // Handle the common positive case fast.
2677 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2678 return AT;
2679 }
Mike Stump1eb44332009-09-09 15:08:12 +00002680
John McCall0953e762009-09-24 19:53:00 +00002681 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002682 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002683 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002684 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002685
John McCall0953e762009-09-24 19:53:00 +00002686 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002687 // implements C99 6.7.3p8: "If the specification of an array type includes
2688 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002690 // If we get here, we either have type qualifiers on the type, or we have
2691 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002692 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002693
John McCall0953e762009-09-24 19:53:00 +00002694 QualifierCollector Qs;
2695 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002697 // If we have a simple case, just return now.
2698 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002699 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002700 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002702 // Otherwise, we have an array and we have qualifiers on it. Push the
2703 // qualifiers into the array element type and return a new array type.
2704 // Get the canonical version of the element with the extra qualifiers on it.
2705 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002706 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002708 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2709 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2710 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002711 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002712 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2713 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2714 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002715 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002716
Mike Stump1eb44332009-09-09 15:08:12 +00002717 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002718 = dyn_cast<DependentSizedArrayType>(ATy))
2719 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002720 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002721 DSAT->getSizeExpr() ?
2722 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002723 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002724 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002725 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002727 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002728 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002729 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002730 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002731 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002732 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002733 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002734}
2735
2736
Chris Lattnere6327742008-04-02 05:18:44 +00002737/// getArrayDecayedType - Return the properly qualified result of decaying the
2738/// specified array type to a pointer. This operation is non-trivial when
2739/// handling typedefs etc. The canonical type of "T" must be an array type,
2740/// this returns a pointer to a properly qualified element of the array.
2741///
2742/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2743QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002744 // Get the element type with 'getAsArrayType' so that we don't lose any
2745 // typedefs in the element type of the array. This also handles propagation
2746 // of type qualifiers from the array type into the element type if present
2747 // (C99 6.7.3p8).
2748 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2749 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002751 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002752
2753 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002754 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002755}
2756
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002757QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002758 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002759 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2760 QT = AT->getElementType();
2761 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002762}
2763
Anders Carlssonfbbce492009-09-25 01:23:32 +00002764QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2765 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Anders Carlssonfbbce492009-09-25 01:23:32 +00002767 if (const ArrayType *AT = getAsArrayType(ElemTy))
2768 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002769
Anders Carlsson6183a992008-12-21 03:44:36 +00002770 return ElemTy;
2771}
2772
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002773/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002774uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002775ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2776 uint64_t ElementCount = 1;
2777 do {
2778 ElementCount *= CA->getSize().getZExtValue();
2779 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2780 } while (CA);
2781 return ElementCount;
2782}
2783
Reid Spencer5f016e22007-07-11 17:01:13 +00002784/// getFloatingRank - Return a relative rank for floating point types.
2785/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002786static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002787 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002789
John McCall183700f2009-09-21 23:43:11 +00002790 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2791 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002792 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 case BuiltinType::Float: return FloatRank;
2794 case BuiltinType::Double: return DoubleRank;
2795 case BuiltinType::LongDouble: return LongDoubleRank;
2796 }
2797}
2798
Mike Stump1eb44332009-09-09 15:08:12 +00002799/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2800/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002801/// 'typeDomain' is a real floating point or complex type.
2802/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002803QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2804 QualType Domain) const {
2805 FloatingRank EltRank = getFloatingRank(Size);
2806 if (Domain->isComplexType()) {
2807 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002808 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002809 case FloatRank: return FloatComplexTy;
2810 case DoubleRank: return DoubleComplexTy;
2811 case LongDoubleRank: return LongDoubleComplexTy;
2812 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 }
Chris Lattner1361b112008-04-06 23:58:54 +00002814
2815 assert(Domain->isRealFloatingType() && "Unknown domain!");
2816 switch (EltRank) {
2817 default: assert(0 && "getFloatingRank(): illegal value for rank");
2818 case FloatRank: return FloatTy;
2819 case DoubleRank: return DoubleTy;
2820 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002821 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002822}
2823
Chris Lattner7cfeb082008-04-06 23:55:33 +00002824/// getFloatingTypeOrder - Compare the rank of the two specified floating
2825/// point types, ignoring the domain of the type (i.e. 'double' ==
2826/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002827/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002828int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2829 FloatingRank LHSR = getFloatingRank(LHS);
2830 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Chris Lattnera75cea32008-04-06 23:38:49 +00002832 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002833 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002834 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002835 return 1;
2836 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002837}
2838
Chris Lattnerf52ab252008-04-06 22:59:24 +00002839/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2840/// routine will assert if passed a built-in type that isn't an integer or enum,
2841/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002842unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002843 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002844 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002845 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002846
Eli Friedmana3426752009-07-05 23:44:27 +00002847 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2848 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2849
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002850 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2851 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2852
2853 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2854 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2855
Chris Lattnerf52ab252008-04-06 22:59:24 +00002856 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002857 default: assert(0 && "getIntegerRank(): not a built-in integer");
2858 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002859 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002860 case BuiltinType::Char_S:
2861 case BuiltinType::Char_U:
2862 case BuiltinType::SChar:
2863 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002864 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002865 case BuiltinType::Short:
2866 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002867 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002868 case BuiltinType::Int:
2869 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002870 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002871 case BuiltinType::Long:
2872 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002873 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002874 case BuiltinType::LongLong:
2875 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002876 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002877 case BuiltinType::Int128:
2878 case BuiltinType::UInt128:
2879 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002880 }
2881}
2882
Eli Friedman04e83572009-08-20 04:21:42 +00002883/// \brief Whether this is a promotable bitfield reference according
2884/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2885///
2886/// \returns the type this bit-field will promote to, or NULL if no
2887/// promotion occurs.
2888QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002889 if (E->isTypeDependent() || E->isValueDependent())
2890 return QualType();
2891
Eli Friedman04e83572009-08-20 04:21:42 +00002892 FieldDecl *Field = E->getBitField();
2893 if (!Field)
2894 return QualType();
2895
2896 QualType FT = Field->getType();
2897
2898 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2899 uint64_t BitWidth = BitWidthAP.getZExtValue();
2900 uint64_t IntSize = getTypeSize(IntTy);
2901 // GCC extension compatibility: if the bit-field size is less than or equal
2902 // to the size of int, it gets promoted no matter what its type is.
2903 // For instance, unsigned long bf : 4 gets promoted to signed int.
2904 if (BitWidth < IntSize)
2905 return IntTy;
2906
2907 if (BitWidth == IntSize)
2908 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2909
2910 // Types bigger than int are not subject to promotions, and therefore act
2911 // like the base type.
2912 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2913 // is ridiculous.
2914 return QualType();
2915}
2916
Eli Friedmana95d7572009-08-19 07:44:53 +00002917/// getPromotedIntegerType - Returns the type that Promotable will
2918/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2919/// integer type.
2920QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2921 assert(!Promotable.isNull());
2922 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002923 if (const EnumType *ET = Promotable->getAs<EnumType>())
2924 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002925 if (Promotable->isSignedIntegerType())
2926 return IntTy;
2927 uint64_t PromotableSize = getTypeSize(Promotable);
2928 uint64_t IntSize = getTypeSize(IntTy);
2929 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2930 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2931}
2932
Mike Stump1eb44332009-09-09 15:08:12 +00002933/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002934/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002935/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002936int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002937 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2938 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002939 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Chris Lattnerf52ab252008-04-06 22:59:24 +00002941 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2942 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Chris Lattner7cfeb082008-04-06 23:55:33 +00002944 unsigned LHSRank = getIntegerRank(LHSC);
2945 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Chris Lattner7cfeb082008-04-06 23:55:33 +00002947 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2948 if (LHSRank == RHSRank) return 0;
2949 return LHSRank > RHSRank ? 1 : -1;
2950 }
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Chris Lattner7cfeb082008-04-06 23:55:33 +00002952 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2953 if (LHSUnsigned) {
2954 // If the unsigned [LHS] type is larger, return it.
2955 if (LHSRank >= RHSRank)
2956 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Chris Lattner7cfeb082008-04-06 23:55:33 +00002958 // If the signed type can represent all values of the unsigned type, it
2959 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002960 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002961 return -1;
2962 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002963
Chris Lattner7cfeb082008-04-06 23:55:33 +00002964 // If the unsigned [RHS] type is larger, return it.
2965 if (RHSRank >= LHSRank)
2966 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Chris Lattner7cfeb082008-04-06 23:55:33 +00002968 // If the signed type can represent all values of the unsigned type, it
2969 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002970 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002971 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002972}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002973
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002974static RecordDecl *
2975CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2976 SourceLocation L, IdentifierInfo *Id) {
2977 if (Ctx.getLangOptions().CPlusPlus)
2978 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2979 else
2980 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2981}
2982
Mike Stump1eb44332009-09-09 15:08:12 +00002983// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002984QualType ASTContext::getCFConstantStringType() {
2985 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002986 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002987 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002988 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002989 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002990
Anders Carlssonf06273f2007-11-19 00:25:30 +00002991 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Anders Carlsson71993dd2007-08-17 05:31:46 +00002993 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002994 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002995 // int flags;
2996 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002997 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002998 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002999 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003000 FieldTypes[3] = LongTy;
3001
Anders Carlsson71993dd2007-08-17 05:31:46 +00003002 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003003 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003004 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003005 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003006 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003007 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003008 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003009 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003010 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003011 }
3012
Douglas Gregor838db382010-02-11 01:19:42 +00003013 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003014 }
Mike Stump1eb44332009-09-09 15:08:12 +00003015
Anders Carlsson71993dd2007-08-17 05:31:46 +00003016 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003017}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003018
Douglas Gregor319ac892009-04-23 22:29:11 +00003019void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003020 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003021 assert(Rec && "Invalid CFConstantStringType");
3022 CFConstantStringTypeDecl = Rec->getDecl();
3023}
3024
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003025// getNSConstantStringType - Return the type used for constant NSStrings.
3026QualType ASTContext::getNSConstantStringType() {
3027 if (!NSConstantStringTypeDecl) {
3028 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003029 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003030 &Idents.get("__builtin_NSString"));
3031 NSConstantStringTypeDecl->startDefinition();
3032
3033 QualType FieldTypes[3];
3034
3035 // const int *isa;
3036 FieldTypes[0] = getPointerType(IntTy.withConst());
3037 // const char *str;
3038 FieldTypes[1] = getPointerType(CharTy.withConst());
3039 // unsigned int length;
3040 FieldTypes[2] = UnsignedIntTy;
3041
3042 // Create fields
3043 for (unsigned i = 0; i < 3; ++i) {
3044 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3045 SourceLocation(), 0,
3046 FieldTypes[i], /*TInfo=*/0,
3047 /*BitWidth=*/0,
3048 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003049 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003050 NSConstantStringTypeDecl->addDecl(Field);
3051 }
3052
3053 NSConstantStringTypeDecl->completeDefinition();
3054 }
3055
3056 return getTagDeclType(NSConstantStringTypeDecl);
3057}
3058
3059void ASTContext::setNSConstantStringType(QualType T) {
3060 const RecordType *Rec = T->getAs<RecordType>();
3061 assert(Rec && "Invalid NSConstantStringType");
3062 NSConstantStringTypeDecl = Rec->getDecl();
3063}
3064
Mike Stump1eb44332009-09-09 15:08:12 +00003065QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003066 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003067 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003068 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003069 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003070 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003072 QualType FieldTypes[] = {
3073 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003074 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003075 getPointerType(UnsignedLongTy),
3076 getConstantArrayType(UnsignedLongTy,
3077 llvm::APInt(32, 5), ArrayType::Normal, 0)
3078 };
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Douglas Gregor44b43212008-12-11 16:49:14 +00003080 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003081 FieldDecl *Field = FieldDecl::Create(*this,
3082 ObjCFastEnumerationStateTypeDecl,
3083 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003084 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003085 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003086 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003087 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003088 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003089 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003090 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003091 if (CXXRecordDecl *CXXRD =
3092 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003093 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Douglas Gregor838db382010-02-11 01:19:42 +00003095 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003096 }
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003098 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3099}
3100
Mike Stumpadaaad32009-10-20 02:12:22 +00003101QualType ASTContext::getBlockDescriptorType() {
3102 if (BlockDescriptorType)
3103 return getTagDeclType(BlockDescriptorType);
3104
3105 RecordDecl *T;
3106 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003107 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003108 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003109 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003110
3111 QualType FieldTypes[] = {
3112 UnsignedLongTy,
3113 UnsignedLongTy,
3114 };
3115
3116 const char *FieldNames[] = {
3117 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003118 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003119 };
3120
3121 for (size_t i = 0; i < 2; ++i) {
3122 FieldDecl *Field = FieldDecl::Create(*this,
3123 T,
3124 SourceLocation(),
3125 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003126 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003127 /*BitWidth=*/0,
3128 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003129 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003130 T->addDecl(Field);
3131 }
3132
Douglas Gregor838db382010-02-11 01:19:42 +00003133 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003134
3135 BlockDescriptorType = T;
3136
3137 return getTagDeclType(BlockDescriptorType);
3138}
3139
3140void ASTContext::setBlockDescriptorType(QualType T) {
3141 const RecordType *Rec = T->getAs<RecordType>();
3142 assert(Rec && "Invalid BlockDescriptorType");
3143 BlockDescriptorType = Rec->getDecl();
3144}
3145
Mike Stump083c25e2009-10-22 00:49:09 +00003146QualType ASTContext::getBlockDescriptorExtendedType() {
3147 if (BlockDescriptorExtendedType)
3148 return getTagDeclType(BlockDescriptorExtendedType);
3149
3150 RecordDecl *T;
3151 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003152 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003153 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003154 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003155
3156 QualType FieldTypes[] = {
3157 UnsignedLongTy,
3158 UnsignedLongTy,
3159 getPointerType(VoidPtrTy),
3160 getPointerType(VoidPtrTy)
3161 };
3162
3163 const char *FieldNames[] = {
3164 "reserved",
3165 "Size",
3166 "CopyFuncPtr",
3167 "DestroyFuncPtr"
3168 };
3169
3170 for (size_t i = 0; i < 4; ++i) {
3171 FieldDecl *Field = FieldDecl::Create(*this,
3172 T,
3173 SourceLocation(),
3174 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003175 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003176 /*BitWidth=*/0,
3177 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003178 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003179 T->addDecl(Field);
3180 }
3181
Douglas Gregor838db382010-02-11 01:19:42 +00003182 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003183
3184 BlockDescriptorExtendedType = T;
3185
3186 return getTagDeclType(BlockDescriptorExtendedType);
3187}
3188
3189void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3190 const RecordType *Rec = T->getAs<RecordType>();
3191 assert(Rec && "Invalid BlockDescriptorType");
3192 BlockDescriptorExtendedType = Rec->getDecl();
3193}
3194
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003195bool ASTContext::BlockRequiresCopying(QualType Ty) {
3196 if (Ty->isBlockPointerType())
3197 return true;
3198 if (isObjCNSObjectType(Ty))
3199 return true;
3200 if (Ty->isObjCObjectPointerType())
3201 return true;
3202 return false;
3203}
3204
Daniel Dunbar4087f272010-08-17 22:39:59 +00003205QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003206 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003207 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003208 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003209 // unsigned int __flags;
3210 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003211 // void *__copy_helper; // as needed
3212 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003213 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003214 // } *
3215
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003216 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3217
3218 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003219 llvm::SmallString<36> Name;
3220 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3221 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003222 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003223 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003224 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003225 T->startDefinition();
3226 QualType Int32Ty = IntTy;
3227 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3228 QualType FieldTypes[] = {
3229 getPointerType(VoidPtrTy),
3230 getPointerType(getTagDeclType(T)),
3231 Int32Ty,
3232 Int32Ty,
3233 getPointerType(VoidPtrTy),
3234 getPointerType(VoidPtrTy),
3235 Ty
3236 };
3237
Daniel Dunbar4087f272010-08-17 22:39:59 +00003238 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003239 "__isa",
3240 "__forwarding",
3241 "__flags",
3242 "__size",
3243 "__copy_helper",
3244 "__destroy_helper",
3245 DeclName,
3246 };
3247
3248 for (size_t i = 0; i < 7; ++i) {
3249 if (!HasCopyAndDispose && i >=4 && i <= 5)
3250 continue;
3251 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3252 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003253 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003254 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003255 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003256 T->addDecl(Field);
3257 }
3258
Douglas Gregor838db382010-02-11 01:19:42 +00003259 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003260
3261 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003262}
3263
3264
3265QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003266 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003267 llvm::SmallVectorImpl<const Expr *> &Layout) {
3268
Mike Stumpadaaad32009-10-20 02:12:22 +00003269 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003270 llvm::SmallString<36> Name;
3271 llvm::raw_svector_ostream(Name) << "__block_literal_"
3272 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003273 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003274 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003275 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003276 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003277 QualType FieldTypes[] = {
3278 getPointerType(VoidPtrTy),
3279 IntTy,
3280 IntTy,
3281 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003282 (BlockHasCopyDispose ?
3283 getPointerType(getBlockDescriptorExtendedType()) :
3284 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003285 };
3286
3287 const char *FieldNames[] = {
3288 "__isa",
3289 "__flags",
3290 "__reserved",
3291 "__FuncPtr",
3292 "__descriptor"
3293 };
3294
3295 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003296 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003297 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003298 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003299 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003300 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003301 T->addDecl(Field);
3302 }
3303
John McCallea1471e2010-05-20 01:18:31 +00003304 for (unsigned i = 0; i < Layout.size(); ++i) {
3305 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003306
John McCallea1471e2010-05-20 01:18:31 +00003307 QualType FieldType = E->getType();
3308 IdentifierInfo *FieldName = 0;
3309 if (isa<CXXThisExpr>(E)) {
3310 FieldName = &Idents.get("this");
3311 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3312 const ValueDecl *D = BDRE->getDecl();
3313 FieldName = D->getIdentifier();
3314 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003315 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003316 } else {
3317 // Padding.
3318 assert(isa<ConstantArrayType>(FieldType) &&
3319 isa<DeclRefExpr>(E) &&
3320 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3321 "doesn't match characteristics of padding decl");
3322 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003323
3324 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003325 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003326 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003327 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003328 T->addDecl(Field);
3329 }
3330
Douglas Gregor838db382010-02-11 01:19:42 +00003331 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003332
3333 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003334}
3335
Douglas Gregor319ac892009-04-23 22:29:11 +00003336void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003337 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003338 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3339 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3340}
3341
Anders Carlssone8c49532007-10-29 06:33:42 +00003342// This returns true if a type has been typedefed to BOOL:
3343// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003344static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003345 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003346 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3347 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003349 return false;
3350}
3351
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003352/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003353/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003354CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003355 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003357 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003358 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003359 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003360 // Treat arrays as pointers, since that's how they're passed in.
3361 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003362 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003363 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003364}
3365
3366static inline
3367std::string charUnitsToString(const CharUnits &CU) {
3368 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003369}
3370
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003371/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003372/// declaration.
3373void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3374 std::string& S) {
3375 const BlockDecl *Decl = Expr->getBlockDecl();
3376 QualType BlockTy =
3377 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3378 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003379 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003380 // Compute size of all parameters.
3381 // Start with computing size of a pointer in number of bytes.
3382 // FIXME: There might(should) be a better way of doing this computation!
3383 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003384 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3385 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003386 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003387 E = Decl->param_end(); PI != E; ++PI) {
3388 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003389 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003390 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003391 ParmOffset += sz;
3392 }
3393 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003394 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003395 // Block pointer and offset.
3396 S += "@?0";
3397 ParmOffset = PtrSize;
3398
3399 // Argument types.
3400 ParmOffset = PtrSize;
3401 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3402 Decl->param_end(); PI != E; ++PI) {
3403 ParmVarDecl *PVDecl = *PI;
3404 QualType PType = PVDecl->getOriginalType();
3405 if (const ArrayType *AT =
3406 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3407 // Use array's original type only if it has known number of
3408 // elements.
3409 if (!isa<ConstantArrayType>(AT))
3410 PType = PVDecl->getType();
3411 } else if (PType->isFunctionType())
3412 PType = PVDecl->getType();
3413 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003414 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003415 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003416 }
3417}
3418
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003419/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003420/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003421void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003422 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003423 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003424 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003425 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003426 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003427 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003428 // Compute size of all parameters.
3429 // Start with computing size of a pointer in number of bytes.
3430 // FIXME: There might(should) be a better way of doing this computation!
3431 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003432 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003433 // The first two arguments (self and _cmd) are pointers; account for
3434 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003435 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003436 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003437 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003438 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003439 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003440 assert (sz.isPositive() &&
3441 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003442 ParmOffset += sz;
3443 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003444 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003445 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003446 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003448 // Argument types.
3449 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003450 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003451 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003452 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003453 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003454 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003455 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3456 // Use array's original type only if it has known number of
3457 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003458 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003459 PType = PVDecl->getType();
3460 } else if (PType->isFunctionType())
3461 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003462 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003463 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003464 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003465 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003466 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003467 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003468 }
3469}
3470
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003471/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003472/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003473/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3474/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003475/// Property attributes are stored as a comma-delimited C string. The simple
3476/// attributes readonly and bycopy are encoded as single characters. The
3477/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3478/// encoded as single characters, followed by an identifier. Property types
3479/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003480/// these attributes are defined by the following enumeration:
3481/// @code
3482/// enum PropertyAttributes {
3483/// kPropertyReadOnly = 'R', // property is read-only.
3484/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3485/// kPropertyByref = '&', // property is a reference to the value last assigned
3486/// kPropertyDynamic = 'D', // property is dynamic
3487/// kPropertyGetter = 'G', // followed by getter selector name
3488/// kPropertySetter = 'S', // followed by setter selector name
3489/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3490/// kPropertyType = 't' // followed by old-style type encoding.
3491/// kPropertyWeak = 'W' // 'weak' property
3492/// kPropertyStrong = 'P' // property GC'able
3493/// kPropertyNonAtomic = 'N' // property non-atomic
3494/// };
3495/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003496void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003497 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003498 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003499 // Collect information from the property implementation decl(s).
3500 bool Dynamic = false;
3501 ObjCPropertyImplDecl *SynthesizePID = 0;
3502
3503 // FIXME: Duplicated code due to poor abstraction.
3504 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003505 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003506 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3507 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003508 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003509 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003510 ObjCPropertyImplDecl *PID = *i;
3511 if (PID->getPropertyDecl() == PD) {
3512 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3513 Dynamic = true;
3514 } else {
3515 SynthesizePID = PID;
3516 }
3517 }
3518 }
3519 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003520 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003521 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003522 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003523 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003524 ObjCPropertyImplDecl *PID = *i;
3525 if (PID->getPropertyDecl() == PD) {
3526 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3527 Dynamic = true;
3528 } else {
3529 SynthesizePID = PID;
3530 }
3531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003533 }
3534 }
3535
3536 // FIXME: This is not very efficient.
3537 S = "T";
3538
3539 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003540 // GCC has some special rules regarding encoding of properties which
3541 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003542 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003543 true /* outermost type */,
3544 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003545
3546 if (PD->isReadOnly()) {
3547 S += ",R";
3548 } else {
3549 switch (PD->getSetterKind()) {
3550 case ObjCPropertyDecl::Assign: break;
3551 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003552 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003553 }
3554 }
3555
3556 // It really isn't clear at all what this means, since properties
3557 // are "dynamic by default".
3558 if (Dynamic)
3559 S += ",D";
3560
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003561 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3562 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003564 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3565 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003566 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003567 }
3568
3569 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3570 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003571 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003572 }
3573
3574 if (SynthesizePID) {
3575 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3576 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003577 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003578 }
3579
3580 // FIXME: OBJCGC: weak & strong
3581}
3582
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003583/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003584/// Another legacy compatibility encoding: 32-bit longs are encoded as
3585/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003586/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3587///
3588void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003589 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003590 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003591 if (BT->getKind() == BuiltinType::ULong &&
3592 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003593 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003594 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003595 if (BT->getKind() == BuiltinType::Long &&
3596 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003597 PointeeTy = IntTy;
3598 }
3599 }
3600}
3601
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003602void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003603 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003604 // We follow the behavior of gcc, expanding structures which are
3605 // directly pointed to, and expanding embedded structures. Note that
3606 // these rules are sufficient to prevent recursive encoding of the
3607 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003608 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003609 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003610}
3611
David Chisnall64fd7e82010-06-04 01:10:52 +00003612static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3613 switch (T->getAs<BuiltinType>()->getKind()) {
3614 default: assert(0 && "Unhandled builtin type kind");
3615 case BuiltinType::Void: return 'v';
3616 case BuiltinType::Bool: return 'B';
3617 case BuiltinType::Char_U:
3618 case BuiltinType::UChar: return 'C';
3619 case BuiltinType::UShort: return 'S';
3620 case BuiltinType::UInt: return 'I';
3621 case BuiltinType::ULong:
3622 return
3623 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3624 case BuiltinType::UInt128: return 'T';
3625 case BuiltinType::ULongLong: return 'Q';
3626 case BuiltinType::Char_S:
3627 case BuiltinType::SChar: return 'c';
3628 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003629 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003630 case BuiltinType::Int: return 'i';
3631 case BuiltinType::Long:
3632 return
3633 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3634 case BuiltinType::LongLong: return 'q';
3635 case BuiltinType::Int128: return 't';
3636 case BuiltinType::Float: return 'f';
3637 case BuiltinType::Double: return 'd';
3638 case BuiltinType::LongDouble: return 'd';
3639 }
3640}
3641
Mike Stump1eb44332009-09-09 15:08:12 +00003642static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003643 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003644 const Expr *E = FD->getBitWidth();
3645 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3646 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003647 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003648 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3649 // The GNU runtime requires more information; bitfields are encoded as b,
3650 // then the offset (in bits) of the first element, then the type of the
3651 // bitfield, then the size in bits. For example, in this structure:
3652 //
3653 // struct
3654 // {
3655 // int integer;
3656 // int flags:2;
3657 // };
3658 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3659 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3660 // information is not especially sensible, but we're stuck with it for
3661 // compatibility with GCC, although providing it breaks anything that
3662 // actually uses runtime introspection and wants to work on both runtimes...
3663 if (!Ctx->getLangOptions().NeXTRuntime) {
3664 const RecordDecl *RD = FD->getParent();
3665 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3666 // FIXME: This same linear search is also used in ExprConstant - it might
3667 // be better if the FieldDecl stored its offset. We'd be increasing the
3668 // size of the object slightly, but saving some time every time it is used.
3669 unsigned i = 0;
3670 for (RecordDecl::field_iterator Field = RD->field_begin(),
3671 FieldEnd = RD->field_end();
3672 Field != FieldEnd; (void)++Field, ++i) {
3673 if (*Field == FD)
3674 break;
3675 }
3676 S += llvm::utostr(RL.getFieldOffset(i));
3677 S += ObjCEncodingForPrimitiveKind(Context, T);
3678 }
3679 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003680 S += llvm::utostr(N);
3681}
3682
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003683// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003684void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3685 bool ExpandPointedToStructures,
3686 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003687 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003688 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003689 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003690 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003691 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003692 return EncodeBitField(this, S, T, FD);
3693 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003694 return;
3695 }
Mike Stump1eb44332009-09-09 15:08:12 +00003696
John McCall183700f2009-09-21 23:43:11 +00003697 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003698 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003699 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003700 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003701 return;
3702 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003703
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003704 // encoding for pointer or r3eference types.
3705 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003706 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003707 if (PT->isObjCSelType()) {
3708 S += ':';
3709 return;
3710 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003711 PointeeTy = PT->getPointeeType();
3712 }
3713 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3714 PointeeTy = RT->getPointeeType();
3715 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003716 bool isReadOnly = false;
3717 // For historical/compatibility reasons, the read-only qualifier of the
3718 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3719 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003720 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003721 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003722 if (OutermostType && T.isConstQualified()) {
3723 isReadOnly = true;
3724 S += 'r';
3725 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003726 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003727 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003728 while (P->getAs<PointerType>())
3729 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003730 if (P.isConstQualified()) {
3731 isReadOnly = true;
3732 S += 'r';
3733 }
3734 }
3735 if (isReadOnly) {
3736 // Another legacy compatibility encoding. Some ObjC qualifier and type
3737 // combinations need to be rearranged.
3738 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003739 if (llvm::StringRef(S).endswith("nr"))
3740 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003743 if (PointeeTy->isCharType()) {
3744 // char pointer types should be encoded as '*' unless it is a
3745 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003746 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003747 S += '*';
3748 return;
3749 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003750 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003751 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3752 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3753 S += '#';
3754 return;
3755 }
3756 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3757 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3758 S += '@';
3759 return;
3760 }
3761 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003762 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003763 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003764 getLegacyIntegralTypeEncoding(PointeeTy);
3765
Mike Stump1eb44332009-09-09 15:08:12 +00003766 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003767 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003768 return;
3769 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003770
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003771 if (const ArrayType *AT =
3772 // Ignore type qualifiers etc.
3773 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003774 if (isa<IncompleteArrayType>(AT)) {
3775 // Incomplete arrays are encoded as a pointer to the array element.
3776 S += '^';
3777
Mike Stump1eb44332009-09-09 15:08:12 +00003778 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003779 false, ExpandStructures, FD);
3780 } else {
3781 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Anders Carlsson559a8332009-02-22 01:38:57 +00003783 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3784 S += llvm::utostr(CAT->getSize().getZExtValue());
3785 else {
3786 //Variable length arrays are encoded as a regular array with 0 elements.
3787 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3788 S += '0';
3789 }
Mike Stump1eb44332009-09-09 15:08:12 +00003790
3791 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003792 false, ExpandStructures, FD);
3793 S += ']';
3794 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003795 return;
3796 }
Mike Stump1eb44332009-09-09 15:08:12 +00003797
John McCall183700f2009-09-21 23:43:11 +00003798 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003799 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003800 return;
3801 }
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Ted Kremenek6217b802009-07-29 21:53:49 +00003803 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003804 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003805 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003806 // Anonymous structures print as '?'
3807 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3808 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003809 if (ClassTemplateSpecializationDecl *Spec
3810 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3811 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3812 std::string TemplateArgsStr
3813 = TemplateSpecializationType::PrintTemplateArgumentList(
3814 TemplateArgs.getFlatArgumentList(),
3815 TemplateArgs.flat_size(),
3816 (*this).PrintingPolicy);
3817
3818 S += TemplateArgsStr;
3819 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003820 } else {
3821 S += '?';
3822 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003823 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003824 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003825 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3826 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003827 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003828 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003829 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003830 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003831 S += '"';
3832 }
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003834 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003835 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003836 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003837 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003838 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003839 QualType qt = Field->getType();
3840 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003841 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003842 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003843 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003844 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003845 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003846 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003847 return;
3848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003850 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003851 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003852 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003853 else
3854 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003855 return;
3856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003858 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003859 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003860 return;
3861 }
Mike Stump1eb44332009-09-09 15:08:12 +00003862
John McCallc12c5bb2010-05-15 11:32:37 +00003863 // Ignore protocol qualifiers when mangling at this level.
3864 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3865 T = OT->getBaseType();
3866
John McCall0953e762009-09-24 19:53:00 +00003867 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003868 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003869 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003870 S += '{';
3871 const IdentifierInfo *II = OI->getIdentifier();
3872 S += II->getName();
3873 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003874 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3875 DeepCollectObjCIvars(OI, true, Ivars);
3876 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3877 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3878 if (Field->isBitField())
3879 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003880 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003881 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003882 }
3883 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003884 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003885 }
Mike Stump1eb44332009-09-09 15:08:12 +00003886
John McCall183700f2009-09-21 23:43:11 +00003887 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003888 if (OPT->isObjCIdType()) {
3889 S += '@';
3890 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003891 }
Mike Stump1eb44332009-09-09 15:08:12 +00003892
Steve Naroff27d20a22009-10-28 22:03:49 +00003893 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3894 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3895 // Since this is a binary compatibility issue, need to consult with runtime
3896 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003897 S += '#';
3898 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003901 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003902 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003903 ExpandPointedToStructures,
3904 ExpandStructures, FD);
3905 if (FD || EncodingProperty) {
3906 // Note that we do extended encoding of protocol qualifer list
3907 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003908 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003909 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3910 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003911 S += '<';
3912 S += (*I)->getNameAsString();
3913 S += '>';
3914 }
3915 S += '"';
3916 }
3917 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003920 QualType PointeeTy = OPT->getPointeeType();
3921 if (!EncodingProperty &&
3922 isa<TypedefType>(PointeeTy.getTypePtr())) {
3923 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003924 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003925 // {...};
3926 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003927 getObjCEncodingForTypeImpl(PointeeTy, S,
3928 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003929 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003930 return;
3931 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003932
3933 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003934 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003935 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003936 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003937 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3938 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003939 S += '<';
3940 S += (*I)->getNameAsString();
3941 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003942 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003943 S += '"';
3944 }
3945 return;
3946 }
Mike Stump1eb44332009-09-09 15:08:12 +00003947
John McCall532ec7b2010-05-17 23:56:34 +00003948 // gcc just blithely ignores member pointers.
3949 // TODO: maybe there should be a mangling for these
3950 if (T->getAs<MemberPointerType>())
3951 return;
3952
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003953 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003954}
3955
Mike Stump1eb44332009-09-09 15:08:12 +00003956void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003957 std::string& S) const {
3958 if (QT & Decl::OBJC_TQ_In)
3959 S += 'n';
3960 if (QT & Decl::OBJC_TQ_Inout)
3961 S += 'N';
3962 if (QT & Decl::OBJC_TQ_Out)
3963 S += 'o';
3964 if (QT & Decl::OBJC_TQ_Bycopy)
3965 S += 'O';
3966 if (QT & Decl::OBJC_TQ_Byref)
3967 S += 'R';
3968 if (QT & Decl::OBJC_TQ_Oneway)
3969 S += 'V';
3970}
3971
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003972void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003973 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003974
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003975 BuiltinVaListType = T;
3976}
3977
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003978void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003979 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003980}
3981
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003982void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003983 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003984}
3985
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003986void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003987 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003988}
3989
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003990void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003991 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003992}
3993
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003994void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003995 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003996 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003998 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003999}
4000
John McCall0bd6feb2009-12-02 08:04:21 +00004001/// \brief Retrieve the template name that corresponds to a non-empty
4002/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004003TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4004 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004005 unsigned size = End - Begin;
4006 assert(size > 1 && "set is not overloaded!");
4007
4008 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4009 size * sizeof(FunctionTemplateDecl*));
4010 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4011
4012 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004013 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004014 NamedDecl *D = *I;
4015 assert(isa<FunctionTemplateDecl>(D) ||
4016 (isa<UsingShadowDecl>(D) &&
4017 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4018 *Storage++ = D;
4019 }
4020
4021 return TemplateName(OT);
4022}
4023
Douglas Gregor7532dc62009-03-30 22:58:21 +00004024/// \brief Retrieve the template name that represents a qualified
4025/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004026TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004027 bool TemplateKeyword,
4028 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004029 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004030 llvm::FoldingSetNodeID ID;
4031 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4032
4033 void *InsertPos = 0;
4034 QualifiedTemplateName *QTN =
4035 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4036 if (!QTN) {
4037 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4038 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4039 }
4040
4041 return TemplateName(QTN);
4042}
4043
4044/// \brief Retrieve the template name that represents a dependent
4045/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004046TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004047 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004048 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004049 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004050
4051 llvm::FoldingSetNodeID ID;
4052 DependentTemplateName::Profile(ID, NNS, Name);
4053
4054 void *InsertPos = 0;
4055 DependentTemplateName *QTN =
4056 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4057
4058 if (QTN)
4059 return TemplateName(QTN);
4060
4061 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4062 if (CanonNNS == NNS) {
4063 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4064 } else {
4065 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4066 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004067 DependentTemplateName *CheckQTN =
4068 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4069 assert(!CheckQTN && "Dependent type name canonicalization broken");
4070 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004071 }
4072
4073 DependentTemplateNames.InsertNode(QTN, InsertPos);
4074 return TemplateName(QTN);
4075}
4076
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004077/// \brief Retrieve the template name that represents a dependent
4078/// template name such as \c MetaFun::template operator+.
4079TemplateName
4080ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4081 OverloadedOperatorKind Operator) {
4082 assert((!NNS || NNS->isDependent()) &&
4083 "Nested name specifier must be dependent");
4084
4085 llvm::FoldingSetNodeID ID;
4086 DependentTemplateName::Profile(ID, NNS, Operator);
4087
4088 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004089 DependentTemplateName *QTN
4090 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004091
4092 if (QTN)
4093 return TemplateName(QTN);
4094
4095 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4096 if (CanonNNS == NNS) {
4097 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4098 } else {
4099 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4100 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004101
4102 DependentTemplateName *CheckQTN
4103 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4104 assert(!CheckQTN && "Dependent template name canonicalization broken");
4105 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004106 }
4107
4108 DependentTemplateNames.InsertNode(QTN, InsertPos);
4109 return TemplateName(QTN);
4110}
4111
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004112/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004113/// TargetInfo, produce the corresponding type. The unsigned @p Type
4114/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004115CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004116 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004117 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004118 case TargetInfo::SignedShort: return ShortTy;
4119 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4120 case TargetInfo::SignedInt: return IntTy;
4121 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4122 case TargetInfo::SignedLong: return LongTy;
4123 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4124 case TargetInfo::SignedLongLong: return LongLongTy;
4125 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4126 }
4127
4128 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004129 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004130}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004131
4132//===----------------------------------------------------------------------===//
4133// Type Predicates.
4134//===----------------------------------------------------------------------===//
4135
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004136/// isObjCNSObjectType - Return true if this is an NSObject object using
4137/// NSObject attribute on a c-style pointer type.
4138/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004139/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004140///
4141bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4142 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4143 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004144 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004145 return true;
4146 }
Mike Stump1eb44332009-09-09 15:08:12 +00004147 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004148}
4149
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004150/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4151/// garbage collection attribute.
4152///
John McCall0953e762009-09-24 19:53:00 +00004153Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4154 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004155 if (getLangOptions().ObjC1 &&
4156 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004157 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004158 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004159 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004160 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004161 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004162 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004163 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004164 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004165 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004166 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004167 // Non-pointers have none gc'able attribute regardless of the attribute
4168 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004169 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004170 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004171 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004172 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004173}
4174
Chris Lattner6ac46a42008-04-07 06:51:04 +00004175//===----------------------------------------------------------------------===//
4176// Type Compatibility Testing
4177//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004178
Mike Stump1eb44332009-09-09 15:08:12 +00004179/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004180/// compatible.
4181static bool areCompatVectorTypes(const VectorType *LHS,
4182 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004183 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004184 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004185 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004186}
4187
Douglas Gregor255210e2010-08-06 10:14:59 +00004188bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4189 QualType SecondVec) {
4190 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4191 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4192
4193 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4194 return true;
4195
4196 // AltiVec vectors types are identical to equivalent GCC vector types
4197 const VectorType *First = FirstVec->getAs<VectorType>();
4198 const VectorType *Second = SecondVec->getAs<VectorType>();
4199 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4200 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4201 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4202 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4203 hasSameType(First->getElementType(), Second->getElementType()) &&
4204 (First->getNumElements() == Second->getNumElements()))
4205 return true;
4206
4207 return false;
4208}
4209
Steve Naroff4084c302009-07-23 01:01:38 +00004210//===----------------------------------------------------------------------===//
4211// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4212//===----------------------------------------------------------------------===//
4213
4214/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4215/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004216bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4217 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004218 if (lProto == rProto)
4219 return true;
4220 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4221 E = rProto->protocol_end(); PI != E; ++PI)
4222 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4223 return true;
4224 return false;
4225}
4226
Steve Naroff4084c302009-07-23 01:01:38 +00004227/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4228/// return true if lhs's protocols conform to rhs's protocol; false
4229/// otherwise.
4230bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4231 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4232 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4233 return false;
4234}
4235
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004236/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4237/// Class<p1, ...>.
4238bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4239 QualType rhs) {
4240 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4241 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4242 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4243
4244 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4245 E = lhsQID->qual_end(); I != E; ++I) {
4246 bool match = false;
4247 ObjCProtocolDecl *lhsProto = *I;
4248 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4249 E = rhsOPT->qual_end(); J != E; ++J) {
4250 ObjCProtocolDecl *rhsProto = *J;
4251 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4252 match = true;
4253 break;
4254 }
4255 }
4256 if (!match)
4257 return false;
4258 }
4259 return true;
4260}
4261
Steve Naroff4084c302009-07-23 01:01:38 +00004262/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4263/// ObjCQualifiedIDType.
4264bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4265 bool compare) {
4266 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004267 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004268 lhs->isObjCIdType() || lhs->isObjCClassType())
4269 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004270 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004271 rhs->isObjCIdType() || rhs->isObjCClassType())
4272 return true;
4273
4274 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004275 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Steve Naroff4084c302009-07-23 01:01:38 +00004277 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004278
Steve Naroff4084c302009-07-23 01:01:38 +00004279 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004280 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004281 // make sure we check the class hierarchy.
4282 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4283 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4284 E = lhsQID->qual_end(); I != E; ++I) {
4285 // when comparing an id<P> on lhs with a static type on rhs,
4286 // see if static class implements all of id's protocols, directly or
4287 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004288 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004289 return false;
4290 }
4291 }
4292 // If there are no qualifiers and no interface, we have an 'id'.
4293 return true;
4294 }
Mike Stump1eb44332009-09-09 15:08:12 +00004295 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004296 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4297 E = lhsQID->qual_end(); I != E; ++I) {
4298 ObjCProtocolDecl *lhsProto = *I;
4299 bool match = false;
4300
4301 // when comparing an id<P> on lhs with a static type on rhs,
4302 // see if static class implements all of id's protocols, directly or
4303 // through its super class and categories.
4304 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4305 E = rhsOPT->qual_end(); J != E; ++J) {
4306 ObjCProtocolDecl *rhsProto = *J;
4307 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4308 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4309 match = true;
4310 break;
4311 }
4312 }
Mike Stump1eb44332009-09-09 15:08:12 +00004313 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004314 // make sure we check the class hierarchy.
4315 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4316 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4317 E = lhsQID->qual_end(); I != E; ++I) {
4318 // when comparing an id<P> on lhs with a static type on rhs,
4319 // see if static class implements all of id's protocols, directly or
4320 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004321 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004322 match = true;
4323 break;
4324 }
4325 }
4326 }
4327 if (!match)
4328 return false;
4329 }
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Steve Naroff4084c302009-07-23 01:01:38 +00004331 return true;
4332 }
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Steve Naroff4084c302009-07-23 01:01:38 +00004334 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4335 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4336
Mike Stump1eb44332009-09-09 15:08:12 +00004337 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004338 lhs->getAsObjCInterfacePointerType()) {
4339 if (lhsOPT->qual_empty()) {
4340 bool match = false;
4341 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4342 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4343 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004344 // when comparing an id<P> on rhs with a static type on lhs,
4345 // static class must implement all of id's protocols directly or
4346 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004347 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004348 match = true;
4349 break;
4350 }
4351 }
4352 if (!match)
4353 return false;
4354 }
4355 return true;
4356 }
Mike Stump1eb44332009-09-09 15:08:12 +00004357 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004358 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4359 E = lhsOPT->qual_end(); I != E; ++I) {
4360 ObjCProtocolDecl *lhsProto = *I;
4361 bool match = false;
4362
4363 // when comparing an id<P> on lhs with a static type on rhs,
4364 // see if static class implements all of id's protocols, directly or
4365 // through its super class and categories.
4366 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4367 E = rhsQID->qual_end(); J != E; ++J) {
4368 ObjCProtocolDecl *rhsProto = *J;
4369 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4370 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4371 match = true;
4372 break;
4373 }
4374 }
4375 if (!match)
4376 return false;
4377 }
4378 return true;
4379 }
4380 return false;
4381}
4382
Eli Friedman3d815e72008-08-22 00:56:42 +00004383/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004384/// compatible for assignment from RHS to LHS. This handles validation of any
4385/// protocol qualifiers on the LHS or RHS.
4386///
Steve Naroff14108da2009-07-10 23:34:53 +00004387bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4388 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004389 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4390 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4391
Steve Naroffde2e22d2009-07-15 18:40:39 +00004392 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004393 if (LHS->isObjCUnqualifiedIdOrClass() ||
4394 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004395 return true;
4396
John McCallc12c5bb2010-05-15 11:32:37 +00004397 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004398 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4399 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004400 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004401
4402 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4403 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4404 QualType(RHSOPT,0));
4405
John McCallc12c5bb2010-05-15 11:32:37 +00004406 // If we have 2 user-defined types, fall into that path.
4407 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004408 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004409
Steve Naroff4084c302009-07-23 01:01:38 +00004410 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004411}
4412
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004413/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4414/// for providing type-safty for objective-c pointers used to pass/return
4415/// arguments in block literals. When passed as arguments, passing 'A*' where
4416/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4417/// not OK. For the return type, the opposite is not OK.
4418bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4419 const ObjCObjectPointerType *LHSOPT,
4420 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004421 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004422 return true;
4423
4424 if (LHSOPT->isObjCBuiltinType()) {
4425 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4426 }
4427
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004428 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004429 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4430 QualType(RHSOPT,0),
4431 false);
4432
4433 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4434 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4435 if (LHS && RHS) { // We have 2 user-defined types.
4436 if (LHS != RHS) {
4437 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4438 return false;
4439 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4440 return true;
4441 }
4442 else
4443 return true;
4444 }
4445 return false;
4446}
4447
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004448/// getIntersectionOfProtocols - This routine finds the intersection of set
4449/// of protocols inherited from two distinct objective-c pointer objects.
4450/// It is used to build composite qualifier list of the composite type of
4451/// the conditional expression involving two objective-c pointer objects.
4452static
4453void getIntersectionOfProtocols(ASTContext &Context,
4454 const ObjCObjectPointerType *LHSOPT,
4455 const ObjCObjectPointerType *RHSOPT,
4456 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4457
John McCallc12c5bb2010-05-15 11:32:37 +00004458 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4459 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4460 assert(LHS->getInterface() && "LHS must have an interface base");
4461 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004462
4463 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4464 unsigned LHSNumProtocols = LHS->getNumProtocols();
4465 if (LHSNumProtocols > 0)
4466 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4467 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004468 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004469 Context.CollectInheritedProtocols(LHS->getInterface(),
4470 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004471 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4472 LHSInheritedProtocols.end());
4473 }
4474
4475 unsigned RHSNumProtocols = RHS->getNumProtocols();
4476 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004477 ObjCProtocolDecl **RHSProtocols =
4478 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004479 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4480 if (InheritedProtocolSet.count(RHSProtocols[i]))
4481 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4482 }
4483 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004484 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004485 Context.CollectInheritedProtocols(RHS->getInterface(),
4486 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004487 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4488 RHSInheritedProtocols.begin(),
4489 E = RHSInheritedProtocols.end(); I != E; ++I)
4490 if (InheritedProtocolSet.count((*I)))
4491 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004492 }
4493}
4494
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004495/// areCommonBaseCompatible - Returns common base class of the two classes if
4496/// one found. Note that this is O'2 algorithm. But it will be called as the
4497/// last type comparison in a ?-exp of ObjC pointer types before a
4498/// warning is issued. So, its invokation is extremely rare.
4499QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004500 const ObjCObjectPointerType *Lptr,
4501 const ObjCObjectPointerType *Rptr) {
4502 const ObjCObjectType *LHS = Lptr->getObjectType();
4503 const ObjCObjectType *RHS = Rptr->getObjectType();
4504 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4505 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4506 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004507 return QualType();
4508
John McCallc12c5bb2010-05-15 11:32:37 +00004509 while ((LDecl = LDecl->getSuperClass())) {
4510 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004511 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004512 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4513 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4514
4515 QualType Result = QualType(LHS, 0);
4516 if (!Protocols.empty())
4517 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4518 Result = getObjCObjectPointerType(Result);
4519 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004520 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004521 }
4522
4523 return QualType();
4524}
4525
John McCallc12c5bb2010-05-15 11:32:37 +00004526bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4527 const ObjCObjectType *RHS) {
4528 assert(LHS->getInterface() && "LHS is not an interface type");
4529 assert(RHS->getInterface() && "RHS is not an interface type");
4530
Chris Lattner6ac46a42008-04-07 06:51:04 +00004531 // Verify that the base decls are compatible: the RHS must be a subclass of
4532 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004533 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004534 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Chris Lattner6ac46a42008-04-07 06:51:04 +00004536 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4537 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004538 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004539 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004540
Chris Lattner6ac46a42008-04-07 06:51:04 +00004541 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4542 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004543 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004544 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004545
John McCallc12c5bb2010-05-15 11:32:37 +00004546 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4547 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004548 LHSPI != LHSPE; LHSPI++) {
4549 bool RHSImplementsProtocol = false;
4550
4551 // If the RHS doesn't implement the protocol on the left, the types
4552 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004553 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4554 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004555 RHSPI != RHSPE; RHSPI++) {
4556 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004557 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004558 break;
4559 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004560 }
4561 // FIXME: For better diagnostics, consider passing back the protocol name.
4562 if (!RHSImplementsProtocol)
4563 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004564 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004565 // The RHS implements all protocols listed on the LHS.
4566 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004567}
4568
Steve Naroff389bf462009-02-12 17:52:19 +00004569bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4570 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004571 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4572 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004573
Steve Naroff14108da2009-07-10 23:34:53 +00004574 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004575 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004576
4577 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4578 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004579}
4580
Douglas Gregor569c3162010-08-07 11:51:51 +00004581bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4582 return canAssignObjCInterfaces(
4583 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4584 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4585}
4586
Mike Stump1eb44332009-09-09 15:08:12 +00004587/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004588/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004589/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004590/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004591bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4592 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004593 if (getLangOptions().CPlusPlus)
4594 return hasSameType(LHS, RHS);
4595
Douglas Gregor447234d2010-07-29 15:18:02 +00004596 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004597}
4598
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004599bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4600 return !mergeTypes(LHS, RHS, true).isNull();
4601}
4602
4603QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004604 bool OfBlockPointer,
4605 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004606 const FunctionType *lbase = lhs->getAs<FunctionType>();
4607 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004608 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4609 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004610 bool allLTypes = true;
4611 bool allRTypes = true;
4612
4613 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004614 QualType retType;
4615 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004616 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4617 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004618 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004619 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4620 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004621 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004622
4623 if (Unqualified)
4624 retType = retType.getUnqualifiedType();
4625
4626 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4627 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4628 if (Unqualified) {
4629 LRetType = LRetType.getUnqualifiedType();
4630 RRetType = RRetType.getUnqualifiedType();
4631 }
4632
4633 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004634 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004635 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004636 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004637 // FIXME: double check this
4638 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4639 // rbase->getRegParmAttr() != 0 &&
4640 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004641 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4642 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004643 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4644 lbaseInfo.getRegParm();
4645 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4646 if (NoReturn != lbaseInfo.getNoReturn() ||
4647 RegParm != lbaseInfo.getRegParm())
4648 allLTypes = false;
4649 if (NoReturn != rbaseInfo.getNoReturn() ||
4650 RegParm != rbaseInfo.getRegParm())
4651 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004652 CallingConv lcc = lbaseInfo.getCC();
4653 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004654 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004655 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004656 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Eli Friedman3d815e72008-08-22 00:56:42 +00004658 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004659 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4660 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004661 unsigned lproto_nargs = lproto->getNumArgs();
4662 unsigned rproto_nargs = rproto->getNumArgs();
4663
4664 // Compatible functions must have the same number of arguments
4665 if (lproto_nargs != rproto_nargs)
4666 return QualType();
4667
4668 // Variadic and non-variadic functions aren't compatible
4669 if (lproto->isVariadic() != rproto->isVariadic())
4670 return QualType();
4671
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004672 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4673 return QualType();
4674
Eli Friedman3d815e72008-08-22 00:56:42 +00004675 // Check argument compatibility
4676 llvm::SmallVector<QualType, 10> types;
4677 for (unsigned i = 0; i < lproto_nargs; i++) {
4678 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4679 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004680 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4681 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004682 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004683
4684 if (Unqualified)
4685 argtype = argtype.getUnqualifiedType();
4686
Eli Friedman3d815e72008-08-22 00:56:42 +00004687 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004688 if (Unqualified) {
4689 largtype = largtype.getUnqualifiedType();
4690 rargtype = rargtype.getUnqualifiedType();
4691 }
4692
Chris Lattner61710852008-10-05 17:34:18 +00004693 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4694 allLTypes = false;
4695 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4696 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004697 }
4698 if (allLTypes) return lhs;
4699 if (allRTypes) return rhs;
4700 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004701 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004702 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004703 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004704 }
4705
4706 if (lproto) allRTypes = false;
4707 if (rproto) allLTypes = false;
4708
Douglas Gregor72564e72009-02-26 23:50:07 +00004709 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004710 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004711 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004712 if (proto->isVariadic()) return QualType();
4713 // Check that the types are compatible with the types that
4714 // would result from default argument promotions (C99 6.7.5.3p15).
4715 // The only types actually affected are promotable integer
4716 // types and floats, which would be passed as a different
4717 // type depending on whether the prototype is visible.
4718 unsigned proto_nargs = proto->getNumArgs();
4719 for (unsigned i = 0; i < proto_nargs; ++i) {
4720 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004721
4722 // Look at the promotion type of enum types, since that is the type used
4723 // to pass enum values.
4724 if (const EnumType *Enum = argTy->getAs<EnumType>())
4725 argTy = Enum->getDecl()->getPromotionType();
4726
Eli Friedman3d815e72008-08-22 00:56:42 +00004727 if (argTy->isPromotableIntegerType() ||
4728 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4729 return QualType();
4730 }
4731
4732 if (allLTypes) return lhs;
4733 if (allRTypes) return rhs;
4734 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004735 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004736 proto->getTypeQuals(),
4737 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004738 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004739 }
4740
4741 if (allLTypes) return lhs;
4742 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004743 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004744 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004745}
4746
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004747QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004748 bool OfBlockPointer,
4749 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004750 // C++ [expr]: If an expression initially has the type "reference to T", the
4751 // type is adjusted to "T" prior to any further analysis, the expression
4752 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004753 // expression is an lvalue unless the reference is an rvalue reference and
4754 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004755 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4756 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004757
4758 if (Unqualified) {
4759 LHS = LHS.getUnqualifiedType();
4760 RHS = RHS.getUnqualifiedType();
4761 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004762
Eli Friedman3d815e72008-08-22 00:56:42 +00004763 QualType LHSCan = getCanonicalType(LHS),
4764 RHSCan = getCanonicalType(RHS);
4765
4766 // If two types are identical, they are compatible.
4767 if (LHSCan == RHSCan)
4768 return LHS;
4769
John McCall0953e762009-09-24 19:53:00 +00004770 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004771 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4772 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004773 if (LQuals != RQuals) {
4774 // If any of these qualifiers are different, we have a type
4775 // mismatch.
4776 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4777 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4778 return QualType();
4779
4780 // Exactly one GC qualifier difference is allowed: __strong is
4781 // okay if the other type has no GC qualifier but is an Objective
4782 // C object pointer (i.e. implicitly strong by default). We fix
4783 // this by pretending that the unqualified type was actually
4784 // qualified __strong.
4785 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4786 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4787 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4788
4789 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4790 return QualType();
4791
4792 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4793 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4794 }
4795 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4796 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4797 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004798 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004799 }
4800
4801 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004802
Eli Friedman852d63b2009-06-01 01:22:52 +00004803 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4804 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004805
Chris Lattner1adb8832008-01-14 05:45:46 +00004806 // We want to consider the two function types to be the same for these
4807 // comparisons, just force one to the other.
4808 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4809 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004810
4811 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004812 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4813 LHSClass = Type::ConstantArray;
4814 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4815 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004816
John McCallc12c5bb2010-05-15 11:32:37 +00004817 // ObjCInterfaces are just specialized ObjCObjects.
4818 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4819 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4820
Nate Begeman213541a2008-04-18 23:10:10 +00004821 // Canonicalize ExtVector -> Vector.
4822 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4823 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004824
Chris Lattnera36a61f2008-04-07 05:43:21 +00004825 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004826 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004827 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004828 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004829 // Compatibility is based on the underlying type, not the promotion
4830 // type.
John McCall183700f2009-09-21 23:43:11 +00004831 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004832 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4833 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004834 }
John McCall183700f2009-09-21 23:43:11 +00004835 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004836 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4837 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004838 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004839
Eli Friedman3d815e72008-08-22 00:56:42 +00004840 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004841 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004842
Steve Naroff4a746782008-01-09 22:43:08 +00004843 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004844 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004845#define TYPE(Class, Base)
4846#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004847#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004848#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4849#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4850#include "clang/AST/TypeNodes.def"
4851 assert(false && "Non-canonical and dependent types shouldn't get here");
4852 return QualType();
4853
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004854 case Type::LValueReference:
4855 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004856 case Type::MemberPointer:
4857 assert(false && "C++ should never be in mergeTypes");
4858 return QualType();
4859
John McCallc12c5bb2010-05-15 11:32:37 +00004860 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004861 case Type::IncompleteArray:
4862 case Type::VariableArray:
4863 case Type::FunctionProto:
4864 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004865 assert(false && "Types are eliminated above");
4866 return QualType();
4867
Chris Lattner1adb8832008-01-14 05:45:46 +00004868 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004869 {
4870 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004871 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4872 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004873 if (Unqualified) {
4874 LHSPointee = LHSPointee.getUnqualifiedType();
4875 RHSPointee = RHSPointee.getUnqualifiedType();
4876 }
4877 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4878 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004879 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004880 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004881 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004882 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004883 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004884 return getPointerType(ResultType);
4885 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004886 case Type::BlockPointer:
4887 {
4888 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004889 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4890 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004891 if (Unqualified) {
4892 LHSPointee = LHSPointee.getUnqualifiedType();
4893 RHSPointee = RHSPointee.getUnqualifiedType();
4894 }
4895 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4896 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004897 if (ResultType.isNull()) return QualType();
4898 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4899 return LHS;
4900 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4901 return RHS;
4902 return getBlockPointerType(ResultType);
4903 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004904 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004905 {
4906 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4907 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4908 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4909 return QualType();
4910
4911 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4912 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004913 if (Unqualified) {
4914 LHSElem = LHSElem.getUnqualifiedType();
4915 RHSElem = RHSElem.getUnqualifiedType();
4916 }
4917
4918 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004919 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004920 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4921 return LHS;
4922 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4923 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004924 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4925 ArrayType::ArraySizeModifier(), 0);
4926 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4927 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004928 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4929 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004930 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4931 return LHS;
4932 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4933 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004934 if (LVAT) {
4935 // FIXME: This isn't correct! But tricky to implement because
4936 // the array's size has to be the size of LHS, but the type
4937 // has to be different.
4938 return LHS;
4939 }
4940 if (RVAT) {
4941 // FIXME: This isn't correct! But tricky to implement because
4942 // the array's size has to be the size of RHS, but the type
4943 // has to be different.
4944 return RHS;
4945 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004946 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4947 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004948 return getIncompleteArrayType(ResultType,
4949 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004950 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004951 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00004952 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00004953 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004954 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004955 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004956 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004957 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004958 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004959 case Type::Complex:
4960 // Distinct complex types are incompatible.
4961 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004962 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004963 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004964 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4965 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004966 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004967 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004968 case Type::ObjCObject: {
4969 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004970 // FIXME: This should be type compatibility, e.g. whether
4971 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004972 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4973 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4974 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004975 return LHS;
4976
Eli Friedman3d815e72008-08-22 00:56:42 +00004977 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004978 }
Steve Naroff14108da2009-07-10 23:34:53 +00004979 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004980 if (OfBlockPointer) {
4981 if (canAssignObjCInterfacesInBlockPointer(
4982 LHS->getAs<ObjCObjectPointerType>(),
4983 RHS->getAs<ObjCObjectPointerType>()))
4984 return LHS;
4985 return QualType();
4986 }
John McCall183700f2009-09-21 23:43:11 +00004987 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4988 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004989 return LHS;
4990
Steve Naroffbc76dd02008-12-10 22:14:21 +00004991 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004992 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004993 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004994
4995 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004996}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004997
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004998/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4999/// 'RHS' attributes and returns the merged version; including for function
5000/// return types.
5001QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5002 QualType LHSCan = getCanonicalType(LHS),
5003 RHSCan = getCanonicalType(RHS);
5004 // If two types are identical, they are compatible.
5005 if (LHSCan == RHSCan)
5006 return LHS;
5007 if (RHSCan->isFunctionType()) {
5008 if (!LHSCan->isFunctionType())
5009 return QualType();
5010 QualType OldReturnType =
5011 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5012 QualType NewReturnType =
5013 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5014 QualType ResReturnType =
5015 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5016 if (ResReturnType.isNull())
5017 return QualType();
5018 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5019 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5020 // In either case, use OldReturnType to build the new function type.
5021 const FunctionType *F = LHS->getAs<FunctionType>();
5022 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5023 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5024 QualType ResultType
5025 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5026 FPT->getNumArgs(), FPT->isVariadic(),
5027 FPT->getTypeQuals(),
5028 FPT->hasExceptionSpec(),
5029 FPT->hasAnyExceptionSpec(),
5030 FPT->getNumExceptions(),
5031 FPT->exception_begin(),
5032 Info);
5033 return ResultType;
5034 }
5035 }
5036 return QualType();
5037 }
5038
5039 // If the qualifiers are different, the types can still be merged.
5040 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5041 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5042 if (LQuals != RQuals) {
5043 // If any of these qualifiers are different, we have a type mismatch.
5044 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5045 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5046 return QualType();
5047
5048 // Exactly one GC qualifier difference is allowed: __strong is
5049 // okay if the other type has no GC qualifier but is an Objective
5050 // C object pointer (i.e. implicitly strong by default). We fix
5051 // this by pretending that the unqualified type was actually
5052 // qualified __strong.
5053 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5054 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5055 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5056
5057 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5058 return QualType();
5059
5060 if (GC_L == Qualifiers::Strong)
5061 return LHS;
5062 if (GC_R == Qualifiers::Strong)
5063 return RHS;
5064 return QualType();
5065 }
5066
5067 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5068 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5069 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5070 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5071 if (ResQT == LHSBaseQT)
5072 return LHS;
5073 if (ResQT == RHSBaseQT)
5074 return RHS;
5075 }
5076 return QualType();
5077}
5078
Chris Lattner5426bf62008-04-07 07:01:58 +00005079//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005080// Integer Predicates
5081//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005082
Eli Friedmanad74a752008-06-28 06:23:08 +00005083unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005084 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005085 return 1;
John McCall842aef82009-12-09 09:09:27 +00005086 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005087 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005088 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005089 return (unsigned)getTypeSize(T);
5090}
5091
5092QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005093 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005094
5095 // Turn <4 x signed int> -> <4 x unsigned int>
5096 if (const VectorType *VTy = T->getAs<VectorType>())
5097 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005098 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005099
5100 // For enums, we return the unsigned version of the base type.
5101 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005102 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005103
5104 const BuiltinType *BTy = T->getAs<BuiltinType>();
5105 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005106 switch (BTy->getKind()) {
5107 case BuiltinType::Char_S:
5108 case BuiltinType::SChar:
5109 return UnsignedCharTy;
5110 case BuiltinType::Short:
5111 return UnsignedShortTy;
5112 case BuiltinType::Int:
5113 return UnsignedIntTy;
5114 case BuiltinType::Long:
5115 return UnsignedLongTy;
5116 case BuiltinType::LongLong:
5117 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005118 case BuiltinType::Int128:
5119 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005120 default:
5121 assert(0 && "Unexpected signed integer type");
5122 return QualType();
5123 }
5124}
5125
Douglas Gregor2cf26342009-04-09 22:27:44 +00005126ExternalASTSource::~ExternalASTSource() { }
5127
5128void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005129
5130
5131//===----------------------------------------------------------------------===//
5132// Builtin Type Computation
5133//===----------------------------------------------------------------------===//
5134
5135/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5136/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005137static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005138 ASTContext::GetBuiltinTypeError &Error,
5139 bool AllowTypeModifiers = true) {
5140 // Modifiers.
5141 int HowLong = 0;
5142 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005143
Chris Lattner86df27b2009-06-14 00:45:47 +00005144 // Read the modifiers first.
5145 bool Done = false;
5146 while (!Done) {
5147 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005148 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005149 case 'S':
5150 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5151 assert(!Signed && "Can't use 'S' modifier multiple times!");
5152 Signed = true;
5153 break;
5154 case 'U':
5155 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5156 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5157 Unsigned = true;
5158 break;
5159 case 'L':
5160 assert(HowLong <= 2 && "Can't have LLLL modifier");
5161 ++HowLong;
5162 break;
5163 }
5164 }
5165
5166 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Chris Lattner86df27b2009-06-14 00:45:47 +00005168 // Read the base type.
5169 switch (*Str++) {
5170 default: assert(0 && "Unknown builtin type letter!");
5171 case 'v':
5172 assert(HowLong == 0 && !Signed && !Unsigned &&
5173 "Bad modifiers used with 'v'!");
5174 Type = Context.VoidTy;
5175 break;
5176 case 'f':
5177 assert(HowLong == 0 && !Signed && !Unsigned &&
5178 "Bad modifiers used with 'f'!");
5179 Type = Context.FloatTy;
5180 break;
5181 case 'd':
5182 assert(HowLong < 2 && !Signed && !Unsigned &&
5183 "Bad modifiers used with 'd'!");
5184 if (HowLong)
5185 Type = Context.LongDoubleTy;
5186 else
5187 Type = Context.DoubleTy;
5188 break;
5189 case 's':
5190 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5191 if (Unsigned)
5192 Type = Context.UnsignedShortTy;
5193 else
5194 Type = Context.ShortTy;
5195 break;
5196 case 'i':
5197 if (HowLong == 3)
5198 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5199 else if (HowLong == 2)
5200 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5201 else if (HowLong == 1)
5202 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5203 else
5204 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5205 break;
5206 case 'c':
5207 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5208 if (Signed)
5209 Type = Context.SignedCharTy;
5210 else if (Unsigned)
5211 Type = Context.UnsignedCharTy;
5212 else
5213 Type = Context.CharTy;
5214 break;
5215 case 'b': // boolean
5216 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5217 Type = Context.BoolTy;
5218 break;
5219 case 'z': // size_t.
5220 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5221 Type = Context.getSizeType();
5222 break;
5223 case 'F':
5224 Type = Context.getCFConstantStringType();
5225 break;
5226 case 'a':
5227 Type = Context.getBuiltinVaListType();
5228 assert(!Type.isNull() && "builtin va list type not initialized!");
5229 break;
5230 case 'A':
5231 // This is a "reference" to a va_list; however, what exactly
5232 // this means depends on how va_list is defined. There are two
5233 // different kinds of va_list: ones passed by value, and ones
5234 // passed by reference. An example of a by-value va_list is
5235 // x86, where va_list is a char*. An example of by-ref va_list
5236 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5237 // we want this argument to be a char*&; for x86-64, we want
5238 // it to be a __va_list_tag*.
5239 Type = Context.getBuiltinVaListType();
5240 assert(!Type.isNull() && "builtin va list type not initialized!");
5241 if (Type->isArrayType()) {
5242 Type = Context.getArrayDecayedType(Type);
5243 } else {
5244 Type = Context.getLValueReferenceType(Type);
5245 }
5246 break;
5247 case 'V': {
5248 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005249 unsigned NumElements = strtoul(Str, &End, 10);
5250 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005251
Chris Lattner86df27b2009-06-14 00:45:47 +00005252 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Chris Lattner86df27b2009-06-14 00:45:47 +00005254 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005255 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005256 Type = Context.getVectorType(ElementType, NumElements,
5257 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005258 break;
5259 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005260 case 'X': {
5261 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5262 Type = Context.getComplexType(ElementType);
5263 break;
5264 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005265 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005266 Type = Context.getFILEType();
5267 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005268 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005269 return QualType();
5270 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005271 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005272 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005273 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005274 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005275 else
5276 Type = Context.getjmp_bufType();
5277
Mike Stumpfd612db2009-07-28 23:47:15 +00005278 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005279 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005280 return QualType();
5281 }
5282 break;
Mike Stump782fa302009-07-28 02:25:19 +00005283 }
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Chris Lattner86df27b2009-06-14 00:45:47 +00005285 if (!AllowTypeModifiers)
5286 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005287
Chris Lattner86df27b2009-06-14 00:45:47 +00005288 Done = false;
5289 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005290 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005291 default: Done = true; --Str; break;
5292 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005293 case '&':
John McCall187ab372010-03-12 04:21:28 +00005294 {
5295 // Both pointers and references can have their pointee types
5296 // qualified with an address space.
5297 char *End;
5298 unsigned AddrSpace = strtoul(Str, &End, 10);
5299 if (End != Str && AddrSpace != 0) {
5300 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5301 Str = End;
5302 }
5303 }
5304 if (c == '*')
5305 Type = Context.getPointerType(Type);
5306 else
5307 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005308 break;
5309 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5310 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005311 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005312 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005313 case 'D':
5314 Type = Context.getVolatileType(Type);
5315 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005316 }
5317 }
Mike Stump1eb44332009-09-09 15:08:12 +00005318
Chris Lattner86df27b2009-06-14 00:45:47 +00005319 return Type;
5320}
5321
5322/// GetBuiltinType - Return the type for the specified builtin.
5323QualType ASTContext::GetBuiltinType(unsigned id,
5324 GetBuiltinTypeError &Error) {
5325 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005326
Chris Lattner86df27b2009-06-14 00:45:47 +00005327 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005328
Chris Lattner86df27b2009-06-14 00:45:47 +00005329 Error = GE_None;
5330 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5331 if (Error != GE_None)
5332 return QualType();
5333 while (TypeStr[0] && TypeStr[0] != '.') {
5334 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5335 if (Error != GE_None)
5336 return QualType();
5337
5338 // Do array -> pointer decay. The builtin should use the decayed type.
5339 if (Ty->isArrayType())
5340 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005341
Chris Lattner86df27b2009-06-14 00:45:47 +00005342 ArgTypes.push_back(Ty);
5343 }
5344
5345 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5346 "'.' should only occur at end of builtin type list!");
5347
5348 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5349 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5350 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005351
5352 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005353 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005354 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005355 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005356}
Eli Friedmana95d7572009-08-19 07:44:53 +00005357
5358QualType
5359ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5360 // Perform the usual unary conversions. We do this early so that
5361 // integral promotions to "int" can allow us to exit early, in the
5362 // lhs == rhs check. Also, for conversion purposes, we ignore any
5363 // qualifiers. For example, "const float" and "float" are
5364 // equivalent.
5365 if (lhs->isPromotableIntegerType())
5366 lhs = getPromotedIntegerType(lhs);
5367 else
5368 lhs = lhs.getUnqualifiedType();
5369 if (rhs->isPromotableIntegerType())
5370 rhs = getPromotedIntegerType(rhs);
5371 else
5372 rhs = rhs.getUnqualifiedType();
5373
5374 // If both types are identical, no conversion is needed.
5375 if (lhs == rhs)
5376 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005377
Eli Friedmana95d7572009-08-19 07:44:53 +00005378 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5379 // The caller can deal with this (e.g. pointer + int).
5380 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5381 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005382
5383 // At this point, we have two different arithmetic types.
5384
Eli Friedmana95d7572009-08-19 07:44:53 +00005385 // Handle complex types first (C99 6.3.1.8p1).
5386 if (lhs->isComplexType() || rhs->isComplexType()) {
5387 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005388 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005389 // convert the rhs to the lhs complex type.
5390 return lhs;
5391 }
Mike Stump1eb44332009-09-09 15:08:12 +00005392 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005393 // convert the lhs to the rhs complex type.
5394 return rhs;
5395 }
5396 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005397 // When both operands are complex, the shorter operand is converted to the
5398 // type of the longer, and that is the type of the result. This corresponds
5399 // to what is done when combining two real floating-point operands.
5400 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005401 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005402 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005403 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005404 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005405 // "double _Complex" is promoted to "long double _Complex".
5406 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005407
5408 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005409 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005410 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005411 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005412 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005413 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5414 // domains match. This is a requirement for our implementation, C99
5415 // does not require this promotion.
5416 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5417 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5418 return rhs;
5419 } else { // handle "_Complex double, double".
5420 return lhs;
5421 }
5422 }
5423 return lhs; // The domain/size match exactly.
5424 }
5425 // Now handle "real" floating types (i.e. float, double, long double).
5426 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5427 // if we have an integer operand, the result is the real floating type.
5428 if (rhs->isIntegerType()) {
5429 // convert rhs to the lhs floating point type.
5430 return lhs;
5431 }
5432 if (rhs->isComplexIntegerType()) {
5433 // convert rhs to the complex floating point type.
5434 return getComplexType(lhs);
5435 }
5436 if (lhs->isIntegerType()) {
5437 // convert lhs to the rhs floating point type.
5438 return rhs;
5439 }
Mike Stump1eb44332009-09-09 15:08:12 +00005440 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005441 // convert lhs to the complex floating point type.
5442 return getComplexType(rhs);
5443 }
5444 // We have two real floating types, float/complex combos were handled above.
5445 // Convert the smaller operand to the bigger result.
5446 int result = getFloatingTypeOrder(lhs, rhs);
5447 if (result > 0) // convert the rhs
5448 return lhs;
5449 assert(result < 0 && "illegal float comparison");
5450 return rhs; // convert the lhs
5451 }
5452 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5453 // Handle GCC complex int extension.
5454 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5455 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5456
5457 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005458 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005459 rhsComplexInt->getElementType()) >= 0)
5460 return lhs; // convert the rhs
5461 return rhs;
5462 } else if (lhsComplexInt && rhs->isIntegerType()) {
5463 // convert the rhs to the lhs complex type.
5464 return lhs;
5465 } else if (rhsComplexInt && lhs->isIntegerType()) {
5466 // convert the lhs to the rhs complex type.
5467 return rhs;
5468 }
5469 }
5470 // Finally, we have two differing integer types.
5471 // The rules for this case are in C99 6.3.1.8
5472 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005473 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5474 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005475 QualType destType;
5476 if (lhsSigned == rhsSigned) {
5477 // Same signedness; use the higher-ranked type
5478 destType = compare >= 0 ? lhs : rhs;
5479 } else if (compare != (lhsSigned ? 1 : -1)) {
5480 // The unsigned type has greater than or equal rank to the
5481 // signed type, so use the unsigned type
5482 destType = lhsSigned ? rhs : lhs;
5483 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5484 // The two types are different widths; if we are here, that
5485 // means the signed type is larger than the unsigned type, so
5486 // use the signed type.
5487 destType = lhsSigned ? lhs : rhs;
5488 } else {
5489 // The signed type is higher-ranked than the unsigned type,
5490 // but isn't actually any bigger (like unsigned int and long
5491 // on most 32-bit systems). Use the unsigned type corresponding
5492 // to the signed type.
5493 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5494 }
5495 return destType;
5496}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005497
5498GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5499 GVALinkage External = GVA_StrongExternal;
5500
5501 Linkage L = FD->getLinkage();
5502 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5503 FD->getType()->getLinkage() == UniqueExternalLinkage)
5504 L = UniqueExternalLinkage;
5505
5506 switch (L) {
5507 case NoLinkage:
5508 case InternalLinkage:
5509 case UniqueExternalLinkage:
5510 return GVA_Internal;
5511
5512 case ExternalLinkage:
5513 switch (FD->getTemplateSpecializationKind()) {
5514 case TSK_Undeclared:
5515 case TSK_ExplicitSpecialization:
5516 External = GVA_StrongExternal;
5517 break;
5518
5519 case TSK_ExplicitInstantiationDefinition:
5520 return GVA_ExplicitTemplateInstantiation;
5521
5522 case TSK_ExplicitInstantiationDeclaration:
5523 case TSK_ImplicitInstantiation:
5524 External = GVA_TemplateInstantiation;
5525 break;
5526 }
5527 }
5528
5529 if (!FD->isInlined())
5530 return External;
5531
5532 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5533 // GNU or C99 inline semantics. Determine whether this symbol should be
5534 // externally visible.
5535 if (FD->isInlineDefinitionExternallyVisible())
5536 return External;
5537
5538 // C99 inline semantics, where the symbol is not externally visible.
5539 return GVA_C99Inline;
5540 }
5541
5542 // C++0x [temp.explicit]p9:
5543 // [ Note: The intent is that an inline function that is the subject of
5544 // an explicit instantiation declaration will still be implicitly
5545 // instantiated when used so that the body can be considered for
5546 // inlining, but that no out-of-line copy of the inline function would be
5547 // generated in the translation unit. -- end note ]
5548 if (FD->getTemplateSpecializationKind()
5549 == TSK_ExplicitInstantiationDeclaration)
5550 return GVA_C99Inline;
5551
5552 return GVA_CXXInline;
5553}
5554
5555GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5556 // If this is a static data member, compute the kind of template
5557 // specialization. Otherwise, this variable is not part of a
5558 // template.
5559 TemplateSpecializationKind TSK = TSK_Undeclared;
5560 if (VD->isStaticDataMember())
5561 TSK = VD->getTemplateSpecializationKind();
5562
5563 Linkage L = VD->getLinkage();
5564 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5565 VD->getType()->getLinkage() == UniqueExternalLinkage)
5566 L = UniqueExternalLinkage;
5567
5568 switch (L) {
5569 case NoLinkage:
5570 case InternalLinkage:
5571 case UniqueExternalLinkage:
5572 return GVA_Internal;
5573
5574 case ExternalLinkage:
5575 switch (TSK) {
5576 case TSK_Undeclared:
5577 case TSK_ExplicitSpecialization:
5578 return GVA_StrongExternal;
5579
5580 case TSK_ExplicitInstantiationDeclaration:
5581 llvm_unreachable("Variable should not be instantiated");
5582 // Fall through to treat this like any other instantiation.
5583
5584 case TSK_ExplicitInstantiationDefinition:
5585 return GVA_ExplicitTemplateInstantiation;
5586
5587 case TSK_ImplicitInstantiation:
5588 return GVA_TemplateInstantiation;
5589 }
5590 }
5591
5592 return GVA_StrongExternal;
5593}
5594
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005595bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005596 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5597 if (!VD->isFileVarDecl())
5598 return false;
5599 } else if (!isa<FunctionDecl>(D))
5600 return false;
5601
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005602 // Weak references don't produce any output by themselves.
5603 if (D->hasAttr<WeakRefAttr>())
5604 return false;
5605
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005606 // Aliases and used decls are required.
5607 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5608 return true;
5609
5610 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5611 // Forward declarations aren't required.
5612 if (!FD->isThisDeclarationADefinition())
5613 return false;
5614
5615 // Constructors and destructors are required.
5616 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5617 return true;
5618
5619 // The key function for a class is required.
5620 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5621 const CXXRecordDecl *RD = MD->getParent();
5622 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5623 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5624 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5625 return true;
5626 }
5627 }
5628
5629 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5630
5631 // static, static inline, always_inline, and extern inline functions can
5632 // always be deferred. Normal inline functions can be deferred in C99/C++.
5633 // Implicit template instantiations can also be deferred in C++.
5634 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5635 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5636 return false;
5637 return true;
5638 }
5639
5640 const VarDecl *VD = cast<VarDecl>(D);
5641 assert(VD->isFileVarDecl() && "Expected file scoped var");
5642
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005643 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5644 return false;
5645
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005646 // Structs that have non-trivial constructors or destructors are required.
5647
5648 // FIXME: Handle references.
5649 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5650 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005651 if (RD->hasDefinition() &&
5652 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005653 return true;
5654 }
5655 }
5656
5657 GVALinkage L = GetGVALinkageForVariable(VD);
5658 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5659 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5660 return false;
5661 }
5662
5663 return true;
5664}
Charles Davis071cc7d2010-08-16 03:33:14 +00005665
5666CXXABI::~CXXABI() {}