blob: b549415a1b45ae77e824bd0b5310fbb15e22a3b1 [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) {
139 if (!LangOpts.CPlusPlus) return NULL;
140 if (T.getCXXABI() == "microsoft")
141 return CreateMicrosoftCXXABI(*this);
142 else
143 return CreateItaniumCXXABI(*this);
144}
145
Chris Lattner61710852008-10-05 17:34:18 +0000146ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000147 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000148 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000149 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000150 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000151 TemplateSpecializationTypes(this_()),
152 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000153 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
154 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000155 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000156 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000157 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000158 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000159 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000160 BuiltinInfo(builtins),
161 DeclarationNames(*this),
162 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000163 LastSDM(0, 0),
164 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000165 ObjCIdRedefinitionType = QualType();
166 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000167 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000168 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000169 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000170 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000171}
172
Reid Spencer5f016e22007-07-11 17:01:13 +0000173ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000174 // Release the DenseMaps associated with DeclContext objects.
175 // FIXME: Is this the ideal solution?
176 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000177
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000178 // Call all of the deallocation functions.
179 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
180 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000181
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000182 // Release all of the memory associated with overridden C++ methods.
183 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
184 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
185 OM != OMEnd; ++OM)
186 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000187
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000188 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000189 // because they can contain DenseMaps.
190 for (llvm::DenseMap<const ObjCContainerDecl*,
191 const ASTRecordLayout*>::iterator
192 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
193 // Increment in loop to prevent using deallocated memory.
194 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
195 R->Destroy(*this);
196
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000197 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
198 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202 }
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000203 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000204
Douglas Gregor00545312010-05-23 18:26:36 +0000205void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
206 Deallocations.push_back(std::make_pair(Callback, Data));
207}
208
Mike Stump1eb44332009-09-09 15:08:12 +0000209void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000210ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
211 ExternalSource.reset(Source.take());
212}
213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214void ASTContext::PrintStats() const {
215 fprintf(stderr, "*** AST Context Stats:\n");
216 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000217
Douglas Gregordbe833d2009-05-26 14:40:08 +0000218 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000219#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000220#define ABSTRACT_TYPE(Name, Parent)
221#include "clang/AST/TypeNodes.def"
222 0 // Extra
223 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000224
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
226 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000227 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 }
229
Douglas Gregordbe833d2009-05-26 14:40:08 +0000230 unsigned Idx = 0;
231 unsigned TotalBytes = 0;
232#define TYPE(Name, Parent) \
233 if (counts[Idx]) \
234 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
235 TotalBytes += counts[Idx] * sizeof(Name##Type); \
236 ++Idx;
237#define ABSTRACT_TYPE(Name, Parent)
238#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Douglas Gregordbe833d2009-05-26 14:40:08 +0000240 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000241
Douglas Gregor4923aa22010-07-02 20:37:36 +0000242 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000243 fprintf(stderr, " %u/%u implicit default constructors created\n",
244 NumImplicitDefaultConstructorsDeclared,
245 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000246 fprintf(stderr, " %u/%u implicit copy constructors created\n",
247 NumImplicitCopyConstructorsDeclared,
248 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000249 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
250 NumImplicitCopyAssignmentOperatorsDeclared,
251 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000252 fprintf(stderr, " %u/%u implicit destructors created\n",
253 NumImplicitDestructorsDeclared, NumImplicitDestructors);
254
Douglas Gregor2cf26342009-04-09 22:27:44 +0000255 if (ExternalSource.get()) {
256 fprintf(stderr, "\n");
257 ExternalSource->PrintStats();
258 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000259
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000260 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000261}
262
263
John McCalle27ec8a2009-10-23 23:03:21 +0000264void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000265 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000266 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000267 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000268}
269
Reid Spencer5f016e22007-07-11 17:01:13 +0000270void ASTContext::InitBuiltinTypes() {
271 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // C99 6.2.5p19.
274 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 // C99 6.2.5p2.
277 InitBuiltinType(BoolTy, BuiltinType::Bool);
278 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000279 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 InitBuiltinType(CharTy, BuiltinType::Char_S);
281 else
282 InitBuiltinType(CharTy, BuiltinType::Char_U);
283 // C99 6.2.5p4.
284 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
285 InitBuiltinType(ShortTy, BuiltinType::Short);
286 InitBuiltinType(IntTy, BuiltinType::Int);
287 InitBuiltinType(LongTy, BuiltinType::Long);
288 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 // C99 6.2.5p6.
291 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
292 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
293 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
294 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
295 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // C99 6.2.5p10.
298 InitBuiltinType(FloatTy, BuiltinType::Float);
299 InitBuiltinType(DoubleTy, BuiltinType::Double);
300 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000301
Chris Lattner2df9ced2009-04-30 02:43:43 +0000302 // GNU extension, 128-bit integers.
303 InitBuiltinType(Int128Ty, BuiltinType::Int128);
304 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
305
Chris Lattner3a250322009-02-26 23:43:47 +0000306 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
307 InitBuiltinType(WCharTy, BuiltinType::WChar);
308 else // C99
309 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000310
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000311 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
312 InitBuiltinType(Char16Ty, BuiltinType::Char16);
313 else // C99
314 Char16Ty = getFromTargetType(Target.getChar16Type());
315
316 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
317 InitBuiltinType(Char32Ty, BuiltinType::Char32);
318 else // C99
319 Char32Ty = getFromTargetType(Target.getChar32Type());
320
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000321 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000322 InitBuiltinType(OverloadTy, BuiltinType::Overload);
323
324 // Placeholder type for type-dependent expressions whose type is
325 // completely unknown. No code should ever check a type against
326 // DependentTy and users should never see it; however, it is here to
327 // help diagnose failures to properly check for type-dependent
328 // expressions.
329 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330
Mike Stump1eb44332009-09-09 15:08:12 +0000331 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000332 // not yet been deduced.
333 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // C99 6.2.5p11.
336 FloatComplexTy = getComplexType(FloatTy);
337 DoubleComplexTy = getComplexType(DoubleTy);
338 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339
Steve Naroff7e219e42007-10-15 14:41:52 +0000340 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Steve Naroffde2e22d2009-07-15 18:40:39 +0000342 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
343 ObjCIdTypedefType = QualType();
344 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000345 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000347 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000348 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
349 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000350 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000351
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000352 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000354 // void * type
355 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000356
357 // nullptr type (C++0x 2.14.7)
358 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000359}
360
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000361MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000362ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000363 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000364 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000365 = InstantiatedFromStaticDataMember.find(Var);
366 if (Pos == InstantiatedFromStaticDataMember.end())
367 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Douglas Gregor7caa6822009-07-24 20:34:43 +0000369 return Pos->second;
370}
371
Mike Stump1eb44332009-09-09 15:08:12 +0000372void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000373ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000374 TemplateSpecializationKind TSK,
375 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000376 assert(Inst->isStaticDataMember() && "Not a static data member");
377 assert(Tmpl->isStaticDataMember() && "Not a static data member");
378 assert(!InstantiatedFromStaticDataMember[Inst] &&
379 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000380 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000381 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000382}
383
John McCall7ba107a2009-11-18 02:36:19 +0000384NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000385ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000386 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000387 = InstantiatedFromUsingDecl.find(UUD);
388 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000389 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Anders Carlsson0d8df782009-08-29 19:37:28 +0000391 return Pos->second;
392}
393
394void
John McCalled976492009-12-04 22:46:56 +0000395ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
396 assert((isa<UsingDecl>(Pattern) ||
397 isa<UnresolvedUsingValueDecl>(Pattern) ||
398 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
399 "pattern decl is not a using decl");
400 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
401 InstantiatedFromUsingDecl[Inst] = Pattern;
402}
403
404UsingShadowDecl *
405ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
406 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
407 = InstantiatedFromUsingShadowDecl.find(Inst);
408 if (Pos == InstantiatedFromUsingShadowDecl.end())
409 return 0;
410
411 return Pos->second;
412}
413
414void
415ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
416 UsingShadowDecl *Pattern) {
417 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
418 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000419}
420
Anders Carlssond8b285f2009-09-01 04:26:58 +0000421FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
422 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
423 = InstantiatedFromUnnamedFieldDecl.find(Field);
424 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
425 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlssond8b285f2009-09-01 04:26:58 +0000427 return Pos->second;
428}
429
430void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
431 FieldDecl *Tmpl) {
432 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
433 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
434 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
435 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Anders Carlssond8b285f2009-09-01 04:26:58 +0000437 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
438}
439
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000440ASTContext::overridden_cxx_method_iterator
441ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
442 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
443 = OverriddenMethods.find(Method);
444 if (Pos == OverriddenMethods.end())
445 return 0;
446
447 return Pos->second.begin();
448}
449
450ASTContext::overridden_cxx_method_iterator
451ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
452 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
453 = OverriddenMethods.find(Method);
454 if (Pos == OverriddenMethods.end())
455 return 0;
456
457 return Pos->second.end();
458}
459
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000460unsigned
461ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
462 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
463 = OverriddenMethods.find(Method);
464 if (Pos == OverriddenMethods.end())
465 return 0;
466
467 return Pos->second.size();
468}
469
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000470void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
471 const CXXMethodDecl *Overridden) {
472 OverriddenMethods[Method].push_back(Overridden);
473}
474
Chris Lattner464175b2007-07-18 17:52:12 +0000475//===----------------------------------------------------------------------===//
476// Type Sizing and Analysis
477//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000478
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000479/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
480/// scalar floating point type.
481const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000482 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000483 assert(BT && "Not a floating point type!");
484 switch (BT->getKind()) {
485 default: assert(0 && "Not a floating point type!");
486 case BuiltinType::Float: return Target.getFloatFormat();
487 case BuiltinType::Double: return Target.getDoubleFormat();
488 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
489 }
490}
491
Ken Dyck8b752f12010-01-27 17:10:57 +0000492/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000493/// specified decl. Note that bitfields do not have a valid alignment, so
494/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000495/// If @p RefAsPointee, references are treated like their underlying type
496/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000497CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000498 unsigned Align = Target.getCharWidth();
499
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000500 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000501 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000502
Chris Lattneraf707ab2009-01-24 21:53:27 +0000503 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
504 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000506 if (RefAsPointee)
507 T = RT->getPointeeType();
508 else
509 T = getPointerType(RT->getPointeeType());
510 }
511 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000512 unsigned MinWidth = Target.getLargeArrayMinWidth();
513 unsigned ArrayAlign = Target.getLargeArrayAlign();
514 if (isa<VariableArrayType>(T) && MinWidth != 0)
515 Align = std::max(Align, ArrayAlign);
516 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
517 unsigned Size = getTypeSize(CT);
518 if (MinWidth != 0 && MinWidth <= Size)
519 Align = std::max(Align, ArrayAlign);
520 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000521 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000522 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
523 T = cast<ArrayType>(T)->getElementType();
524
525 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
526 }
Charles Davis05f62472010-02-23 04:52:00 +0000527 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
528 // In the case of a field in a packed struct, we want the minimum
529 // of the alignment of the field and the alignment of the struct.
530 Align = std::min(Align,
531 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
532 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000533 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000534
Ken Dyck8b752f12010-01-27 17:10:57 +0000535 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000536}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000537
John McCallea1471e2010-05-20 01:18:31 +0000538std::pair<CharUnits, CharUnits>
539ASTContext::getTypeInfoInChars(const Type *T) {
540 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
541 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
542 CharUnits::fromQuantity(Info.second / getCharWidth()));
543}
544
545std::pair<CharUnits, CharUnits>
546ASTContext::getTypeInfoInChars(QualType T) {
547 return getTypeInfoInChars(T.getTypePtr());
548}
549
Chris Lattnera7674d82007-07-13 22:13:22 +0000550/// getTypeSize - Return the size of the specified type, in bits. This method
551/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000552///
553/// FIXME: Pointers into different addr spaces could have different sizes and
554/// alignment requirements: getPointerInfo should take an AddrSpace, this
555/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000556std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000557ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000558 uint64_t Width=0;
559 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000560 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000561#define TYPE(Class, Base)
562#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000563#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000564#define DEPENDENT_TYPE(Class, Base) case Type::Class:
565#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000566 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000567 break;
568
Chris Lattner692233e2007-07-13 22:27:08 +0000569 case Type::FunctionNoProto:
570 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000571 // GCC extension: alignof(function) = 32 bits
572 Width = 0;
573 Align = 32;
574 break;
575
Douglas Gregor72564e72009-02-26 23:50:07 +0000576 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000577 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000578 Width = 0;
579 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
580 break;
581
Steve Narofffb22d962007-08-30 01:06:46 +0000582 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000583 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattner98be4942008-03-05 18:54:05 +0000585 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000586 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000587 Align = EltInfo.second;
588 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000589 }
Nate Begeman213541a2008-04-18 23:10:10 +0000590 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000591 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000592 const VectorType *VT = cast<VectorType>(T);
593 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
594 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000595 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000596 // If the alignment is not a power of 2, round up to the next power of 2.
597 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000598 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000599 Align = llvm::NextPowerOf2(Align);
600 Width = llvm::RoundUpToAlignment(Width, Align);
601 }
Chris Lattner030d8842007-07-19 22:06:24 +0000602 break;
603 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000604
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000605 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000606 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000607 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000608 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000609 // GCC extension: alignof(void) = 8 bits.
610 Width = 0;
611 Align = 8;
612 break;
613
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000614 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000615 Width = Target.getBoolWidth();
616 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000617 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000618 case BuiltinType::Char_S:
619 case BuiltinType::Char_U:
620 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000621 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 Width = Target.getCharWidth();
623 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000624 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000625 case BuiltinType::WChar:
626 Width = Target.getWCharWidth();
627 Align = Target.getWCharAlign();
628 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000629 case BuiltinType::Char16:
630 Width = Target.getChar16Width();
631 Align = Target.getChar16Align();
632 break;
633 case BuiltinType::Char32:
634 Width = Target.getChar32Width();
635 Align = Target.getChar32Align();
636 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000637 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getShortWidth();
640 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000642 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000643 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000644 Width = Target.getIntWidth();
645 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000646 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000647 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000648 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000649 Width = Target.getLongWidth();
650 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000651 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000652 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000653 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000654 Width = Target.getLongLongWidth();
655 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000656 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000657 case BuiltinType::Int128:
658 case BuiltinType::UInt128:
659 Width = 128;
660 Align = 128; // int128_t is 128-bit aligned on all targets.
661 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000663 Width = Target.getFloatWidth();
664 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 break;
666 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000667 Width = Target.getDoubleWidth();
668 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000669 break;
670 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000671 Width = Target.getLongDoubleWidth();
672 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000674 case BuiltinType::NullPtr:
675 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
676 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000677 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000678 case BuiltinType::ObjCId:
679 case BuiltinType::ObjCClass:
680 case BuiltinType::ObjCSel:
681 Width = Target.getPointerWidth(0);
682 Align = Target.getPointerAlign(0);
683 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000684 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000685 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000686 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000687 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000688 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000689 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000690 case Type::BlockPointer: {
691 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
692 Width = Target.getPointerWidth(AS);
693 Align = Target.getPointerAlign(AS);
694 break;
695 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000696 case Type::LValueReference:
697 case Type::RValueReference: {
698 // alignof and sizeof should never enter this code path here, so we go
699 // the pointer route.
700 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
701 Width = Target.getPointerWidth(AS);
702 Align = Target.getPointerAlign(AS);
703 break;
704 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000705 case Type::Pointer: {
706 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000707 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000708 Align = Target.getPointerAlign(AS);
709 break;
710 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000711 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000712 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000713 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000714 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000715 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000716 Align = PtrDiffInfo.second;
717 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000718 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000719 case Type::Complex: {
720 // Complex types have the same alignment as their elements, but twice the
721 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000722 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000723 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000724 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000725 Align = EltInfo.second;
726 break;
727 }
John McCallc12c5bb2010-05-15 11:32:37 +0000728 case Type::ObjCObject:
729 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000730 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000731 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000732 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
733 Width = Layout.getSize();
734 Align = Layout.getAlignment();
735 break;
736 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000737 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000738 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000739 const TagType *TT = cast<TagType>(T);
740
741 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000742 Width = 1;
743 Align = 1;
744 break;
745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Daniel Dunbar1d751182008-11-08 05:48:37 +0000747 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000748 return getTypeInfo(ET->getDecl()->getIntegerType());
749
Daniel Dunbar1d751182008-11-08 05:48:37 +0000750 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000751 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
752 Width = Layout.getSize();
753 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000754 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000755 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000756
Chris Lattner9fcfe922009-10-22 05:17:15 +0000757 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000758 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
759 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000760
Douglas Gregor18857642009-04-30 17:32:17 +0000761 case Type::Typedef: {
762 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000763 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000764 Align = std::max(Aligned->getMaxAlignment(),
765 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000766 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
767 } else
768 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000769 break;
Chris Lattner71763312008-04-06 22:05:18 +0000770 }
Douglas Gregor18857642009-04-30 17:32:17 +0000771
772 case Type::TypeOfExpr:
773 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
774 .getTypePtr());
775
776 case Type::TypeOf:
777 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
778
Anders Carlsson395b4752009-06-24 19:06:50 +0000779 case Type::Decltype:
780 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
781 .getTypePtr());
782
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000783 case Type::Elaborated:
784 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregor18857642009-04-30 17:32:17 +0000786 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000787 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000788 "Cannot request the size of a dependent type");
789 // FIXME: this is likely to be wrong once we support template
790 // aliases, since a template alias could refer to a typedef that
791 // has an __aligned__ attribute on it.
792 return getTypeInfo(getCanonicalType(T));
793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Chris Lattner464175b2007-07-18 17:52:12 +0000795 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000796 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000797}
798
Ken Dyckbdc601b2009-12-22 14:23:30 +0000799/// getTypeSizeInChars - Return the size of the specified type, in characters.
800/// This method does not work on incomplete types.
801CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000802 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000803}
804CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000805 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000806}
807
Ken Dyck16e20cc2010-01-26 17:25:18 +0000808/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000809/// characters. This method does not work on incomplete types.
810CharUnits ASTContext::getTypeAlignInChars(QualType T) {
811 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
812}
813CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
814 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
815}
816
Chris Lattner34ebde42009-01-27 18:08:34 +0000817/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
818/// type for the current target in bits. This can be different than the ABI
819/// alignment in cases where it is beneficial for performance to overalign
820/// a data type.
821unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
822 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000823
824 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000825 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000826 T = CT->getElementType().getTypePtr();
827 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
828 T->isSpecificBuiltinType(BuiltinType::LongLong))
829 return std::max(ABIAlign, (unsigned)getTypeSize(T));
830
Chris Lattner34ebde42009-01-27 18:08:34 +0000831 return ABIAlign;
832}
833
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000834static void CollectLocalObjCIvars(ASTContext *Ctx,
835 const ObjCInterfaceDecl *OI,
836 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000837 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
838 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000839 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000840 if (!IVDecl->isInvalidDecl())
841 Fields.push_back(cast<FieldDecl>(IVDecl));
842 }
843}
844
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000845void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
846 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
847 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
848 CollectObjCIvars(SuperClass, Fields);
849 CollectLocalObjCIvars(this, OI, Fields);
850}
851
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000852/// ShallowCollectObjCIvars -
853/// Collect all ivars, including those synthesized, in the current class.
854///
855void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000856 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000857 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
858 E = OI->ivar_end(); I != E; ++I) {
859 Ivars.push_back(*I);
860 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000861
862 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000863}
864
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000865/// CollectNonClassIvars -
866/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000867/// This includes synthesized ivars (via @synthesize) and those in
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000868// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000869///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000870void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000871 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000872 // Find ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000873 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
874 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000875 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
876 E = CDecl->ivar_end(); I != E; ++I) {
877 Ivars.push_back(*I);
878 }
879 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000880
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000881 // Also add any ivar defined in this class's implementation. This
882 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000883 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
884 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
885 E = ImplDecl->ivar_end(); I != E; ++I)
886 Ivars.push_back(*I);
887 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000888}
889
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000890/// CollectInheritedProtocols - Collect all protocols in current class and
891/// those inherited by it.
892void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000893 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000894 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
895 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
896 PE = OI->protocol_end(); P != PE; ++P) {
897 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000898 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000899 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000900 PE = Proto->protocol_end(); P != PE; ++P) {
901 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000902 CollectInheritedProtocols(*P, Protocols);
903 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000904 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000905
906 // Categories of this Interface.
907 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
908 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
909 CollectInheritedProtocols(CDeclChain, Protocols);
910 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
911 while (SD) {
912 CollectInheritedProtocols(SD, Protocols);
913 SD = SD->getSuperClass();
914 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000915 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000916 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
917 PE = OC->protocol_end(); P != PE; ++P) {
918 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000919 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000920 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
921 PE = Proto->protocol_end(); P != PE; ++P)
922 CollectInheritedProtocols(*P, Protocols);
923 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000924 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000925 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
926 PE = OP->protocol_end(); P != PE; ++P) {
927 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000928 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000929 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
930 PE = Proto->protocol_end(); P != PE; ++P)
931 CollectInheritedProtocols(*P, Protocols);
932 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000933 }
934}
935
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000936unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
937 unsigned count = 0;
938 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000939 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
940 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000941 count += CDecl->ivar_size();
942
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000943 // Count ivar defined in this class's implementation. This
944 // includes synthesized ivars.
945 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000946 count += ImplDecl->ivar_size();
947
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000948 return count;
949}
950
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000951/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
952ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
953 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
954 I = ObjCImpls.find(D);
955 if (I != ObjCImpls.end())
956 return cast<ObjCImplementationDecl>(I->second);
957 return 0;
958}
959/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
960ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
961 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
962 I = ObjCImpls.find(D);
963 if (I != ObjCImpls.end())
964 return cast<ObjCCategoryImplDecl>(I->second);
965 return 0;
966}
967
968/// \brief Set the implementation of ObjCInterfaceDecl.
969void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
970 ObjCImplementationDecl *ImplD) {
971 assert(IFaceD && ImplD && "Passed null params");
972 ObjCImpls[IFaceD] = ImplD;
973}
974/// \brief Set the implementation of ObjCCategoryDecl.
975void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
976 ObjCCategoryImplDecl *ImplD) {
977 assert(CatD && ImplD && "Passed null params");
978 ObjCImpls[CatD] = ImplD;
979}
980
John McCalla93c9342009-12-07 02:54:59 +0000981/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000982///
John McCalla93c9342009-12-07 02:54:59 +0000983/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000984/// the TypeLoc wrappers.
985///
986/// \param T the type that will be the basis for type source info. This type
987/// should refer to how the declarator was written in source code, not to
988/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000989TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000990 unsigned DataSize) {
991 if (!DataSize)
992 DataSize = TypeLoc::getFullDataSizeForType(T);
993 else
994 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +0000995 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +0000996
John McCalla93c9342009-12-07 02:54:59 +0000997 TypeSourceInfo *TInfo =
998 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
999 new (TInfo) TypeSourceInfo(T);
1000 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001001}
1002
John McCalla93c9342009-12-07 02:54:59 +00001003TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001004 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001005 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001006 DI->getTypeLoc().initialize(L);
1007 return DI;
1008}
1009
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001010const ASTRecordLayout &
1011ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1012 return getObjCLayout(D, 0);
1013}
1014
1015const ASTRecordLayout &
1016ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1017 return getObjCLayout(D->getClassInterface(), D);
1018}
1019
Chris Lattnera7674d82007-07-13 22:13:22 +00001020//===----------------------------------------------------------------------===//
1021// Type creation/memoization methods
1022//===----------------------------------------------------------------------===//
1023
John McCall0953e762009-09-24 19:53:00 +00001024QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1025 unsigned Fast = Quals.getFastQualifiers();
1026 Quals.removeFastQualifiers();
1027
1028 // Check if we've already instantiated this type.
1029 llvm::FoldingSetNodeID ID;
1030 ExtQuals::Profile(ID, TypeNode, Quals);
1031 void *InsertPos = 0;
1032 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1033 assert(EQ->getQualifiers() == Quals);
1034 QualType T = QualType(EQ, Fast);
1035 return T;
1036 }
1037
John McCall6b304a02009-09-24 23:30:46 +00001038 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001039 ExtQualNodes.InsertNode(New, InsertPos);
1040 QualType T = QualType(New, Fast);
1041 return T;
1042}
1043
1044QualType ASTContext::getVolatileType(QualType T) {
1045 QualType CanT = getCanonicalType(T);
1046 if (CanT.isVolatileQualified()) return T;
1047
1048 QualifierCollector Quals;
1049 const Type *TypeNode = Quals.strip(T);
1050 Quals.addVolatile();
1051
1052 return getExtQualType(TypeNode, Quals);
1053}
1054
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001055QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001056 QualType CanT = getCanonicalType(T);
1057 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001058 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001059
John McCall0953e762009-09-24 19:53:00 +00001060 // If we are composing extended qualifiers together, merge together
1061 // into one ExtQuals node.
1062 QualifierCollector Quals;
1063 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001064
John McCall0953e762009-09-24 19:53:00 +00001065 // If this type already has an address space specified, it cannot get
1066 // another one.
1067 assert(!Quals.hasAddressSpace() &&
1068 "Type cannot be in multiple addr spaces!");
1069 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
John McCall0953e762009-09-24 19:53:00 +00001071 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001072}
1073
Chris Lattnerb7d25532009-02-18 22:53:11 +00001074QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001075 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001076 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001077 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001078 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001080 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001081 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001082 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001083 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1084 return getPointerType(ResultType);
1085 }
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
John McCall0953e762009-09-24 19:53:00 +00001088 // If we are composing extended qualifiers together, merge together
1089 // into one ExtQuals node.
1090 QualifierCollector Quals;
1091 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001092
John McCall0953e762009-09-24 19:53:00 +00001093 // If this type already has an ObjCGC specified, it cannot get
1094 // another one.
1095 assert(!Quals.hasObjCGCAttr() &&
1096 "Type cannot have multiple ObjCGCs!");
1097 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001098
John McCall0953e762009-09-24 19:53:00 +00001099 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001100}
Chris Lattnera7674d82007-07-13 22:13:22 +00001101
Rafael Espindola264ba482010-03-30 20:24:48 +00001102static QualType getExtFunctionType(ASTContext& Context, QualType T,
1103 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001104 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001105 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1106 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001107 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001108 if (ResultType == Pointee)
1109 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001110
1111 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001112 } else if (const BlockPointerType *BlockPointer
1113 = T->getAs<BlockPointerType>()) {
1114 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001115 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001116 if (ResultType == Pointee)
1117 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001118
1119 ResultType = Context.getBlockPointerType(ResultType);
1120 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001121 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001122 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001123
Douglas Gregor43c79c22009-12-09 00:47:37 +00001124 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001125 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001126 Info);
John McCall0953e762009-09-24 19:53:00 +00001127 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001128 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001129 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001130 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1131 FPT->getNumArgs(), FPT->isVariadic(),
1132 FPT->getTypeQuals(),
1133 FPT->hasExceptionSpec(),
1134 FPT->hasAnyExceptionSpec(),
1135 FPT->getNumExceptions(),
1136 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001137 Info);
John McCall0953e762009-09-24 19:53:00 +00001138 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001139 } else
1140 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001141
1142 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1143}
1144
1145QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001146 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001147 return getExtFunctionType(*this, T,
1148 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001149}
1150
1151QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001152 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001153 return getExtFunctionType(*this, T,
1154 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001155}
1156
Rafael Espindola425ef722010-03-30 22:15:11 +00001157QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1158 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1159 return getExtFunctionType(*this, T,
1160 Info.withRegParm(RegParm));
1161}
1162
Reid Spencer5f016e22007-07-11 17:01:13 +00001163/// getComplexType - Return the uniqued reference to the type for a complex
1164/// number with the specified element type.
1165QualType ASTContext::getComplexType(QualType T) {
1166 // Unique pointers, to guarantee there is only one pointer of a particular
1167 // structure.
1168 llvm::FoldingSetNodeID ID;
1169 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 void *InsertPos = 0;
1172 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1173 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 // If the pointee type isn't canonical, this won't be a canonical type either,
1176 // so fill in the canonical type field.
1177 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001178 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001179 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 // Get the new insert position for the node we care about.
1182 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001183 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 }
John McCall6b304a02009-09-24 23:30:46 +00001185 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 Types.push_back(New);
1187 ComplexTypes.InsertNode(New, InsertPos);
1188 return QualType(New, 0);
1189}
1190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191/// getPointerType - Return the uniqued reference to the type for a pointer to
1192/// the specified type.
1193QualType ASTContext::getPointerType(QualType T) {
1194 // Unique pointers, to guarantee there is only one pointer of a particular
1195 // structure.
1196 llvm::FoldingSetNodeID ID;
1197 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 void *InsertPos = 0;
1200 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1201 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 // If the pointee type isn't canonical, this won't be a canonical type either,
1204 // so fill in the canonical type field.
1205 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001206 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001207 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 // Get the new insert position for the node we care about.
1210 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001211 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 }
John McCall6b304a02009-09-24 23:30:46 +00001213 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 Types.push_back(New);
1215 PointerTypes.InsertNode(New, InsertPos);
1216 return QualType(New, 0);
1217}
1218
Mike Stump1eb44332009-09-09 15:08:12 +00001219/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001220/// a pointer to the specified block.
1221QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001222 assert(T->isFunctionType() && "block of function types only");
1223 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001224 // structure.
1225 llvm::FoldingSetNodeID ID;
1226 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Steve Naroff5618bd42008-08-27 16:04:49 +00001228 void *InsertPos = 0;
1229 if (BlockPointerType *PT =
1230 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1231 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
1233 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001234 // type either so fill in the canonical type field.
1235 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001236 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001237 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Steve Naroff5618bd42008-08-27 16:04:49 +00001239 // Get the new insert position for the node we care about.
1240 BlockPointerType *NewIP =
1241 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001242 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001243 }
John McCall6b304a02009-09-24 23:30:46 +00001244 BlockPointerType *New
1245 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001246 Types.push_back(New);
1247 BlockPointerTypes.InsertNode(New, InsertPos);
1248 return QualType(New, 0);
1249}
1250
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001251/// getLValueReferenceType - Return the uniqued reference to the type for an
1252/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001253QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // Unique pointers, to guarantee there is only one pointer of a particular
1255 // structure.
1256 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001257 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001258
1259 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001260 if (LValueReferenceType *RT =
1261 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001263
John McCall54e14c42009-10-22 22:37:11 +00001264 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 // If the referencee type isn't canonical, this won't be a canonical type
1267 // either, so fill in the canonical type field.
1268 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001269 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1270 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1271 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001274 LValueReferenceType *NewIP =
1275 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001276 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 }
1278
John McCall6b304a02009-09-24 23:30:46 +00001279 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001280 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1281 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001283 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001284
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001285 return QualType(New, 0);
1286}
1287
1288/// getRValueReferenceType - Return the uniqued reference to the type for an
1289/// rvalue reference to the specified type.
1290QualType ASTContext::getRValueReferenceType(QualType T) {
1291 // Unique pointers, to guarantee there is only one pointer of a particular
1292 // structure.
1293 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001294 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001295
1296 void *InsertPos = 0;
1297 if (RValueReferenceType *RT =
1298 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1299 return QualType(RT, 0);
1300
John McCall54e14c42009-10-22 22:37:11 +00001301 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1302
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303 // If the referencee type isn't canonical, this won't be a canonical type
1304 // either, so fill in the canonical type field.
1305 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001306 if (InnerRef || !T.isCanonical()) {
1307 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1308 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001309
1310 // Get the new insert position for the node we care about.
1311 RValueReferenceType *NewIP =
1312 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1313 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1314 }
1315
John McCall6b304a02009-09-24 23:30:46 +00001316 RValueReferenceType *New
1317 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001318 Types.push_back(New);
1319 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 return QualType(New, 0);
1321}
1322
Sebastian Redlf30208a2009-01-24 21:16:55 +00001323/// getMemberPointerType - Return the uniqued reference to the type for a
1324/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001325QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001326 // Unique pointers, to guarantee there is only one pointer of a particular
1327 // structure.
1328 llvm::FoldingSetNodeID ID;
1329 MemberPointerType::Profile(ID, T, Cls);
1330
1331 void *InsertPos = 0;
1332 if (MemberPointerType *PT =
1333 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1334 return QualType(PT, 0);
1335
1336 // If the pointee or class type isn't canonical, this won't be a canonical
1337 // type either, so fill in the canonical type field.
1338 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001339 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001340 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1341
1342 // Get the new insert position for the node we care about.
1343 MemberPointerType *NewIP =
1344 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1345 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1346 }
John McCall6b304a02009-09-24 23:30:46 +00001347 MemberPointerType *New
1348 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001349 Types.push_back(New);
1350 MemberPointerTypes.InsertNode(New, InsertPos);
1351 return QualType(New, 0);
1352}
1353
Mike Stump1eb44332009-09-09 15:08:12 +00001354/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001355/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001356QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001357 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001358 ArrayType::ArraySizeModifier ASM,
1359 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001360 assert((EltTy->isDependentType() ||
1361 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001362 "Constant array of VLAs is illegal!");
1363
Chris Lattner38aeec72009-05-13 04:12:56 +00001364 // Convert the array size into a canonical width matching the pointer size for
1365 // the target.
1366 llvm::APInt ArySize(ArySizeIn);
1367 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001370 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001373 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001374 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // If the element type isn't canonical, this won't be a canonical type either,
1378 // so fill in the canonical type field.
1379 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001380 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001381 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001382 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001384 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001385 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001386 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
John McCall6b304a02009-09-24 23:30:46 +00001389 ConstantArrayType *New = new(*this,TypeAlignment)
1390 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001391 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 Types.push_back(New);
1393 return QualType(New, 0);
1394}
1395
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001396/// getVariableArrayType - Returns a non-unique reference to the type for a
1397/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001398QualType ASTContext::getVariableArrayType(QualType EltTy,
1399 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001400 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001401 unsigned EltTypeQuals,
1402 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001403 // Since we don't unique expressions, it isn't possible to unique VLA's
1404 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001405 QualType CanonType;
1406
1407 if (!EltTy.isCanonical()) {
1408 if (NumElts)
1409 NumElts->Retain();
1410 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1411 EltTypeQuals, Brackets);
1412 }
1413
John McCall6b304a02009-09-24 23:30:46 +00001414 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001415 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001416
1417 VariableArrayTypes.push_back(New);
1418 Types.push_back(New);
1419 return QualType(New, 0);
1420}
1421
Douglas Gregor898574e2008-12-05 23:32:09 +00001422/// getDependentSizedArrayType - Returns a non-unique reference to
1423/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001424/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001425QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1426 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001427 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001428 unsigned EltTypeQuals,
1429 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001430 assert((!NumElts || NumElts->isTypeDependent() ||
1431 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001432 "Size must be type- or value-dependent!");
1433
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001434 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001435 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001436 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001437
1438 if (NumElts) {
1439 // Dependently-sized array types that do not have a specified
1440 // number of elements will have their sizes deduced from an
1441 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001442 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1443 EltTypeQuals, NumElts);
1444
1445 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1446 }
1447
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001448 DependentSizedArrayType *New;
1449 if (Canon) {
1450 // We already have a canonical version of this array type; use it as
1451 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001452 New = new (*this, TypeAlignment)
1453 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1454 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001455 } else {
1456 QualType CanonEltTy = getCanonicalType(EltTy);
1457 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001458 New = new (*this, TypeAlignment)
1459 DependentSizedArrayType(*this, EltTy, QualType(),
1460 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001461
Douglas Gregor789b1f62010-02-04 18:10:26 +00001462 if (NumElts) {
1463 DependentSizedArrayType *CanonCheck
1464 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1465 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1466 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001467 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001468 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001469 } else {
1470 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1471 ASM, EltTypeQuals,
1472 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001473 New = new (*this, TypeAlignment)
1474 DependentSizedArrayType(*this, EltTy, Canon,
1475 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001476 }
1477 }
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Douglas Gregor898574e2008-12-05 23:32:09 +00001479 Types.push_back(New);
1480 return QualType(New, 0);
1481}
1482
Eli Friedmanc5773c42008-02-15 18:16:39 +00001483QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1484 ArrayType::ArraySizeModifier ASM,
1485 unsigned EltTypeQuals) {
1486 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001487 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001488
1489 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001490 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001491 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1492 return QualType(ATP, 0);
1493
1494 // If the element type isn't canonical, this won't be a canonical type
1495 // either, so fill in the canonical type field.
1496 QualType Canonical;
1497
John McCall467b27b2009-10-22 20:10:53 +00001498 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001499 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001500 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001501
1502 // Get the new insert position for the node we care about.
1503 IncompleteArrayType *NewIP =
1504 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001505 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001506 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001507
John McCall6b304a02009-09-24 23:30:46 +00001508 IncompleteArrayType *New = new (*this, TypeAlignment)
1509 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001510
1511 IncompleteArrayTypes.InsertNode(New, InsertPos);
1512 Types.push_back(New);
1513 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001514}
1515
Steve Naroff73322922007-07-18 18:00:27 +00001516/// getVectorType - Return the unique reference to a vector type of
1517/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001518QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001519 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Chris Lattnerf52ab252008-04-06 22:59:24 +00001522 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001523 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Check if we've already instantiated a vector of this type.
1526 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001527 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1528
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 void *InsertPos = 0;
1530 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1531 return QualType(VTP, 0);
1532
1533 // If the element type isn't canonical, this won't be a canonical type either,
1534 // so fill in the canonical type field.
1535 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001536 if (!vecType.isCanonical()) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00001537 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1538 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 // Get the new insert position for the node we care about.
1541 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001542 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 }
John McCall6b304a02009-09-24 23:30:46 +00001544 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001545 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 VectorTypes.InsertNode(New, InsertPos);
1547 Types.push_back(New);
1548 return QualType(New, 0);
1549}
1550
Nate Begeman213541a2008-04-18 23:10:10 +00001551/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001552/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001553QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001554 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Chris Lattnerf52ab252008-04-06 22:59:24 +00001556 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001557 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Steve Naroff73322922007-07-18 18:00:27 +00001559 // Check if we've already instantiated a vector of this type.
1560 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001561 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1562 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001563 void *InsertPos = 0;
1564 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1565 return QualType(VTP, 0);
1566
1567 // If the element type isn't canonical, this won't be a canonical type either,
1568 // so fill in the canonical type field.
1569 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001570 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001571 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Steve Naroff73322922007-07-18 18:00:27 +00001573 // Get the new insert position for the node we care about.
1574 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001575 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001576 }
John McCall6b304a02009-09-24 23:30:46 +00001577 ExtVectorType *New = new (*this, TypeAlignment)
1578 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001579 VectorTypes.InsertNode(New, InsertPos);
1580 Types.push_back(New);
1581 return QualType(New, 0);
1582}
1583
Mike Stump1eb44332009-09-09 15:08:12 +00001584QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001585 Expr *SizeExpr,
1586 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001587 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001588 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001589 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001591 void *InsertPos = 0;
1592 DependentSizedExtVectorType *Canon
1593 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1594 DependentSizedExtVectorType *New;
1595 if (Canon) {
1596 // We already have a canonical version of this array type; use it as
1597 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001598 New = new (*this, TypeAlignment)
1599 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1600 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001601 } else {
1602 QualType CanonVecTy = getCanonicalType(vecType);
1603 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001604 New = new (*this, TypeAlignment)
1605 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1606 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001607
1608 DependentSizedExtVectorType *CanonCheck
1609 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1610 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1611 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001612 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1613 } else {
1614 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1615 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001616 New = new (*this, TypeAlignment)
1617 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001618 }
1619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001621 Types.push_back(New);
1622 return QualType(New, 0);
1623}
1624
Douglas Gregor72564e72009-02-26 23:50:07 +00001625/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001626///
Rafael Espindola264ba482010-03-30 20:24:48 +00001627QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1628 const FunctionType::ExtInfo &Info) {
1629 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // Unique functions, to guarantee there is only one function of a particular
1631 // structure.
1632 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001633 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001636 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001637 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001641 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001642 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001643 Canonical =
1644 getFunctionNoProtoType(getCanonicalType(ResultTy),
1645 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001648 FunctionNoProtoType *NewIP =
1649 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001650 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 }
Mike Stump1eb44332009-09-09 15:08:12 +00001652
John McCall6b304a02009-09-24 23:30:46 +00001653 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001654 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001656 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 return QualType(New, 0);
1658}
1659
1660/// getFunctionType - Return a normal function type with a typed argument
1661/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001662QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001663 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001664 unsigned TypeQuals, bool hasExceptionSpec,
1665 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001666 const QualType *ExArray,
1667 const FunctionType::ExtInfo &Info) {
1668 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 // Unique functions, to guarantee there is only one function of a particular
1670 // structure.
1671 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001672 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001673 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001674 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001675
1676 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001677 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001678 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001680
1681 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001682 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001684 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 isCanonical = false;
1686
1687 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001688 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001690 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 llvm::SmallVector<QualType, 16> CanonicalArgs;
1692 CanonicalArgs.reserve(NumArgs);
1693 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001694 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001695
Chris Lattnerf52ab252008-04-06 22:59:24 +00001696 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001697 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001698 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001699 false, 0, 0,
1700 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001701
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001703 FunctionProtoType *NewIP =
1704 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001705 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001707
Douglas Gregor72564e72009-02-26 23:50:07 +00001708 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001709 // for two variable size arrays (for parameter and exception types) at the
1710 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001711 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001712 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1713 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001714 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001715 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001716 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001717 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001719 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 return QualType(FTP, 0);
1721}
1722
John McCall3cb0ebd2010-03-10 03:28:59 +00001723#ifndef NDEBUG
1724static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1725 if (!isa<CXXRecordDecl>(D)) return false;
1726 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1727 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1728 return true;
1729 if (RD->getDescribedClassTemplate() &&
1730 !isa<ClassTemplateSpecializationDecl>(RD))
1731 return true;
1732 return false;
1733}
1734#endif
1735
1736/// getInjectedClassNameType - Return the unique reference to the
1737/// injected class name type for the specified templated declaration.
1738QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1739 QualType TST) {
1740 assert(NeedsInjectedClassNameType(Decl));
1741 if (Decl->TypeForDecl) {
1742 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001743 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001744 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1745 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1746 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1747 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001748 Decl->TypeForDecl =
1749 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001750 Types.push_back(Decl->TypeForDecl);
1751 }
1752 return QualType(Decl->TypeForDecl, 0);
1753}
1754
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001755/// getTypeDeclType - Return the unique reference to the type for the
1756/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001757QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001758 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001759 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001760
John McCall19c85762010-02-16 03:57:14 +00001761 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001762 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001763
John McCallbecb8d52010-03-10 06:48:02 +00001764 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1765 "Template type parameter types are always available.");
1766
John McCall19c85762010-02-16 03:57:14 +00001767 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001768 assert(!Record->getPreviousDeclaration() &&
1769 "struct/union has previous declaration");
1770 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001771 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001772 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001773 assert(!Enum->getPreviousDeclaration() &&
1774 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001775 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001776 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001777 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1778 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001779 } else
John McCallbecb8d52010-03-10 06:48:02 +00001780 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001781
John McCallbecb8d52010-03-10 06:48:02 +00001782 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001783 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001784}
1785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786/// getTypedefType - Return the unique reference to the type for the
1787/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001788QualType
1789ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001792 if (Canonical.isNull())
1793 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001794 Decl->TypeForDecl = new(*this, TypeAlignment)
1795 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 Types.push_back(Decl->TypeForDecl);
1797 return QualType(Decl->TypeForDecl, 0);
1798}
1799
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001800QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1801 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1802
1803 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1804 if (PrevDecl->TypeForDecl)
1805 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1806
1807 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1808 Types.push_back(Decl->TypeForDecl);
1809 return QualType(Decl->TypeForDecl, 0);
1810}
1811
1812QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1813 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1814
1815 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1816 if (PrevDecl->TypeForDecl)
1817 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1818
1819 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1820 Types.push_back(Decl->TypeForDecl);
1821 return QualType(Decl->TypeForDecl, 0);
1822}
1823
John McCall49a832b2009-10-18 09:09:24 +00001824/// \brief Retrieve a substitution-result type.
1825QualType
1826ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1827 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001828 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001829 && "replacement types must always be canonical");
1830
1831 llvm::FoldingSetNodeID ID;
1832 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1833 void *InsertPos = 0;
1834 SubstTemplateTypeParmType *SubstParm
1835 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1836
1837 if (!SubstParm) {
1838 SubstParm = new (*this, TypeAlignment)
1839 SubstTemplateTypeParmType(Parm, Replacement);
1840 Types.push_back(SubstParm);
1841 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1842 }
1843
1844 return QualType(SubstParm, 0);
1845}
1846
Douglas Gregorfab9d672009-02-05 23:33:38 +00001847/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001848/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001849/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001850QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001851 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001852 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001853 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001854 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001855 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001856 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001857 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1858
1859 if (TypeParm)
1860 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Douglas Gregorefed5c82010-06-16 15:23:05 +00001862 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001863 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001864 TypeParm = new (*this, TypeAlignment)
1865 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001866
1867 TemplateTypeParmType *TypeCheck
1868 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1869 assert(!TypeCheck && "Template type parameter canonical type broken");
1870 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001871 } else
John McCall6b304a02009-09-24 23:30:46 +00001872 TypeParm = new (*this, TypeAlignment)
1873 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001874
1875 Types.push_back(TypeParm);
1876 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1877
1878 return QualType(TypeParm, 0);
1879}
1880
John McCall3cb0ebd2010-03-10 03:28:59 +00001881TypeSourceInfo *
1882ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1883 SourceLocation NameLoc,
1884 const TemplateArgumentListInfo &Args,
1885 QualType CanonType) {
1886 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1887
1888 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1889 TemplateSpecializationTypeLoc TL
1890 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1891 TL.setTemplateNameLoc(NameLoc);
1892 TL.setLAngleLoc(Args.getLAngleLoc());
1893 TL.setRAngleLoc(Args.getRAngleLoc());
1894 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1895 TL.setArgLocInfo(i, Args[i].getLocInfo());
1896 return DI;
1897}
1898
Mike Stump1eb44332009-09-09 15:08:12 +00001899QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001900ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001901 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001902 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001903 unsigned NumArgs = Args.size();
1904
John McCall833ca992009-10-29 08:12:44 +00001905 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1906 ArgVec.reserve(NumArgs);
1907 for (unsigned i = 0; i != NumArgs; ++i)
1908 ArgVec.push_back(Args[i].getArgument());
1909
John McCall31f17ec2010-04-27 00:57:59 +00001910 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001911 Canon);
John McCall833ca992009-10-29 08:12:44 +00001912}
1913
1914QualType
1915ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001916 const TemplateArgument *Args,
1917 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001918 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001919 if (!Canon.isNull())
1920 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001921 else
1922 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001923
Douglas Gregor1275ae02009-07-28 23:00:59 +00001924 // Allocate the (non-canonical) template specialization type, but don't
1925 // try to unique it: these types typically have location information that
1926 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001927 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001928 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001929 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001930 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001931 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001932 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001933 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregor55f6b142009-02-09 18:46:07 +00001935 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001936 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001937}
1938
Mike Stump1eb44332009-09-09 15:08:12 +00001939QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001940ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1941 const TemplateArgument *Args,
1942 unsigned NumArgs) {
1943 // Build the canonical template specialization type.
1944 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1945 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1946 CanonArgs.reserve(NumArgs);
1947 for (unsigned I = 0; I != NumArgs; ++I)
1948 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1949
1950 // Determine whether this canonical template specialization type already
1951 // exists.
1952 llvm::FoldingSetNodeID ID;
1953 TemplateSpecializationType::Profile(ID, CanonTemplate,
1954 CanonArgs.data(), NumArgs, *this);
1955
1956 void *InsertPos = 0;
1957 TemplateSpecializationType *Spec
1958 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1959
1960 if (!Spec) {
1961 // Allocate a new canonical template specialization type.
1962 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1963 sizeof(TemplateArgument) * NumArgs),
1964 TypeAlignment);
1965 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1966 CanonArgs.data(), NumArgs,
1967 QualType());
1968 Types.push_back(Spec);
1969 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1970 }
1971
1972 assert(Spec->isDependentType() &&
1973 "Non-dependent template-id type must have a canonical type");
1974 return QualType(Spec, 0);
1975}
1976
1977QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001978ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1979 NestedNameSpecifier *NNS,
1980 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001981 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001982 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001983
1984 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001985 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001986 if (T)
1987 return QualType(T, 0);
1988
Douglas Gregor789b1f62010-02-04 18:10:26 +00001989 QualType Canon = NamedType;
1990 if (!Canon.isCanonical()) {
1991 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001992 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1993 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001994 (void)CheckT;
1995 }
1996
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001997 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001998 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001999 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002000 return QualType(T, 0);
2001}
2002
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002003QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2004 NestedNameSpecifier *NNS,
2005 const IdentifierInfo *Name,
2006 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002007 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2008
2009 if (Canon.isNull()) {
2010 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002011 ElaboratedTypeKeyword CanonKeyword = Keyword;
2012 if (Keyword == ETK_None)
2013 CanonKeyword = ETK_Typename;
2014
2015 if (CanonNNS != NNS || CanonKeyword != Keyword)
2016 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002017 }
2018
2019 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002020 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002021
2022 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002023 DependentNameType *T
2024 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002025 if (T)
2026 return QualType(T, 0);
2027
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002028 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002029 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002030 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002031 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002032}
2033
Mike Stump1eb44332009-09-09 15:08:12 +00002034QualType
John McCall33500952010-06-11 00:33:02 +00002035ASTContext::getDependentTemplateSpecializationType(
2036 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002037 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002038 const IdentifierInfo *Name,
2039 const TemplateArgumentListInfo &Args) {
2040 // TODO: avoid this copy
2041 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2042 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2043 ArgCopy.push_back(Args[I].getArgument());
2044 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2045 ArgCopy.size(),
2046 ArgCopy.data());
2047}
2048
2049QualType
2050ASTContext::getDependentTemplateSpecializationType(
2051 ElaboratedTypeKeyword Keyword,
2052 NestedNameSpecifier *NNS,
2053 const IdentifierInfo *Name,
2054 unsigned NumArgs,
2055 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002056 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2057
Douglas Gregor789b1f62010-02-04 18:10:26 +00002058 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002059 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2060 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002061
2062 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002063 DependentTemplateSpecializationType *T
2064 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002065 if (T)
2066 return QualType(T, 0);
2067
John McCall33500952010-06-11 00:33:02 +00002068 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002069
John McCall33500952010-06-11 00:33:02 +00002070 ElaboratedTypeKeyword CanonKeyword = Keyword;
2071 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2072
2073 bool AnyNonCanonArgs = false;
2074 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2075 for (unsigned I = 0; I != NumArgs; ++I) {
2076 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2077 if (!CanonArgs[I].structurallyEquals(Args[I]))
2078 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002079 }
2080
John McCall33500952010-06-11 00:33:02 +00002081 QualType Canon;
2082 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2083 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2084 Name, NumArgs,
2085 CanonArgs.data());
2086
2087 // Find the insert position again.
2088 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2089 }
2090
2091 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2092 sizeof(TemplateArgument) * NumArgs),
2093 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002094 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002095 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002096 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002097 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002098 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002099}
2100
Chris Lattner88cb27a2008-04-07 04:56:42 +00002101/// CmpProtocolNames - Comparison predicate for sorting protocols
2102/// alphabetically.
2103static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2104 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002105 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002106}
2107
John McCallc12c5bb2010-05-15 11:32:37 +00002108static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002109 unsigned NumProtocols) {
2110 if (NumProtocols == 0) return true;
2111
2112 for (unsigned i = 1; i != NumProtocols; ++i)
2113 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2114 return false;
2115 return true;
2116}
2117
2118static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002119 unsigned &NumProtocols) {
2120 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Chris Lattner88cb27a2008-04-07 04:56:42 +00002122 // Sort protocols, keyed by name.
2123 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2124
2125 // Remove duplicates.
2126 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2127 NumProtocols = ProtocolsEnd-Protocols;
2128}
2129
John McCallc12c5bb2010-05-15 11:32:37 +00002130QualType ASTContext::getObjCObjectType(QualType BaseType,
2131 ObjCProtocolDecl * const *Protocols,
2132 unsigned NumProtocols) {
2133 // If the base type is an interface and there aren't any protocols
2134 // to add, then the interface type will do just fine.
2135 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2136 return BaseType;
2137
2138 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002139 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002140 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002141 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002142 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2143 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002144
John McCallc12c5bb2010-05-15 11:32:37 +00002145 // Build the canonical type, which has the canonical base type and
2146 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002147 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002148 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2149 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2150 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002151 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2152 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002153 unsigned UniqueCount = NumProtocols;
2154
John McCall54e14c42009-10-22 22:37:11 +00002155 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002156 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2157 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002158 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002159 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2160 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002161 }
2162
2163 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002164 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2165 }
2166
2167 unsigned Size = sizeof(ObjCObjectTypeImpl);
2168 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2169 void *Mem = Allocate(Size, TypeAlignment);
2170 ObjCObjectTypeImpl *T =
2171 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2172
2173 Types.push_back(T);
2174 ObjCObjectTypes.InsertNode(T, InsertPos);
2175 return QualType(T, 0);
2176}
2177
2178/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2179/// the given object type.
2180QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2181 llvm::FoldingSetNodeID ID;
2182 ObjCObjectPointerType::Profile(ID, ObjectT);
2183
2184 void *InsertPos = 0;
2185 if (ObjCObjectPointerType *QT =
2186 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2187 return QualType(QT, 0);
2188
2189 // Find the canonical object type.
2190 QualType Canonical;
2191 if (!ObjectT.isCanonical()) {
2192 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2193
2194 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002195 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 }
2197
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002198 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002199 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2200 ObjCObjectPointerType *QType =
2201 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002203 Types.push_back(QType);
2204 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002205 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002206}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002207
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002208/// getObjCInterfaceType - Return the unique reference to the type for the
2209/// specified ObjC interface decl. The list of protocols is optional.
2210QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2211 if (Decl->TypeForDecl)
2212 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002214 // FIXME: redeclarations?
2215 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2216 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2217 Decl->TypeForDecl = T;
2218 Types.push_back(T);
2219 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002220}
2221
Douglas Gregor72564e72009-02-26 23:50:07 +00002222/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2223/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002224/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002225/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002226/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002227QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002228 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002229 if (tofExpr->isTypeDependent()) {
2230 llvm::FoldingSetNodeID ID;
2231 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Douglas Gregorb1975722009-07-30 23:18:24 +00002233 void *InsertPos = 0;
2234 DependentTypeOfExprType *Canon
2235 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2236 if (Canon) {
2237 // We already have a "canonical" version of an identical, dependent
2238 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002239 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002240 QualType((TypeOfExprType*)Canon, 0));
2241 }
2242 else {
2243 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002244 Canon
2245 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002246 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2247 toe = Canon;
2248 }
2249 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002250 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002251 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002252 }
Steve Naroff9752f252007-08-01 18:02:17 +00002253 Types.push_back(toe);
2254 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002255}
2256
Steve Naroff9752f252007-08-01 18:02:17 +00002257/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2258/// TypeOfType AST's. The only motivation to unique these nodes would be
2259/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002260/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002261/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002262QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002263 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002264 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002265 Types.push_back(tot);
2266 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002267}
2268
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002269/// getDecltypeForExpr - Given an expr, will return the decltype for that
2270/// expression, according to the rules in C++0x [dcl.type.simple]p4
2271static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002272 if (e->isTypeDependent())
2273 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002275 // If e is an id expression or a class member access, decltype(e) is defined
2276 // as the type of the entity named by e.
2277 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2278 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2279 return VD->getType();
2280 }
2281 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2282 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2283 return FD->getType();
2284 }
2285 // If e is a function call or an invocation of an overloaded operator,
2286 // (parentheses around e are ignored), decltype(e) is defined as the
2287 // return type of that function.
2288 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2289 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002291 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002292
2293 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002294 // defined as T&, otherwise decltype(e) is defined as T.
2295 if (e->isLvalue(Context) == Expr::LV_Valid)
2296 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002298 return T;
2299}
2300
Anders Carlsson395b4752009-06-24 19:06:50 +00002301/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2302/// DecltypeType AST's. The only motivation to unique these nodes would be
2303/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002304/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002305/// on canonical type's (which are always unique).
2306QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002307 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002308 if (e->isTypeDependent()) {
2309 llvm::FoldingSetNodeID ID;
2310 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002312 void *InsertPos = 0;
2313 DependentDecltypeType *Canon
2314 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2315 if (Canon) {
2316 // We already have a "canonical" version of an equivalent, dependent
2317 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002318 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002319 QualType((DecltypeType*)Canon, 0));
2320 }
2321 else {
2322 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002323 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002324 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2325 dt = Canon;
2326 }
2327 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002328 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002329 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002330 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002331 Types.push_back(dt);
2332 return QualType(dt, 0);
2333}
2334
Reid Spencer5f016e22007-07-11 17:01:13 +00002335/// getTagDeclType - Return the unique reference to the type for the
2336/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002337QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002338 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002339 // FIXME: What is the design on getTagDeclType when it requires casting
2340 // away const? mutable?
2341 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002342}
2343
Mike Stump1eb44332009-09-09 15:08:12 +00002344/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2345/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2346/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002347CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002348 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002349}
2350
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002351/// getSignedWCharType - Return the type of "signed wchar_t".
2352/// Used when in C++, as a GCC extension.
2353QualType ASTContext::getSignedWCharType() const {
2354 // FIXME: derive from "Target" ?
2355 return WCharTy;
2356}
2357
2358/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2359/// Used when in C++, as a GCC extension.
2360QualType ASTContext::getUnsignedWCharType() const {
2361 // FIXME: derive from "Target" ?
2362 return UnsignedIntTy;
2363}
2364
Chris Lattner8b9023b2007-07-13 03:05:23 +00002365/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2366/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2367QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002368 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002369}
2370
Chris Lattnere6327742008-04-02 05:18:44 +00002371//===----------------------------------------------------------------------===//
2372// Type Operators
2373//===----------------------------------------------------------------------===//
2374
John McCall54e14c42009-10-22 22:37:11 +00002375CanQualType ASTContext::getCanonicalParamType(QualType T) {
2376 // Push qualifiers into arrays, and then discard any remaining
2377 // qualifiers.
2378 T = getCanonicalType(T);
2379 const Type *Ty = T.getTypePtr();
2380
2381 QualType Result;
2382 if (isa<ArrayType>(Ty)) {
2383 Result = getArrayDecayedType(QualType(Ty,0));
2384 } else if (isa<FunctionType>(Ty)) {
2385 Result = getPointerType(QualType(Ty, 0));
2386 } else {
2387 Result = QualType(Ty, 0);
2388 }
2389
2390 return CanQualType::CreateUnsafe(Result);
2391}
2392
Chris Lattner77c96472008-04-06 22:41:35 +00002393/// getCanonicalType - Return the canonical (structural) type corresponding to
2394/// the specified potentially non-canonical type. The non-canonical version
2395/// of a type may have many "decorated" versions of types. Decorators can
2396/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2397/// to be free of any of these, allowing two canonical types to be compared
2398/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002399CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002400 QualifierCollector Quals;
2401 const Type *Ptr = Quals.strip(T);
2402 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002403
John McCall0953e762009-09-24 19:53:00 +00002404 // The canonical internal type will be the canonical type *except*
2405 // that we push type qualifiers down through array types.
2406
2407 // If there are no new qualifiers to push down, stop here.
2408 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002409 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002410
John McCall0953e762009-09-24 19:53:00 +00002411 // If the type qualifiers are on an array type, get the canonical
2412 // type of the array with the qualifiers applied to the element
2413 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002414 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2415 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002416 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002418 // Get the canonical version of the element with the extra qualifiers on it.
2419 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002420 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002421 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002423 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002424 return CanQualType::CreateUnsafe(
2425 getConstantArrayType(NewEltTy, CAT->getSize(),
2426 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002427 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002428 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002429 return CanQualType::CreateUnsafe(
2430 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002431 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002432
Douglas Gregor898574e2008-12-05 23:32:09 +00002433 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002434 return CanQualType::CreateUnsafe(
2435 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002436 DSAT->getSizeExpr() ?
2437 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002438 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002439 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002440 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002441
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002442 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002443 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002444 VAT->getSizeExpr() ?
2445 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002446 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002447 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002448 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002449}
2450
Chandler Carruth28e318c2009-12-29 07:16:59 +00002451QualType ASTContext::getUnqualifiedArrayType(QualType T,
2452 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002453 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002454 const ArrayType *AT = getAsArrayType(T);
2455 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002456 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002457 }
2458
Chandler Carruth28e318c2009-12-29 07:16:59 +00002459 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002460 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002461 if (Elt == UnqualElt)
2462 return T;
2463
Douglas Gregor9dadd942010-05-17 18:45:21 +00002464 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002465 return getConstantArrayType(UnqualElt, CAT->getSize(),
2466 CAT->getSizeModifier(), 0);
2467 }
2468
Douglas Gregor9dadd942010-05-17 18:45:21 +00002469 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002470 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2471 }
2472
Douglas Gregor9dadd942010-05-17 18:45:21 +00002473 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2474 return getVariableArrayType(UnqualElt,
2475 VAT->getSizeExpr() ?
2476 VAT->getSizeExpr()->Retain() : 0,
2477 VAT->getSizeModifier(),
2478 VAT->getIndexTypeCVRQualifiers(),
2479 VAT->getBracketsRange());
2480 }
2481
2482 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002483 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2484 DSAT->getSizeModifier(), 0,
2485 SourceRange());
2486}
2487
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002488/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2489/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2490/// they point to and return true. If T1 and T2 aren't pointer types
2491/// or pointer-to-member types, or if they are not similar at this
2492/// level, returns false and leaves T1 and T2 unchanged. Top-level
2493/// qualifiers on T1 and T2 are ignored. This function will typically
2494/// be called in a loop that successively "unwraps" pointer and
2495/// pointer-to-member types to compare them at each level.
2496bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2497 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2498 *T2PtrType = T2->getAs<PointerType>();
2499 if (T1PtrType && T2PtrType) {
2500 T1 = T1PtrType->getPointeeType();
2501 T2 = T2PtrType->getPointeeType();
2502 return true;
2503 }
2504
2505 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2506 *T2MPType = T2->getAs<MemberPointerType>();
2507 if (T1MPType && T2MPType &&
2508 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2509 QualType(T2MPType->getClass(), 0))) {
2510 T1 = T1MPType->getPointeeType();
2511 T2 = T2MPType->getPointeeType();
2512 return true;
2513 }
2514
2515 if (getLangOptions().ObjC1) {
2516 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2517 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2518 if (T1OPType && T2OPType) {
2519 T1 = T1OPType->getPointeeType();
2520 T2 = T2OPType->getPointeeType();
2521 return true;
2522 }
2523 }
2524
2525 // FIXME: Block pointers, too?
2526
2527 return false;
2528}
2529
Abramo Bagnara25777432010-08-11 22:01:17 +00002530DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2531 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002532 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002533 // DNInfo work in progress: CHECKME: what about DNLoc?
2534 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2535
John McCall80ad16f2009-11-24 18:42:40 +00002536 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002537 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002538 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002539 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2540 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002541 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002542 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2543 // DNInfo work in progress: FIXME: source locations?
2544 DeclarationNameLoc DNLoc;
2545 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2546 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2547 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002548 }
2549 }
2550
John McCall0bd6feb2009-12-02 08:04:21 +00002551 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2552 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002553 // DNInfo work in progress: CHECKME: what about DNLoc?
2554 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002555}
2556
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002557TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002558 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2559 if (TemplateTemplateParmDecl *TTP
2560 = dyn_cast<TemplateTemplateParmDecl>(Template))
2561 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2562
2563 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002564 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002565 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002566
John McCall0bd6feb2009-12-02 08:04:21 +00002567 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002569 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2570 assert(DTN && "Non-dependent template names must refer to template decls.");
2571 return DTN->CanonicalTemplateName;
2572}
2573
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002574bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2575 X = getCanonicalTemplateName(X);
2576 Y = getCanonicalTemplateName(Y);
2577 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2578}
2579
Mike Stump1eb44332009-09-09 15:08:12 +00002580TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002581ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2582 switch (Arg.getKind()) {
2583 case TemplateArgument::Null:
2584 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Douglas Gregor1275ae02009-07-28 23:00:59 +00002586 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002587 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Douglas Gregor1275ae02009-07-28 23:00:59 +00002589 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002590 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Douglas Gregor788cd062009-11-11 01:00:40 +00002592 case TemplateArgument::Template:
2593 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2594
Douglas Gregor1275ae02009-07-28 23:00:59 +00002595 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002596 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002597 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Douglas Gregor1275ae02009-07-28 23:00:59 +00002599 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002600 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Douglas Gregor1275ae02009-07-28 23:00:59 +00002602 case TemplateArgument::Pack: {
2603 // FIXME: Allocate in ASTContext
2604 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2605 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002606 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002607 AEnd = Arg.pack_end();
2608 A != AEnd; (void)++A, ++Idx)
2609 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Douglas Gregor1275ae02009-07-28 23:00:59 +00002611 TemplateArgument Result;
2612 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2613 return Result;
2614 }
2615 }
2616
2617 // Silence GCC warning
2618 assert(false && "Unhandled template argument kind");
2619 return TemplateArgument();
2620}
2621
Douglas Gregord57959a2009-03-27 23:10:48 +00002622NestedNameSpecifier *
2623ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002624 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002625 return 0;
2626
2627 switch (NNS->getKind()) {
2628 case NestedNameSpecifier::Identifier:
2629 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002630 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002631 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2632 NNS->getAsIdentifier());
2633
2634 case NestedNameSpecifier::Namespace:
2635 // A namespace is canonical; build a nested-name-specifier with
2636 // this namespace and no prefix.
2637 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2638
2639 case NestedNameSpecifier::TypeSpec:
2640 case NestedNameSpecifier::TypeSpecWithTemplate: {
2641 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002642 return NestedNameSpecifier::Create(*this, 0,
2643 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002644 T.getTypePtr());
2645 }
2646
2647 case NestedNameSpecifier::Global:
2648 // The global specifier is canonical and unique.
2649 return NNS;
2650 }
2651
2652 // Required to silence a GCC warning
2653 return 0;
2654}
2655
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002656
2657const ArrayType *ASTContext::getAsArrayType(QualType T) {
2658 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002659 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002660 // Handle the common positive case fast.
2661 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2662 return AT;
2663 }
Mike Stump1eb44332009-09-09 15:08:12 +00002664
John McCall0953e762009-09-24 19:53:00 +00002665 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002666 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002667 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002668 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002669
John McCall0953e762009-09-24 19:53:00 +00002670 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002671 // implements C99 6.7.3p8: "If the specification of an array type includes
2672 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002674 // If we get here, we either have type qualifiers on the type, or we have
2675 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002676 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002677
John McCall0953e762009-09-24 19:53:00 +00002678 QualifierCollector Qs;
2679 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002681 // If we have a simple case, just return now.
2682 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002683 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002684 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002686 // Otherwise, we have an array and we have qualifiers on it. Push the
2687 // qualifiers into the array element type and return a new array type.
2688 // Get the canonical version of the element with the extra qualifiers on it.
2689 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002690 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002692 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2693 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2694 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002695 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002696 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2697 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2698 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002699 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002700
Mike Stump1eb44332009-09-09 15:08:12 +00002701 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002702 = dyn_cast<DependentSizedArrayType>(ATy))
2703 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002704 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002705 DSAT->getSizeExpr() ?
2706 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002707 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002708 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002709 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002711 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002712 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002713 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002714 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002715 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002716 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002717 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002718}
2719
2720
Chris Lattnere6327742008-04-02 05:18:44 +00002721/// getArrayDecayedType - Return the properly qualified result of decaying the
2722/// specified array type to a pointer. This operation is non-trivial when
2723/// handling typedefs etc. The canonical type of "T" must be an array type,
2724/// this returns a pointer to a properly qualified element of the array.
2725///
2726/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2727QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002728 // Get the element type with 'getAsArrayType' so that we don't lose any
2729 // typedefs in the element type of the array. This also handles propagation
2730 // of type qualifiers from the array type into the element type if present
2731 // (C99 6.7.3p8).
2732 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2733 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002735 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002736
2737 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002738 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002739}
2740
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002741QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002742 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002743 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2744 QT = AT->getElementType();
2745 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002746}
2747
Anders Carlssonfbbce492009-09-25 01:23:32 +00002748QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2749 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Anders Carlssonfbbce492009-09-25 01:23:32 +00002751 if (const ArrayType *AT = getAsArrayType(ElemTy))
2752 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Anders Carlsson6183a992008-12-21 03:44:36 +00002754 return ElemTy;
2755}
2756
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002757/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002758uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002759ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2760 uint64_t ElementCount = 1;
2761 do {
2762 ElementCount *= CA->getSize().getZExtValue();
2763 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2764 } while (CA);
2765 return ElementCount;
2766}
2767
Reid Spencer5f016e22007-07-11 17:01:13 +00002768/// getFloatingRank - Return a relative rank for floating point types.
2769/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002770static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002771 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002773
John McCall183700f2009-09-21 23:43:11 +00002774 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2775 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002776 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 case BuiltinType::Float: return FloatRank;
2778 case BuiltinType::Double: return DoubleRank;
2779 case BuiltinType::LongDouble: return LongDoubleRank;
2780 }
2781}
2782
Mike Stump1eb44332009-09-09 15:08:12 +00002783/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2784/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002785/// 'typeDomain' is a real floating point or complex type.
2786/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002787QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2788 QualType Domain) const {
2789 FloatingRank EltRank = getFloatingRank(Size);
2790 if (Domain->isComplexType()) {
2791 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002792 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002793 case FloatRank: return FloatComplexTy;
2794 case DoubleRank: return DoubleComplexTy;
2795 case LongDoubleRank: return LongDoubleComplexTy;
2796 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 }
Chris Lattner1361b112008-04-06 23:58:54 +00002798
2799 assert(Domain->isRealFloatingType() && "Unknown domain!");
2800 switch (EltRank) {
2801 default: assert(0 && "getFloatingRank(): illegal value for rank");
2802 case FloatRank: return FloatTy;
2803 case DoubleRank: return DoubleTy;
2804 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002805 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002806}
2807
Chris Lattner7cfeb082008-04-06 23:55:33 +00002808/// getFloatingTypeOrder - Compare the rank of the two specified floating
2809/// point types, ignoring the domain of the type (i.e. 'double' ==
2810/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002811/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002812int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2813 FloatingRank LHSR = getFloatingRank(LHS);
2814 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Chris Lattnera75cea32008-04-06 23:38:49 +00002816 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002817 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002818 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002819 return 1;
2820 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002821}
2822
Chris Lattnerf52ab252008-04-06 22:59:24 +00002823/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2824/// routine will assert if passed a built-in type that isn't an integer or enum,
2825/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002826unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002827 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002828 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002829 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002830
Eli Friedmana3426752009-07-05 23:44:27 +00002831 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2832 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2833
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002834 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2835 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2836
2837 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2838 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2839
Chris Lattnerf52ab252008-04-06 22:59:24 +00002840 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002841 default: assert(0 && "getIntegerRank(): not a built-in integer");
2842 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002843 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002844 case BuiltinType::Char_S:
2845 case BuiltinType::Char_U:
2846 case BuiltinType::SChar:
2847 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002848 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002849 case BuiltinType::Short:
2850 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002851 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002852 case BuiltinType::Int:
2853 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002854 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002855 case BuiltinType::Long:
2856 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002857 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002858 case BuiltinType::LongLong:
2859 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002860 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002861 case BuiltinType::Int128:
2862 case BuiltinType::UInt128:
2863 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002864 }
2865}
2866
Eli Friedman04e83572009-08-20 04:21:42 +00002867/// \brief Whether this is a promotable bitfield reference according
2868/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2869///
2870/// \returns the type this bit-field will promote to, or NULL if no
2871/// promotion occurs.
2872QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002873 if (E->isTypeDependent() || E->isValueDependent())
2874 return QualType();
2875
Eli Friedman04e83572009-08-20 04:21:42 +00002876 FieldDecl *Field = E->getBitField();
2877 if (!Field)
2878 return QualType();
2879
2880 QualType FT = Field->getType();
2881
2882 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2883 uint64_t BitWidth = BitWidthAP.getZExtValue();
2884 uint64_t IntSize = getTypeSize(IntTy);
2885 // GCC extension compatibility: if the bit-field size is less than or equal
2886 // to the size of int, it gets promoted no matter what its type is.
2887 // For instance, unsigned long bf : 4 gets promoted to signed int.
2888 if (BitWidth < IntSize)
2889 return IntTy;
2890
2891 if (BitWidth == IntSize)
2892 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2893
2894 // Types bigger than int are not subject to promotions, and therefore act
2895 // like the base type.
2896 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2897 // is ridiculous.
2898 return QualType();
2899}
2900
Eli Friedmana95d7572009-08-19 07:44:53 +00002901/// getPromotedIntegerType - Returns the type that Promotable will
2902/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2903/// integer type.
2904QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2905 assert(!Promotable.isNull());
2906 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002907 if (const EnumType *ET = Promotable->getAs<EnumType>())
2908 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002909 if (Promotable->isSignedIntegerType())
2910 return IntTy;
2911 uint64_t PromotableSize = getTypeSize(Promotable);
2912 uint64_t IntSize = getTypeSize(IntTy);
2913 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2914 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2915}
2916
Mike Stump1eb44332009-09-09 15:08:12 +00002917/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002918/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002919/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002920int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002921 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2922 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002923 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Chris Lattnerf52ab252008-04-06 22:59:24 +00002925 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2926 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Chris Lattner7cfeb082008-04-06 23:55:33 +00002928 unsigned LHSRank = getIntegerRank(LHSC);
2929 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Chris Lattner7cfeb082008-04-06 23:55:33 +00002931 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2932 if (LHSRank == RHSRank) return 0;
2933 return LHSRank > RHSRank ? 1 : -1;
2934 }
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Chris Lattner7cfeb082008-04-06 23:55:33 +00002936 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2937 if (LHSUnsigned) {
2938 // If the unsigned [LHS] type is larger, return it.
2939 if (LHSRank >= RHSRank)
2940 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Chris Lattner7cfeb082008-04-06 23:55:33 +00002942 // If the signed type can represent all values of the unsigned type, it
2943 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002944 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002945 return -1;
2946 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002947
Chris Lattner7cfeb082008-04-06 23:55:33 +00002948 // If the unsigned [RHS] type is larger, return it.
2949 if (RHSRank >= LHSRank)
2950 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Chris Lattner7cfeb082008-04-06 23:55:33 +00002952 // If the signed type can represent all values of the unsigned type, it
2953 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002954 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002955 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002956}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002957
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002958static RecordDecl *
2959CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2960 SourceLocation L, IdentifierInfo *Id) {
2961 if (Ctx.getLangOptions().CPlusPlus)
2962 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2963 else
2964 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2965}
2966
Mike Stump1eb44332009-09-09 15:08:12 +00002967// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002968QualType ASTContext::getCFConstantStringType() {
2969 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002970 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002971 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002972 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002973 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002974
Anders Carlssonf06273f2007-11-19 00:25:30 +00002975 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Anders Carlsson71993dd2007-08-17 05:31:46 +00002977 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002978 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002979 // int flags;
2980 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002981 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002982 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002983 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002984 FieldTypes[3] = LongTy;
2985
Anders Carlsson71993dd2007-08-17 05:31:46 +00002986 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002987 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002988 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002989 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002990 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002991 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002992 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002993 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002994 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002995 }
2996
Douglas Gregor838db382010-02-11 01:19:42 +00002997 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002998 }
Mike Stump1eb44332009-09-09 15:08:12 +00002999
Anders Carlsson71993dd2007-08-17 05:31:46 +00003000 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003001}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003002
Douglas Gregor319ac892009-04-23 22:29:11 +00003003void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003004 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003005 assert(Rec && "Invalid CFConstantStringType");
3006 CFConstantStringTypeDecl = Rec->getDecl();
3007}
3008
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003009// getNSConstantStringType - Return the type used for constant NSStrings.
3010QualType ASTContext::getNSConstantStringType() {
3011 if (!NSConstantStringTypeDecl) {
3012 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003013 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003014 &Idents.get("__builtin_NSString"));
3015 NSConstantStringTypeDecl->startDefinition();
3016
3017 QualType FieldTypes[3];
3018
3019 // const int *isa;
3020 FieldTypes[0] = getPointerType(IntTy.withConst());
3021 // const char *str;
3022 FieldTypes[1] = getPointerType(CharTy.withConst());
3023 // unsigned int length;
3024 FieldTypes[2] = UnsignedIntTy;
3025
3026 // Create fields
3027 for (unsigned i = 0; i < 3; ++i) {
3028 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3029 SourceLocation(), 0,
3030 FieldTypes[i], /*TInfo=*/0,
3031 /*BitWidth=*/0,
3032 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003033 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003034 NSConstantStringTypeDecl->addDecl(Field);
3035 }
3036
3037 NSConstantStringTypeDecl->completeDefinition();
3038 }
3039
3040 return getTagDeclType(NSConstantStringTypeDecl);
3041}
3042
3043void ASTContext::setNSConstantStringType(QualType T) {
3044 const RecordType *Rec = T->getAs<RecordType>();
3045 assert(Rec && "Invalid NSConstantStringType");
3046 NSConstantStringTypeDecl = Rec->getDecl();
3047}
3048
Mike Stump1eb44332009-09-09 15:08:12 +00003049QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003050 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003051 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003052 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003053 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003054 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003055
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003056 QualType FieldTypes[] = {
3057 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003058 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003059 getPointerType(UnsignedLongTy),
3060 getConstantArrayType(UnsignedLongTy,
3061 llvm::APInt(32, 5), ArrayType::Normal, 0)
3062 };
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Douglas Gregor44b43212008-12-11 16:49:14 +00003064 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003065 FieldDecl *Field = FieldDecl::Create(*this,
3066 ObjCFastEnumerationStateTypeDecl,
3067 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003068 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003069 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003070 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003071 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003072 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003073 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003074 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003075 if (CXXRecordDecl *CXXRD =
3076 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003077 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Douglas Gregor838db382010-02-11 01:19:42 +00003079 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003080 }
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003082 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3083}
3084
Mike Stumpadaaad32009-10-20 02:12:22 +00003085QualType ASTContext::getBlockDescriptorType() {
3086 if (BlockDescriptorType)
3087 return getTagDeclType(BlockDescriptorType);
3088
3089 RecordDecl *T;
3090 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003091 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003092 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003093 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003094
3095 QualType FieldTypes[] = {
3096 UnsignedLongTy,
3097 UnsignedLongTy,
3098 };
3099
3100 const char *FieldNames[] = {
3101 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003102 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003103 };
3104
3105 for (size_t i = 0; i < 2; ++i) {
3106 FieldDecl *Field = FieldDecl::Create(*this,
3107 T,
3108 SourceLocation(),
3109 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003110 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003111 /*BitWidth=*/0,
3112 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003113 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003114 T->addDecl(Field);
3115 }
3116
Douglas Gregor838db382010-02-11 01:19:42 +00003117 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003118
3119 BlockDescriptorType = T;
3120
3121 return getTagDeclType(BlockDescriptorType);
3122}
3123
3124void ASTContext::setBlockDescriptorType(QualType T) {
3125 const RecordType *Rec = T->getAs<RecordType>();
3126 assert(Rec && "Invalid BlockDescriptorType");
3127 BlockDescriptorType = Rec->getDecl();
3128}
3129
Mike Stump083c25e2009-10-22 00:49:09 +00003130QualType ASTContext::getBlockDescriptorExtendedType() {
3131 if (BlockDescriptorExtendedType)
3132 return getTagDeclType(BlockDescriptorExtendedType);
3133
3134 RecordDecl *T;
3135 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003136 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003137 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003138 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003139
3140 QualType FieldTypes[] = {
3141 UnsignedLongTy,
3142 UnsignedLongTy,
3143 getPointerType(VoidPtrTy),
3144 getPointerType(VoidPtrTy)
3145 };
3146
3147 const char *FieldNames[] = {
3148 "reserved",
3149 "Size",
3150 "CopyFuncPtr",
3151 "DestroyFuncPtr"
3152 };
3153
3154 for (size_t i = 0; i < 4; ++i) {
3155 FieldDecl *Field = FieldDecl::Create(*this,
3156 T,
3157 SourceLocation(),
3158 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003159 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003160 /*BitWidth=*/0,
3161 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003162 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003163 T->addDecl(Field);
3164 }
3165
Douglas Gregor838db382010-02-11 01:19:42 +00003166 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003167
3168 BlockDescriptorExtendedType = T;
3169
3170 return getTagDeclType(BlockDescriptorExtendedType);
3171}
3172
3173void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3174 const RecordType *Rec = T->getAs<RecordType>();
3175 assert(Rec && "Invalid BlockDescriptorType");
3176 BlockDescriptorExtendedType = Rec->getDecl();
3177}
3178
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003179bool ASTContext::BlockRequiresCopying(QualType Ty) {
3180 if (Ty->isBlockPointerType())
3181 return true;
3182 if (isObjCNSObjectType(Ty))
3183 return true;
3184 if (Ty->isObjCObjectPointerType())
3185 return true;
3186 return false;
3187}
3188
Daniel Dunbar4087f272010-08-17 22:39:59 +00003189QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003190 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003191 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003192 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003193 // unsigned int __flags;
3194 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003195 // void *__copy_helper; // as needed
3196 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003197 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003198 // } *
3199
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003200 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3201
3202 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003203 llvm::SmallString<36> Name;
3204 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3205 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003206 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003207 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003208 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003209 T->startDefinition();
3210 QualType Int32Ty = IntTy;
3211 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3212 QualType FieldTypes[] = {
3213 getPointerType(VoidPtrTy),
3214 getPointerType(getTagDeclType(T)),
3215 Int32Ty,
3216 Int32Ty,
3217 getPointerType(VoidPtrTy),
3218 getPointerType(VoidPtrTy),
3219 Ty
3220 };
3221
Daniel Dunbar4087f272010-08-17 22:39:59 +00003222 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003223 "__isa",
3224 "__forwarding",
3225 "__flags",
3226 "__size",
3227 "__copy_helper",
3228 "__destroy_helper",
3229 DeclName,
3230 };
3231
3232 for (size_t i = 0; i < 7; ++i) {
3233 if (!HasCopyAndDispose && i >=4 && i <= 5)
3234 continue;
3235 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3236 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003237 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003238 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003239 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003240 T->addDecl(Field);
3241 }
3242
Douglas Gregor838db382010-02-11 01:19:42 +00003243 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003244
3245 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003246}
3247
3248
3249QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003250 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003251 llvm::SmallVectorImpl<const Expr *> &Layout) {
3252
Mike Stumpadaaad32009-10-20 02:12:22 +00003253 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003254 llvm::SmallString<36> Name;
3255 llvm::raw_svector_ostream(Name) << "__block_literal_"
3256 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003257 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003258 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003259 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003260 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003261 QualType FieldTypes[] = {
3262 getPointerType(VoidPtrTy),
3263 IntTy,
3264 IntTy,
3265 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003266 (BlockHasCopyDispose ?
3267 getPointerType(getBlockDescriptorExtendedType()) :
3268 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003269 };
3270
3271 const char *FieldNames[] = {
3272 "__isa",
3273 "__flags",
3274 "__reserved",
3275 "__FuncPtr",
3276 "__descriptor"
3277 };
3278
3279 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003280 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003281 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003282 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003283 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003284 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003285 T->addDecl(Field);
3286 }
3287
John McCallea1471e2010-05-20 01:18:31 +00003288 for (unsigned i = 0; i < Layout.size(); ++i) {
3289 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003290
John McCallea1471e2010-05-20 01:18:31 +00003291 QualType FieldType = E->getType();
3292 IdentifierInfo *FieldName = 0;
3293 if (isa<CXXThisExpr>(E)) {
3294 FieldName = &Idents.get("this");
3295 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3296 const ValueDecl *D = BDRE->getDecl();
3297 FieldName = D->getIdentifier();
3298 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003299 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003300 } else {
3301 // Padding.
3302 assert(isa<ConstantArrayType>(FieldType) &&
3303 isa<DeclRefExpr>(E) &&
3304 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3305 "doesn't match characteristics of padding decl");
3306 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003307
3308 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003309 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003310 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003311 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003312 T->addDecl(Field);
3313 }
3314
Douglas Gregor838db382010-02-11 01:19:42 +00003315 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003316
3317 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003318}
3319
Douglas Gregor319ac892009-04-23 22:29:11 +00003320void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003321 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003322 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3323 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3324}
3325
Anders Carlssone8c49532007-10-29 06:33:42 +00003326// This returns true if a type has been typedefed to BOOL:
3327// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003328static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003329 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003330 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3331 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003333 return false;
3334}
3335
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003336/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003337/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003338CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003339 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003340
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003341 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003342 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003343 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003344 // Treat arrays as pointers, since that's how they're passed in.
3345 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003346 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003347 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003348}
3349
3350static inline
3351std::string charUnitsToString(const CharUnits &CU) {
3352 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003353}
3354
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003355/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003356/// declaration.
3357void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3358 std::string& S) {
3359 const BlockDecl *Decl = Expr->getBlockDecl();
3360 QualType BlockTy =
3361 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3362 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003363 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003364 // Compute size of all parameters.
3365 // Start with computing size of a pointer in number of bytes.
3366 // FIXME: There might(should) be a better way of doing this computation!
3367 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003368 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3369 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003370 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003371 E = Decl->param_end(); PI != E; ++PI) {
3372 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003373 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003374 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003375 ParmOffset += sz;
3376 }
3377 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003378 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003379 // Block pointer and offset.
3380 S += "@?0";
3381 ParmOffset = PtrSize;
3382
3383 // Argument types.
3384 ParmOffset = PtrSize;
3385 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3386 Decl->param_end(); PI != E; ++PI) {
3387 ParmVarDecl *PVDecl = *PI;
3388 QualType PType = PVDecl->getOriginalType();
3389 if (const ArrayType *AT =
3390 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3391 // Use array's original type only if it has known number of
3392 // elements.
3393 if (!isa<ConstantArrayType>(AT))
3394 PType = PVDecl->getType();
3395 } else if (PType->isFunctionType())
3396 PType = PVDecl->getType();
3397 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003398 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003399 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003400 }
3401}
3402
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003403/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003404/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003405void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003406 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003407 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003408 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003409 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003410 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003411 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003412 // Compute size of all parameters.
3413 // Start with computing size of a pointer in number of bytes.
3414 // FIXME: There might(should) be a better way of doing this computation!
3415 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003416 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003417 // The first two arguments (self and _cmd) are pointers; account for
3418 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003419 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003420 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003421 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003422 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003423 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003424 assert (sz.isPositive() &&
3425 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003426 ParmOffset += sz;
3427 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003428 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003429 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003430 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003432 // Argument types.
3433 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003434 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003435 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003436 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003437 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003438 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003439 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3440 // Use array's original type only if it has known number of
3441 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003442 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003443 PType = PVDecl->getType();
3444 } else if (PType->isFunctionType())
3445 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003446 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003447 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003448 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003449 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003450 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003451 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003452 }
3453}
3454
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003455/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003456/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003457/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3458/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003459/// Property attributes are stored as a comma-delimited C string. The simple
3460/// attributes readonly and bycopy are encoded as single characters. The
3461/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3462/// encoded as single characters, followed by an identifier. Property types
3463/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003464/// these attributes are defined by the following enumeration:
3465/// @code
3466/// enum PropertyAttributes {
3467/// kPropertyReadOnly = 'R', // property is read-only.
3468/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3469/// kPropertyByref = '&', // property is a reference to the value last assigned
3470/// kPropertyDynamic = 'D', // property is dynamic
3471/// kPropertyGetter = 'G', // followed by getter selector name
3472/// kPropertySetter = 'S', // followed by setter selector name
3473/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3474/// kPropertyType = 't' // followed by old-style type encoding.
3475/// kPropertyWeak = 'W' // 'weak' property
3476/// kPropertyStrong = 'P' // property GC'able
3477/// kPropertyNonAtomic = 'N' // property non-atomic
3478/// };
3479/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003480void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003481 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003482 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003483 // Collect information from the property implementation decl(s).
3484 bool Dynamic = false;
3485 ObjCPropertyImplDecl *SynthesizePID = 0;
3486
3487 // FIXME: Duplicated code due to poor abstraction.
3488 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003489 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003490 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3491 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003492 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003493 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003494 ObjCPropertyImplDecl *PID = *i;
3495 if (PID->getPropertyDecl() == PD) {
3496 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3497 Dynamic = true;
3498 } else {
3499 SynthesizePID = PID;
3500 }
3501 }
3502 }
3503 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003504 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003505 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003506 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003507 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003508 ObjCPropertyImplDecl *PID = *i;
3509 if (PID->getPropertyDecl() == PD) {
3510 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3511 Dynamic = true;
3512 } else {
3513 SynthesizePID = PID;
3514 }
3515 }
Mike Stump1eb44332009-09-09 15:08:12 +00003516 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003517 }
3518 }
3519
3520 // FIXME: This is not very efficient.
3521 S = "T";
3522
3523 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003524 // GCC has some special rules regarding encoding of properties which
3525 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003526 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003527 true /* outermost type */,
3528 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003529
3530 if (PD->isReadOnly()) {
3531 S += ",R";
3532 } else {
3533 switch (PD->getSetterKind()) {
3534 case ObjCPropertyDecl::Assign: break;
3535 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003536 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003537 }
3538 }
3539
3540 // It really isn't clear at all what this means, since properties
3541 // are "dynamic by default".
3542 if (Dynamic)
3543 S += ",D";
3544
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003545 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3546 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003547
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003548 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3549 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003550 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003551 }
3552
3553 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3554 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003555 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003556 }
3557
3558 if (SynthesizePID) {
3559 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3560 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003561 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003562 }
3563
3564 // FIXME: OBJCGC: weak & strong
3565}
3566
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003567/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003568/// Another legacy compatibility encoding: 32-bit longs are encoded as
3569/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003570/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3571///
3572void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003573 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003574 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003575 if (BT->getKind() == BuiltinType::ULong &&
3576 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003577 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003578 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003579 if (BT->getKind() == BuiltinType::Long &&
3580 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003581 PointeeTy = IntTy;
3582 }
3583 }
3584}
3585
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003586void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003587 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003588 // We follow the behavior of gcc, expanding structures which are
3589 // directly pointed to, and expanding embedded structures. Note that
3590 // these rules are sufficient to prevent recursive encoding of the
3591 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003592 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003593 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003594}
3595
David Chisnall64fd7e82010-06-04 01:10:52 +00003596static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3597 switch (T->getAs<BuiltinType>()->getKind()) {
3598 default: assert(0 && "Unhandled builtin type kind");
3599 case BuiltinType::Void: return 'v';
3600 case BuiltinType::Bool: return 'B';
3601 case BuiltinType::Char_U:
3602 case BuiltinType::UChar: return 'C';
3603 case BuiltinType::UShort: return 'S';
3604 case BuiltinType::UInt: return 'I';
3605 case BuiltinType::ULong:
3606 return
3607 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3608 case BuiltinType::UInt128: return 'T';
3609 case BuiltinType::ULongLong: return 'Q';
3610 case BuiltinType::Char_S:
3611 case BuiltinType::SChar: return 'c';
3612 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003613 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003614 case BuiltinType::Int: return 'i';
3615 case BuiltinType::Long:
3616 return
3617 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3618 case BuiltinType::LongLong: return 'q';
3619 case BuiltinType::Int128: return 't';
3620 case BuiltinType::Float: return 'f';
3621 case BuiltinType::Double: return 'd';
3622 case BuiltinType::LongDouble: return 'd';
3623 }
3624}
3625
Mike Stump1eb44332009-09-09 15:08:12 +00003626static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003627 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003628 const Expr *E = FD->getBitWidth();
3629 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3630 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003631 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003632 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3633 // The GNU runtime requires more information; bitfields are encoded as b,
3634 // then the offset (in bits) of the first element, then the type of the
3635 // bitfield, then the size in bits. For example, in this structure:
3636 //
3637 // struct
3638 // {
3639 // int integer;
3640 // int flags:2;
3641 // };
3642 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3643 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3644 // information is not especially sensible, but we're stuck with it for
3645 // compatibility with GCC, although providing it breaks anything that
3646 // actually uses runtime introspection and wants to work on both runtimes...
3647 if (!Ctx->getLangOptions().NeXTRuntime) {
3648 const RecordDecl *RD = FD->getParent();
3649 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3650 // FIXME: This same linear search is also used in ExprConstant - it might
3651 // be better if the FieldDecl stored its offset. We'd be increasing the
3652 // size of the object slightly, but saving some time every time it is used.
3653 unsigned i = 0;
3654 for (RecordDecl::field_iterator Field = RD->field_begin(),
3655 FieldEnd = RD->field_end();
3656 Field != FieldEnd; (void)++Field, ++i) {
3657 if (*Field == FD)
3658 break;
3659 }
3660 S += llvm::utostr(RL.getFieldOffset(i));
3661 S += ObjCEncodingForPrimitiveKind(Context, T);
3662 }
3663 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003664 S += llvm::utostr(N);
3665}
3666
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003667// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003668void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3669 bool ExpandPointedToStructures,
3670 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003671 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003672 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003673 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003674 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003675 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003676 return EncodeBitField(this, S, T, FD);
3677 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003678 return;
3679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
John McCall183700f2009-09-21 23:43:11 +00003681 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003682 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003683 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003684 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003685 return;
3686 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003687
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003688 // encoding for pointer or r3eference types.
3689 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003690 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003691 if (PT->isObjCSelType()) {
3692 S += ':';
3693 return;
3694 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003695 PointeeTy = PT->getPointeeType();
3696 }
3697 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3698 PointeeTy = RT->getPointeeType();
3699 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003700 bool isReadOnly = false;
3701 // For historical/compatibility reasons, the read-only qualifier of the
3702 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3703 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003704 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003705 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003706 if (OutermostType && T.isConstQualified()) {
3707 isReadOnly = true;
3708 S += 'r';
3709 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003710 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003711 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003712 while (P->getAs<PointerType>())
3713 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003714 if (P.isConstQualified()) {
3715 isReadOnly = true;
3716 S += 'r';
3717 }
3718 }
3719 if (isReadOnly) {
3720 // Another legacy compatibility encoding. Some ObjC qualifier and type
3721 // combinations need to be rearranged.
3722 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003723 if (llvm::StringRef(S).endswith("nr"))
3724 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003725 }
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003727 if (PointeeTy->isCharType()) {
3728 // char pointer types should be encoded as '*' unless it is a
3729 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003730 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003731 S += '*';
3732 return;
3733 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003734 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003735 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3736 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3737 S += '#';
3738 return;
3739 }
3740 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3741 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3742 S += '@';
3743 return;
3744 }
3745 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003746 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003747 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003748 getLegacyIntegralTypeEncoding(PointeeTy);
3749
Mike Stump1eb44332009-09-09 15:08:12 +00003750 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003751 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003752 return;
3753 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003754
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003755 if (const ArrayType *AT =
3756 // Ignore type qualifiers etc.
3757 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003758 if (isa<IncompleteArrayType>(AT)) {
3759 // Incomplete arrays are encoded as a pointer to the array element.
3760 S += '^';
3761
Mike Stump1eb44332009-09-09 15:08:12 +00003762 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003763 false, ExpandStructures, FD);
3764 } else {
3765 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Anders Carlsson559a8332009-02-22 01:38:57 +00003767 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3768 S += llvm::utostr(CAT->getSize().getZExtValue());
3769 else {
3770 //Variable length arrays are encoded as a regular array with 0 elements.
3771 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3772 S += '0';
3773 }
Mike Stump1eb44332009-09-09 15:08:12 +00003774
3775 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003776 false, ExpandStructures, FD);
3777 S += ']';
3778 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003779 return;
3780 }
Mike Stump1eb44332009-09-09 15:08:12 +00003781
John McCall183700f2009-09-21 23:43:11 +00003782 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003783 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003784 return;
3785 }
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Ted Kremenek6217b802009-07-29 21:53:49 +00003787 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003788 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003789 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003790 // Anonymous structures print as '?'
3791 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3792 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003793 if (ClassTemplateSpecializationDecl *Spec
3794 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3795 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3796 std::string TemplateArgsStr
3797 = TemplateSpecializationType::PrintTemplateArgumentList(
3798 TemplateArgs.getFlatArgumentList(),
3799 TemplateArgs.flat_size(),
3800 (*this).PrintingPolicy);
3801
3802 S += TemplateArgsStr;
3803 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003804 } else {
3805 S += '?';
3806 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003807 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003808 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003809 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3810 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003811 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003812 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003813 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003814 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003815 S += '"';
3816 }
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003818 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003819 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003820 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003821 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003822 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003823 QualType qt = Field->getType();
3824 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003825 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003826 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003827 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003828 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003829 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003830 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003831 return;
3832 }
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003834 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003835 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003836 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003837 else
3838 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003839 return;
3840 }
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003842 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003843 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003844 return;
3845 }
Mike Stump1eb44332009-09-09 15:08:12 +00003846
John McCallc12c5bb2010-05-15 11:32:37 +00003847 // Ignore protocol qualifiers when mangling at this level.
3848 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3849 T = OT->getBaseType();
3850
John McCall0953e762009-09-24 19:53:00 +00003851 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003852 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003853 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003854 S += '{';
3855 const IdentifierInfo *II = OI->getIdentifier();
3856 S += II->getName();
3857 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003858 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003859 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003860 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003861 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003862 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003863 RecFields[i]);
3864 else
Mike Stump1eb44332009-09-09 15:08:12 +00003865 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003866 FD);
3867 }
3868 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003869 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003870 }
Mike Stump1eb44332009-09-09 15:08:12 +00003871
John McCall183700f2009-09-21 23:43:11 +00003872 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003873 if (OPT->isObjCIdType()) {
3874 S += '@';
3875 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003876 }
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Steve Naroff27d20a22009-10-28 22:03:49 +00003878 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3879 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3880 // Since this is a binary compatibility issue, need to consult with runtime
3881 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003882 S += '#';
3883 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003884 }
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003886 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003887 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003888 ExpandPointedToStructures,
3889 ExpandStructures, FD);
3890 if (FD || EncodingProperty) {
3891 // Note that we do extended encoding of protocol qualifer list
3892 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003893 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003894 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3895 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003896 S += '<';
3897 S += (*I)->getNameAsString();
3898 S += '>';
3899 }
3900 S += '"';
3901 }
3902 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003905 QualType PointeeTy = OPT->getPointeeType();
3906 if (!EncodingProperty &&
3907 isa<TypedefType>(PointeeTy.getTypePtr())) {
3908 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003909 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003910 // {...};
3911 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003912 getObjCEncodingForTypeImpl(PointeeTy, S,
3913 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003914 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003915 return;
3916 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003917
3918 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003919 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003920 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003921 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003922 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3923 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003924 S += '<';
3925 S += (*I)->getNameAsString();
3926 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003927 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003928 S += '"';
3929 }
3930 return;
3931 }
Mike Stump1eb44332009-09-09 15:08:12 +00003932
John McCall532ec7b2010-05-17 23:56:34 +00003933 // gcc just blithely ignores member pointers.
3934 // TODO: maybe there should be a mangling for these
3935 if (T->getAs<MemberPointerType>())
3936 return;
3937
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003938 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003939}
3940
Mike Stump1eb44332009-09-09 15:08:12 +00003941void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003942 std::string& S) const {
3943 if (QT & Decl::OBJC_TQ_In)
3944 S += 'n';
3945 if (QT & Decl::OBJC_TQ_Inout)
3946 S += 'N';
3947 if (QT & Decl::OBJC_TQ_Out)
3948 S += 'o';
3949 if (QT & Decl::OBJC_TQ_Bycopy)
3950 S += 'O';
3951 if (QT & Decl::OBJC_TQ_Byref)
3952 S += 'R';
3953 if (QT & Decl::OBJC_TQ_Oneway)
3954 S += 'V';
3955}
3956
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003957void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003958 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003959
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003960 BuiltinVaListType = T;
3961}
3962
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003963void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003964 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003965}
3966
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003967void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003968 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003969}
3970
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003971void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003972 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003973}
3974
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003975void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003976 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003977}
3978
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003979void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003980 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003981 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003983 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003984}
3985
John McCall0bd6feb2009-12-02 08:04:21 +00003986/// \brief Retrieve the template name that corresponds to a non-empty
3987/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003988TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3989 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003990 unsigned size = End - Begin;
3991 assert(size > 1 && "set is not overloaded!");
3992
3993 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3994 size * sizeof(FunctionTemplateDecl*));
3995 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3996
3997 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003998 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003999 NamedDecl *D = *I;
4000 assert(isa<FunctionTemplateDecl>(D) ||
4001 (isa<UsingShadowDecl>(D) &&
4002 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4003 *Storage++ = D;
4004 }
4005
4006 return TemplateName(OT);
4007}
4008
Douglas Gregor7532dc62009-03-30 22:58:21 +00004009/// \brief Retrieve the template name that represents a qualified
4010/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004011TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004012 bool TemplateKeyword,
4013 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004014 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004015 llvm::FoldingSetNodeID ID;
4016 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4017
4018 void *InsertPos = 0;
4019 QualifiedTemplateName *QTN =
4020 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4021 if (!QTN) {
4022 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4023 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4024 }
4025
4026 return TemplateName(QTN);
4027}
4028
4029/// \brief Retrieve the template name that represents a dependent
4030/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004031TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004032 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004033 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004034 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004035
4036 llvm::FoldingSetNodeID ID;
4037 DependentTemplateName::Profile(ID, NNS, Name);
4038
4039 void *InsertPos = 0;
4040 DependentTemplateName *QTN =
4041 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4042
4043 if (QTN)
4044 return TemplateName(QTN);
4045
4046 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4047 if (CanonNNS == NNS) {
4048 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4049 } else {
4050 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4051 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004052 DependentTemplateName *CheckQTN =
4053 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4054 assert(!CheckQTN && "Dependent type name canonicalization broken");
4055 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004056 }
4057
4058 DependentTemplateNames.InsertNode(QTN, InsertPos);
4059 return TemplateName(QTN);
4060}
4061
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004062/// \brief Retrieve the template name that represents a dependent
4063/// template name such as \c MetaFun::template operator+.
4064TemplateName
4065ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4066 OverloadedOperatorKind Operator) {
4067 assert((!NNS || NNS->isDependent()) &&
4068 "Nested name specifier must be dependent");
4069
4070 llvm::FoldingSetNodeID ID;
4071 DependentTemplateName::Profile(ID, NNS, Operator);
4072
4073 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004074 DependentTemplateName *QTN
4075 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004076
4077 if (QTN)
4078 return TemplateName(QTN);
4079
4080 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4081 if (CanonNNS == NNS) {
4082 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4083 } else {
4084 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4085 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004086
4087 DependentTemplateName *CheckQTN
4088 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4089 assert(!CheckQTN && "Dependent template name canonicalization broken");
4090 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004091 }
4092
4093 DependentTemplateNames.InsertNode(QTN, InsertPos);
4094 return TemplateName(QTN);
4095}
4096
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004097/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004098/// TargetInfo, produce the corresponding type. The unsigned @p Type
4099/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004100CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004101 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004102 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004103 case TargetInfo::SignedShort: return ShortTy;
4104 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4105 case TargetInfo::SignedInt: return IntTy;
4106 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4107 case TargetInfo::SignedLong: return LongTy;
4108 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4109 case TargetInfo::SignedLongLong: return LongLongTy;
4110 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4111 }
4112
4113 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004114 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004115}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004116
4117//===----------------------------------------------------------------------===//
4118// Type Predicates.
4119//===----------------------------------------------------------------------===//
4120
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004121/// isObjCNSObjectType - Return true if this is an NSObject object using
4122/// NSObject attribute on a c-style pointer type.
4123/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004124/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004125///
4126bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4127 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4128 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004129 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004130 return true;
4131 }
Mike Stump1eb44332009-09-09 15:08:12 +00004132 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004133}
4134
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004135/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4136/// garbage collection attribute.
4137///
John McCall0953e762009-09-24 19:53:00 +00004138Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4139 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004140 if (getLangOptions().ObjC1 &&
4141 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004142 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004143 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004144 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004145 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004146 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004147 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004148 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004149 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004150 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004151 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004152 // Non-pointers have none gc'able attribute regardless of the attribute
4153 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004154 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004155 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004156 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004157 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004158}
4159
Chris Lattner6ac46a42008-04-07 06:51:04 +00004160//===----------------------------------------------------------------------===//
4161// Type Compatibility Testing
4162//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004163
Mike Stump1eb44332009-09-09 15:08:12 +00004164/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004165/// compatible.
4166static bool areCompatVectorTypes(const VectorType *LHS,
4167 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004168 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004169 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004170 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004171}
4172
Douglas Gregor255210e2010-08-06 10:14:59 +00004173bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4174 QualType SecondVec) {
4175 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4176 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4177
4178 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4179 return true;
4180
4181 // AltiVec vectors types are identical to equivalent GCC vector types
4182 const VectorType *First = FirstVec->getAs<VectorType>();
4183 const VectorType *Second = SecondVec->getAs<VectorType>();
4184 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4185 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4186 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4187 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4188 hasSameType(First->getElementType(), Second->getElementType()) &&
4189 (First->getNumElements() == Second->getNumElements()))
4190 return true;
4191
4192 return false;
4193}
4194
Steve Naroff4084c302009-07-23 01:01:38 +00004195//===----------------------------------------------------------------------===//
4196// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4197//===----------------------------------------------------------------------===//
4198
4199/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4200/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004201bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4202 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004203 if (lProto == rProto)
4204 return true;
4205 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4206 E = rProto->protocol_end(); PI != E; ++PI)
4207 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4208 return true;
4209 return false;
4210}
4211
Steve Naroff4084c302009-07-23 01:01:38 +00004212/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4213/// return true if lhs's protocols conform to rhs's protocol; false
4214/// otherwise.
4215bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4216 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4217 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4218 return false;
4219}
4220
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004221/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4222/// Class<p1, ...>.
4223bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4224 QualType rhs) {
4225 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4226 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4227 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4228
4229 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4230 E = lhsQID->qual_end(); I != E; ++I) {
4231 bool match = false;
4232 ObjCProtocolDecl *lhsProto = *I;
4233 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4234 E = rhsOPT->qual_end(); J != E; ++J) {
4235 ObjCProtocolDecl *rhsProto = *J;
4236 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4237 match = true;
4238 break;
4239 }
4240 }
4241 if (!match)
4242 return false;
4243 }
4244 return true;
4245}
4246
Steve Naroff4084c302009-07-23 01:01:38 +00004247/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4248/// ObjCQualifiedIDType.
4249bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4250 bool compare) {
4251 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004252 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004253 lhs->isObjCIdType() || lhs->isObjCClassType())
4254 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004255 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004256 rhs->isObjCIdType() || rhs->isObjCClassType())
4257 return true;
4258
4259 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004260 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004261
Steve Naroff4084c302009-07-23 01:01:38 +00004262 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004263
Steve Naroff4084c302009-07-23 01:01:38 +00004264 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004265 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004266 // make sure we check the class hierarchy.
4267 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4268 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4269 E = lhsQID->qual_end(); I != E; ++I) {
4270 // when comparing an id<P> on lhs with a static type on rhs,
4271 // see if static class implements all of id's protocols, directly or
4272 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004273 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004274 return false;
4275 }
4276 }
4277 // If there are no qualifiers and no interface, we have an 'id'.
4278 return true;
4279 }
Mike Stump1eb44332009-09-09 15:08:12 +00004280 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004281 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4282 E = lhsQID->qual_end(); I != E; ++I) {
4283 ObjCProtocolDecl *lhsProto = *I;
4284 bool match = false;
4285
4286 // when comparing an id<P> on lhs with a static type on rhs,
4287 // see if static class implements all of id's protocols, directly or
4288 // through its super class and categories.
4289 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4290 E = rhsOPT->qual_end(); J != E; ++J) {
4291 ObjCProtocolDecl *rhsProto = *J;
4292 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4293 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4294 match = true;
4295 break;
4296 }
4297 }
Mike Stump1eb44332009-09-09 15:08:12 +00004298 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004299 // make sure we check the class hierarchy.
4300 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4301 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4302 E = lhsQID->qual_end(); I != E; ++I) {
4303 // when comparing an id<P> on lhs with a static type on rhs,
4304 // see if static class implements all of id's protocols, directly or
4305 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004306 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004307 match = true;
4308 break;
4309 }
4310 }
4311 }
4312 if (!match)
4313 return false;
4314 }
Mike Stump1eb44332009-09-09 15:08:12 +00004315
Steve Naroff4084c302009-07-23 01:01:38 +00004316 return true;
4317 }
Mike Stump1eb44332009-09-09 15:08:12 +00004318
Steve Naroff4084c302009-07-23 01:01:38 +00004319 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4320 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4321
Mike Stump1eb44332009-09-09 15:08:12 +00004322 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004323 lhs->getAsObjCInterfacePointerType()) {
4324 if (lhsOPT->qual_empty()) {
4325 bool match = false;
4326 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4327 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4328 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004329 // when comparing an id<P> on rhs with a static type on lhs,
4330 // static class must implement all of id's protocols directly or
4331 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004332 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004333 match = true;
4334 break;
4335 }
4336 }
4337 if (!match)
4338 return false;
4339 }
4340 return true;
4341 }
Mike Stump1eb44332009-09-09 15:08:12 +00004342 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004343 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4344 E = lhsOPT->qual_end(); I != E; ++I) {
4345 ObjCProtocolDecl *lhsProto = *I;
4346 bool match = false;
4347
4348 // when comparing an id<P> on lhs with a static type on rhs,
4349 // see if static class implements all of id's protocols, directly or
4350 // through its super class and categories.
4351 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4352 E = rhsQID->qual_end(); J != E; ++J) {
4353 ObjCProtocolDecl *rhsProto = *J;
4354 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4355 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4356 match = true;
4357 break;
4358 }
4359 }
4360 if (!match)
4361 return false;
4362 }
4363 return true;
4364 }
4365 return false;
4366}
4367
Eli Friedman3d815e72008-08-22 00:56:42 +00004368/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004369/// compatible for assignment from RHS to LHS. This handles validation of any
4370/// protocol qualifiers on the LHS or RHS.
4371///
Steve Naroff14108da2009-07-10 23:34:53 +00004372bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4373 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004374 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4375 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4376
Steve Naroffde2e22d2009-07-15 18:40:39 +00004377 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004378 if (LHS->isObjCUnqualifiedIdOrClass() ||
4379 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004380 return true;
4381
John McCallc12c5bb2010-05-15 11:32:37 +00004382 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004383 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4384 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004385 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004386
4387 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4388 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4389 QualType(RHSOPT,0));
4390
John McCallc12c5bb2010-05-15 11:32:37 +00004391 // If we have 2 user-defined types, fall into that path.
4392 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004393 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Steve Naroff4084c302009-07-23 01:01:38 +00004395 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004396}
4397
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004398/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4399/// for providing type-safty for objective-c pointers used to pass/return
4400/// arguments in block literals. When passed as arguments, passing 'A*' where
4401/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4402/// not OK. For the return type, the opposite is not OK.
4403bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4404 const ObjCObjectPointerType *LHSOPT,
4405 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004406 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004407 return true;
4408
4409 if (LHSOPT->isObjCBuiltinType()) {
4410 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4411 }
4412
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004413 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004414 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4415 QualType(RHSOPT,0),
4416 false);
4417
4418 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4419 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4420 if (LHS && RHS) { // We have 2 user-defined types.
4421 if (LHS != RHS) {
4422 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4423 return false;
4424 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4425 return true;
4426 }
4427 else
4428 return true;
4429 }
4430 return false;
4431}
4432
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004433/// getIntersectionOfProtocols - This routine finds the intersection of set
4434/// of protocols inherited from two distinct objective-c pointer objects.
4435/// It is used to build composite qualifier list of the composite type of
4436/// the conditional expression involving two objective-c pointer objects.
4437static
4438void getIntersectionOfProtocols(ASTContext &Context,
4439 const ObjCObjectPointerType *LHSOPT,
4440 const ObjCObjectPointerType *RHSOPT,
4441 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4442
John McCallc12c5bb2010-05-15 11:32:37 +00004443 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4444 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4445 assert(LHS->getInterface() && "LHS must have an interface base");
4446 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004447
4448 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4449 unsigned LHSNumProtocols = LHS->getNumProtocols();
4450 if (LHSNumProtocols > 0)
4451 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4452 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004453 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004454 Context.CollectInheritedProtocols(LHS->getInterface(),
4455 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004456 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4457 LHSInheritedProtocols.end());
4458 }
4459
4460 unsigned RHSNumProtocols = RHS->getNumProtocols();
4461 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004462 ObjCProtocolDecl **RHSProtocols =
4463 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004464 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4465 if (InheritedProtocolSet.count(RHSProtocols[i]))
4466 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4467 }
4468 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004469 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004470 Context.CollectInheritedProtocols(RHS->getInterface(),
4471 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004472 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4473 RHSInheritedProtocols.begin(),
4474 E = RHSInheritedProtocols.end(); I != E; ++I)
4475 if (InheritedProtocolSet.count((*I)))
4476 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004477 }
4478}
4479
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004480/// areCommonBaseCompatible - Returns common base class of the two classes if
4481/// one found. Note that this is O'2 algorithm. But it will be called as the
4482/// last type comparison in a ?-exp of ObjC pointer types before a
4483/// warning is issued. So, its invokation is extremely rare.
4484QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004485 const ObjCObjectPointerType *Lptr,
4486 const ObjCObjectPointerType *Rptr) {
4487 const ObjCObjectType *LHS = Lptr->getObjectType();
4488 const ObjCObjectType *RHS = Rptr->getObjectType();
4489 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4490 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4491 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004492 return QualType();
4493
John McCallc12c5bb2010-05-15 11:32:37 +00004494 while ((LDecl = LDecl->getSuperClass())) {
4495 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004496 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004497 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4498 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4499
4500 QualType Result = QualType(LHS, 0);
4501 if (!Protocols.empty())
4502 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4503 Result = getObjCObjectPointerType(Result);
4504 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004505 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004506 }
4507
4508 return QualType();
4509}
4510
John McCallc12c5bb2010-05-15 11:32:37 +00004511bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4512 const ObjCObjectType *RHS) {
4513 assert(LHS->getInterface() && "LHS is not an interface type");
4514 assert(RHS->getInterface() && "RHS is not an interface type");
4515
Chris Lattner6ac46a42008-04-07 06:51:04 +00004516 // Verify that the base decls are compatible: the RHS must be a subclass of
4517 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004518 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004519 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004520
Chris Lattner6ac46a42008-04-07 06:51:04 +00004521 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4522 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004523 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004524 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Chris Lattner6ac46a42008-04-07 06:51:04 +00004526 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4527 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004528 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004529 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004530
John McCallc12c5bb2010-05-15 11:32:37 +00004531 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4532 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004533 LHSPI != LHSPE; LHSPI++) {
4534 bool RHSImplementsProtocol = false;
4535
4536 // If the RHS doesn't implement the protocol on the left, the types
4537 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004538 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4539 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004540 RHSPI != RHSPE; RHSPI++) {
4541 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004542 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004543 break;
4544 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004545 }
4546 // FIXME: For better diagnostics, consider passing back the protocol name.
4547 if (!RHSImplementsProtocol)
4548 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004549 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004550 // The RHS implements all protocols listed on the LHS.
4551 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004552}
4553
Steve Naroff389bf462009-02-12 17:52:19 +00004554bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4555 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004556 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4557 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Steve Naroff14108da2009-07-10 23:34:53 +00004559 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004560 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004561
4562 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4563 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004564}
4565
Douglas Gregor569c3162010-08-07 11:51:51 +00004566bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4567 return canAssignObjCInterfaces(
4568 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4569 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4570}
4571
Mike Stump1eb44332009-09-09 15:08:12 +00004572/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004573/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004574/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004575/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004576bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4577 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004578 if (getLangOptions().CPlusPlus)
4579 return hasSameType(LHS, RHS);
4580
Douglas Gregor447234d2010-07-29 15:18:02 +00004581 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004582}
4583
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004584bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4585 return !mergeTypes(LHS, RHS, true).isNull();
4586}
4587
4588QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004589 bool OfBlockPointer,
4590 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004591 const FunctionType *lbase = lhs->getAs<FunctionType>();
4592 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004593 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4594 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004595 bool allLTypes = true;
4596 bool allRTypes = true;
4597
4598 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004599 QualType retType;
4600 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004601 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4602 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004603 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004604 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4605 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004606 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004607
4608 if (Unqualified)
4609 retType = retType.getUnqualifiedType();
4610
4611 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4612 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4613 if (Unqualified) {
4614 LRetType = LRetType.getUnqualifiedType();
4615 RRetType = RRetType.getUnqualifiedType();
4616 }
4617
4618 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004619 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004620 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004621 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004622 // FIXME: double check this
4623 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4624 // rbase->getRegParmAttr() != 0 &&
4625 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004626 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4627 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004628 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4629 lbaseInfo.getRegParm();
4630 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4631 if (NoReturn != lbaseInfo.getNoReturn() ||
4632 RegParm != lbaseInfo.getRegParm())
4633 allLTypes = false;
4634 if (NoReturn != rbaseInfo.getNoReturn() ||
4635 RegParm != rbaseInfo.getRegParm())
4636 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004637 CallingConv lcc = lbaseInfo.getCC();
4638 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004639 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004640 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004641 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Eli Friedman3d815e72008-08-22 00:56:42 +00004643 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004644 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4645 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004646 unsigned lproto_nargs = lproto->getNumArgs();
4647 unsigned rproto_nargs = rproto->getNumArgs();
4648
4649 // Compatible functions must have the same number of arguments
4650 if (lproto_nargs != rproto_nargs)
4651 return QualType();
4652
4653 // Variadic and non-variadic functions aren't compatible
4654 if (lproto->isVariadic() != rproto->isVariadic())
4655 return QualType();
4656
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004657 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4658 return QualType();
4659
Eli Friedman3d815e72008-08-22 00:56:42 +00004660 // Check argument compatibility
4661 llvm::SmallVector<QualType, 10> types;
4662 for (unsigned i = 0; i < lproto_nargs; i++) {
4663 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4664 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004665 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4666 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004667 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004668
4669 if (Unqualified)
4670 argtype = argtype.getUnqualifiedType();
4671
Eli Friedman3d815e72008-08-22 00:56:42 +00004672 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004673 if (Unqualified) {
4674 largtype = largtype.getUnqualifiedType();
4675 rargtype = rargtype.getUnqualifiedType();
4676 }
4677
Chris Lattner61710852008-10-05 17:34:18 +00004678 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4679 allLTypes = false;
4680 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4681 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004682 }
4683 if (allLTypes) return lhs;
4684 if (allRTypes) return rhs;
4685 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004686 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004687 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004688 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004689 }
4690
4691 if (lproto) allRTypes = false;
4692 if (rproto) allLTypes = false;
4693
Douglas Gregor72564e72009-02-26 23:50:07 +00004694 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004695 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004696 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004697 if (proto->isVariadic()) return QualType();
4698 // Check that the types are compatible with the types that
4699 // would result from default argument promotions (C99 6.7.5.3p15).
4700 // The only types actually affected are promotable integer
4701 // types and floats, which would be passed as a different
4702 // type depending on whether the prototype is visible.
4703 unsigned proto_nargs = proto->getNumArgs();
4704 for (unsigned i = 0; i < proto_nargs; ++i) {
4705 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004706
4707 // Look at the promotion type of enum types, since that is the type used
4708 // to pass enum values.
4709 if (const EnumType *Enum = argTy->getAs<EnumType>())
4710 argTy = Enum->getDecl()->getPromotionType();
4711
Eli Friedman3d815e72008-08-22 00:56:42 +00004712 if (argTy->isPromotableIntegerType() ||
4713 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4714 return QualType();
4715 }
4716
4717 if (allLTypes) return lhs;
4718 if (allRTypes) return rhs;
4719 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004720 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004721 proto->getTypeQuals(),
4722 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004723 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004724 }
4725
4726 if (allLTypes) return lhs;
4727 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004728 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004729 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004730}
4731
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004732QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004733 bool OfBlockPointer,
4734 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004735 // C++ [expr]: If an expression initially has the type "reference to T", the
4736 // type is adjusted to "T" prior to any further analysis, the expression
4737 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004738 // expression is an lvalue unless the reference is an rvalue reference and
4739 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004740 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4741 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004742
4743 if (Unqualified) {
4744 LHS = LHS.getUnqualifiedType();
4745 RHS = RHS.getUnqualifiedType();
4746 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004747
Eli Friedman3d815e72008-08-22 00:56:42 +00004748 QualType LHSCan = getCanonicalType(LHS),
4749 RHSCan = getCanonicalType(RHS);
4750
4751 // If two types are identical, they are compatible.
4752 if (LHSCan == RHSCan)
4753 return LHS;
4754
John McCall0953e762009-09-24 19:53:00 +00004755 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004756 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4757 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004758 if (LQuals != RQuals) {
4759 // If any of these qualifiers are different, we have a type
4760 // mismatch.
4761 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4762 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4763 return QualType();
4764
4765 // Exactly one GC qualifier difference is allowed: __strong is
4766 // okay if the other type has no GC qualifier but is an Objective
4767 // C object pointer (i.e. implicitly strong by default). We fix
4768 // this by pretending that the unqualified type was actually
4769 // qualified __strong.
4770 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4771 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4772 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4773
4774 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4775 return QualType();
4776
4777 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4778 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4779 }
4780 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4781 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4782 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004783 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004784 }
4785
4786 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004787
Eli Friedman852d63b2009-06-01 01:22:52 +00004788 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4789 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004790
Chris Lattner1adb8832008-01-14 05:45:46 +00004791 // We want to consider the two function types to be the same for these
4792 // comparisons, just force one to the other.
4793 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4794 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004795
4796 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004797 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4798 LHSClass = Type::ConstantArray;
4799 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4800 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004801
John McCallc12c5bb2010-05-15 11:32:37 +00004802 // ObjCInterfaces are just specialized ObjCObjects.
4803 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4804 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4805
Nate Begeman213541a2008-04-18 23:10:10 +00004806 // Canonicalize ExtVector -> Vector.
4807 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4808 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Chris Lattnera36a61f2008-04-07 05:43:21 +00004810 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004811 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004812 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004813 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004814 // Compatibility is based on the underlying type, not the promotion
4815 // type.
John McCall183700f2009-09-21 23:43:11 +00004816 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004817 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4818 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004819 }
John McCall183700f2009-09-21 23:43:11 +00004820 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004821 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4822 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004823 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004824
Eli Friedman3d815e72008-08-22 00:56:42 +00004825 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004826 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004827
Steve Naroff4a746782008-01-09 22:43:08 +00004828 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004829 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004830#define TYPE(Class, Base)
4831#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004832#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004833#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4834#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4835#include "clang/AST/TypeNodes.def"
4836 assert(false && "Non-canonical and dependent types shouldn't get here");
4837 return QualType();
4838
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004839 case Type::LValueReference:
4840 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004841 case Type::MemberPointer:
4842 assert(false && "C++ should never be in mergeTypes");
4843 return QualType();
4844
John McCallc12c5bb2010-05-15 11:32:37 +00004845 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004846 case Type::IncompleteArray:
4847 case Type::VariableArray:
4848 case Type::FunctionProto:
4849 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004850 assert(false && "Types are eliminated above");
4851 return QualType();
4852
Chris Lattner1adb8832008-01-14 05:45:46 +00004853 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004854 {
4855 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004856 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4857 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004858 if (Unqualified) {
4859 LHSPointee = LHSPointee.getUnqualifiedType();
4860 RHSPointee = RHSPointee.getUnqualifiedType();
4861 }
4862 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4863 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004864 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004865 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004866 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004867 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004868 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004869 return getPointerType(ResultType);
4870 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004871 case Type::BlockPointer:
4872 {
4873 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004874 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4875 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004876 if (Unqualified) {
4877 LHSPointee = LHSPointee.getUnqualifiedType();
4878 RHSPointee = RHSPointee.getUnqualifiedType();
4879 }
4880 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4881 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004882 if (ResultType.isNull()) return QualType();
4883 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4884 return LHS;
4885 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4886 return RHS;
4887 return getBlockPointerType(ResultType);
4888 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004889 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004890 {
4891 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4892 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4893 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4894 return QualType();
4895
4896 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4897 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004898 if (Unqualified) {
4899 LHSElem = LHSElem.getUnqualifiedType();
4900 RHSElem = RHSElem.getUnqualifiedType();
4901 }
4902
4903 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004904 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004905 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4906 return LHS;
4907 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4908 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004909 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4910 ArrayType::ArraySizeModifier(), 0);
4911 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4912 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004913 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4914 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004915 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4916 return LHS;
4917 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4918 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004919 if (LVAT) {
4920 // FIXME: This isn't correct! But tricky to implement because
4921 // the array's size has to be the size of LHS, but the type
4922 // has to be different.
4923 return LHS;
4924 }
4925 if (RVAT) {
4926 // FIXME: This isn't correct! But tricky to implement because
4927 // the array's size has to be the size of RHS, but the type
4928 // has to be different.
4929 return RHS;
4930 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004931 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4932 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004933 return getIncompleteArrayType(ResultType,
4934 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004935 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004936 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00004937 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00004938 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004939 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004940 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004941 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004942 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004943 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004944 case Type::Complex:
4945 // Distinct complex types are incompatible.
4946 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004947 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004948 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004949 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4950 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004951 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004952 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004953 case Type::ObjCObject: {
4954 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004955 // FIXME: This should be type compatibility, e.g. whether
4956 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004957 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4958 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4959 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004960 return LHS;
4961
Eli Friedman3d815e72008-08-22 00:56:42 +00004962 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004963 }
Steve Naroff14108da2009-07-10 23:34:53 +00004964 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004965 if (OfBlockPointer) {
4966 if (canAssignObjCInterfacesInBlockPointer(
4967 LHS->getAs<ObjCObjectPointerType>(),
4968 RHS->getAs<ObjCObjectPointerType>()))
4969 return LHS;
4970 return QualType();
4971 }
John McCall183700f2009-09-21 23:43:11 +00004972 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4973 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004974 return LHS;
4975
Steve Naroffbc76dd02008-12-10 22:14:21 +00004976 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004977 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004978 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004979
4980 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004981}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004982
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004983/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4984/// 'RHS' attributes and returns the merged version; including for function
4985/// return types.
4986QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4987 QualType LHSCan = getCanonicalType(LHS),
4988 RHSCan = getCanonicalType(RHS);
4989 // If two types are identical, they are compatible.
4990 if (LHSCan == RHSCan)
4991 return LHS;
4992 if (RHSCan->isFunctionType()) {
4993 if (!LHSCan->isFunctionType())
4994 return QualType();
4995 QualType OldReturnType =
4996 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4997 QualType NewReturnType =
4998 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4999 QualType ResReturnType =
5000 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5001 if (ResReturnType.isNull())
5002 return QualType();
5003 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5004 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5005 // In either case, use OldReturnType to build the new function type.
5006 const FunctionType *F = LHS->getAs<FunctionType>();
5007 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5008 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5009 QualType ResultType
5010 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5011 FPT->getNumArgs(), FPT->isVariadic(),
5012 FPT->getTypeQuals(),
5013 FPT->hasExceptionSpec(),
5014 FPT->hasAnyExceptionSpec(),
5015 FPT->getNumExceptions(),
5016 FPT->exception_begin(),
5017 Info);
5018 return ResultType;
5019 }
5020 }
5021 return QualType();
5022 }
5023
5024 // If the qualifiers are different, the types can still be merged.
5025 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5026 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5027 if (LQuals != RQuals) {
5028 // If any of these qualifiers are different, we have a type mismatch.
5029 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5030 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5031 return QualType();
5032
5033 // Exactly one GC qualifier difference is allowed: __strong is
5034 // okay if the other type has no GC qualifier but is an Objective
5035 // C object pointer (i.e. implicitly strong by default). We fix
5036 // this by pretending that the unqualified type was actually
5037 // qualified __strong.
5038 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5039 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5040 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5041
5042 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5043 return QualType();
5044
5045 if (GC_L == Qualifiers::Strong)
5046 return LHS;
5047 if (GC_R == Qualifiers::Strong)
5048 return RHS;
5049 return QualType();
5050 }
5051
5052 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5053 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5054 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5055 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5056 if (ResQT == LHSBaseQT)
5057 return LHS;
5058 if (ResQT == RHSBaseQT)
5059 return RHS;
5060 }
5061 return QualType();
5062}
5063
Chris Lattner5426bf62008-04-07 07:01:58 +00005064//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005065// Integer Predicates
5066//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005067
Eli Friedmanad74a752008-06-28 06:23:08 +00005068unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005069 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005070 return 1;
John McCall842aef82009-12-09 09:09:27 +00005071 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005072 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005073 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005074 return (unsigned)getTypeSize(T);
5075}
5076
5077QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005078 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005079
5080 // Turn <4 x signed int> -> <4 x unsigned int>
5081 if (const VectorType *VTy = T->getAs<VectorType>())
5082 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005083 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005084
5085 // For enums, we return the unsigned version of the base type.
5086 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005087 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005088
5089 const BuiltinType *BTy = T->getAs<BuiltinType>();
5090 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005091 switch (BTy->getKind()) {
5092 case BuiltinType::Char_S:
5093 case BuiltinType::SChar:
5094 return UnsignedCharTy;
5095 case BuiltinType::Short:
5096 return UnsignedShortTy;
5097 case BuiltinType::Int:
5098 return UnsignedIntTy;
5099 case BuiltinType::Long:
5100 return UnsignedLongTy;
5101 case BuiltinType::LongLong:
5102 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005103 case BuiltinType::Int128:
5104 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005105 default:
5106 assert(0 && "Unexpected signed integer type");
5107 return QualType();
5108 }
5109}
5110
Douglas Gregor2cf26342009-04-09 22:27:44 +00005111ExternalASTSource::~ExternalASTSource() { }
5112
5113void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005114
5115
5116//===----------------------------------------------------------------------===//
5117// Builtin Type Computation
5118//===----------------------------------------------------------------------===//
5119
5120/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5121/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005122static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005123 ASTContext::GetBuiltinTypeError &Error,
5124 bool AllowTypeModifiers = true) {
5125 // Modifiers.
5126 int HowLong = 0;
5127 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005128
Chris Lattner86df27b2009-06-14 00:45:47 +00005129 // Read the modifiers first.
5130 bool Done = false;
5131 while (!Done) {
5132 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005133 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005134 case 'S':
5135 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5136 assert(!Signed && "Can't use 'S' modifier multiple times!");
5137 Signed = true;
5138 break;
5139 case 'U':
5140 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5141 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5142 Unsigned = true;
5143 break;
5144 case 'L':
5145 assert(HowLong <= 2 && "Can't have LLLL modifier");
5146 ++HowLong;
5147 break;
5148 }
5149 }
5150
5151 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005152
Chris Lattner86df27b2009-06-14 00:45:47 +00005153 // Read the base type.
5154 switch (*Str++) {
5155 default: assert(0 && "Unknown builtin type letter!");
5156 case 'v':
5157 assert(HowLong == 0 && !Signed && !Unsigned &&
5158 "Bad modifiers used with 'v'!");
5159 Type = Context.VoidTy;
5160 break;
5161 case 'f':
5162 assert(HowLong == 0 && !Signed && !Unsigned &&
5163 "Bad modifiers used with 'f'!");
5164 Type = Context.FloatTy;
5165 break;
5166 case 'd':
5167 assert(HowLong < 2 && !Signed && !Unsigned &&
5168 "Bad modifiers used with 'd'!");
5169 if (HowLong)
5170 Type = Context.LongDoubleTy;
5171 else
5172 Type = Context.DoubleTy;
5173 break;
5174 case 's':
5175 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5176 if (Unsigned)
5177 Type = Context.UnsignedShortTy;
5178 else
5179 Type = Context.ShortTy;
5180 break;
5181 case 'i':
5182 if (HowLong == 3)
5183 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5184 else if (HowLong == 2)
5185 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5186 else if (HowLong == 1)
5187 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5188 else
5189 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5190 break;
5191 case 'c':
5192 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5193 if (Signed)
5194 Type = Context.SignedCharTy;
5195 else if (Unsigned)
5196 Type = Context.UnsignedCharTy;
5197 else
5198 Type = Context.CharTy;
5199 break;
5200 case 'b': // boolean
5201 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5202 Type = Context.BoolTy;
5203 break;
5204 case 'z': // size_t.
5205 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5206 Type = Context.getSizeType();
5207 break;
5208 case 'F':
5209 Type = Context.getCFConstantStringType();
5210 break;
5211 case 'a':
5212 Type = Context.getBuiltinVaListType();
5213 assert(!Type.isNull() && "builtin va list type not initialized!");
5214 break;
5215 case 'A':
5216 // This is a "reference" to a va_list; however, what exactly
5217 // this means depends on how va_list is defined. There are two
5218 // different kinds of va_list: ones passed by value, and ones
5219 // passed by reference. An example of a by-value va_list is
5220 // x86, where va_list is a char*. An example of by-ref va_list
5221 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5222 // we want this argument to be a char*&; for x86-64, we want
5223 // it to be a __va_list_tag*.
5224 Type = Context.getBuiltinVaListType();
5225 assert(!Type.isNull() && "builtin va list type not initialized!");
5226 if (Type->isArrayType()) {
5227 Type = Context.getArrayDecayedType(Type);
5228 } else {
5229 Type = Context.getLValueReferenceType(Type);
5230 }
5231 break;
5232 case 'V': {
5233 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005234 unsigned NumElements = strtoul(Str, &End, 10);
5235 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005236
Chris Lattner86df27b2009-06-14 00:45:47 +00005237 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005238
Chris Lattner86df27b2009-06-14 00:45:47 +00005239 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005240 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005241 Type = Context.getVectorType(ElementType, NumElements,
5242 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005243 break;
5244 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005245 case 'X': {
5246 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5247 Type = Context.getComplexType(ElementType);
5248 break;
5249 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005250 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005251 Type = Context.getFILEType();
5252 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005253 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005254 return QualType();
5255 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005256 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005257 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005258 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005259 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005260 else
5261 Type = Context.getjmp_bufType();
5262
Mike Stumpfd612db2009-07-28 23:47:15 +00005263 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005264 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005265 return QualType();
5266 }
5267 break;
Mike Stump782fa302009-07-28 02:25:19 +00005268 }
Mike Stump1eb44332009-09-09 15:08:12 +00005269
Chris Lattner86df27b2009-06-14 00:45:47 +00005270 if (!AllowTypeModifiers)
5271 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005272
Chris Lattner86df27b2009-06-14 00:45:47 +00005273 Done = false;
5274 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005275 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005276 default: Done = true; --Str; break;
5277 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005278 case '&':
John McCall187ab372010-03-12 04:21:28 +00005279 {
5280 // Both pointers and references can have their pointee types
5281 // qualified with an address space.
5282 char *End;
5283 unsigned AddrSpace = strtoul(Str, &End, 10);
5284 if (End != Str && AddrSpace != 0) {
5285 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5286 Str = End;
5287 }
5288 }
5289 if (c == '*')
5290 Type = Context.getPointerType(Type);
5291 else
5292 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005293 break;
5294 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5295 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005296 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005297 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005298 case 'D':
5299 Type = Context.getVolatileType(Type);
5300 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005301 }
5302 }
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Chris Lattner86df27b2009-06-14 00:45:47 +00005304 return Type;
5305}
5306
5307/// GetBuiltinType - Return the type for the specified builtin.
5308QualType ASTContext::GetBuiltinType(unsigned id,
5309 GetBuiltinTypeError &Error) {
5310 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005311
Chris Lattner86df27b2009-06-14 00:45:47 +00005312 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Chris Lattner86df27b2009-06-14 00:45:47 +00005314 Error = GE_None;
5315 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5316 if (Error != GE_None)
5317 return QualType();
5318 while (TypeStr[0] && TypeStr[0] != '.') {
5319 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5320 if (Error != GE_None)
5321 return QualType();
5322
5323 // Do array -> pointer decay. The builtin should use the decayed type.
5324 if (Ty->isArrayType())
5325 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005326
Chris Lattner86df27b2009-06-14 00:45:47 +00005327 ArgTypes.push_back(Ty);
5328 }
5329
5330 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5331 "'.' should only occur at end of builtin type list!");
5332
5333 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5334 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5335 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005336
5337 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005338 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005339 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005340 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005341}
Eli Friedmana95d7572009-08-19 07:44:53 +00005342
5343QualType
5344ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5345 // Perform the usual unary conversions. We do this early so that
5346 // integral promotions to "int" can allow us to exit early, in the
5347 // lhs == rhs check. Also, for conversion purposes, we ignore any
5348 // qualifiers. For example, "const float" and "float" are
5349 // equivalent.
5350 if (lhs->isPromotableIntegerType())
5351 lhs = getPromotedIntegerType(lhs);
5352 else
5353 lhs = lhs.getUnqualifiedType();
5354 if (rhs->isPromotableIntegerType())
5355 rhs = getPromotedIntegerType(rhs);
5356 else
5357 rhs = rhs.getUnqualifiedType();
5358
5359 // If both types are identical, no conversion is needed.
5360 if (lhs == rhs)
5361 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005362
Eli Friedmana95d7572009-08-19 07:44:53 +00005363 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5364 // The caller can deal with this (e.g. pointer + int).
5365 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5366 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005367
5368 // At this point, we have two different arithmetic types.
5369
Eli Friedmana95d7572009-08-19 07:44:53 +00005370 // Handle complex types first (C99 6.3.1.8p1).
5371 if (lhs->isComplexType() || rhs->isComplexType()) {
5372 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005373 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005374 // convert the rhs to the lhs complex type.
5375 return lhs;
5376 }
Mike Stump1eb44332009-09-09 15:08:12 +00005377 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005378 // convert the lhs to the rhs complex type.
5379 return rhs;
5380 }
5381 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005382 // When both operands are complex, the shorter operand is converted to the
5383 // type of the longer, and that is the type of the result. This corresponds
5384 // to what is done when combining two real floating-point operands.
5385 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005386 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005387 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005388 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005389 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005390 // "double _Complex" is promoted to "long double _Complex".
5391 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005392
5393 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005394 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005395 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005396 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005397 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005398 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5399 // domains match. This is a requirement for our implementation, C99
5400 // does not require this promotion.
5401 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5402 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5403 return rhs;
5404 } else { // handle "_Complex double, double".
5405 return lhs;
5406 }
5407 }
5408 return lhs; // The domain/size match exactly.
5409 }
5410 // Now handle "real" floating types (i.e. float, double, long double).
5411 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5412 // if we have an integer operand, the result is the real floating type.
5413 if (rhs->isIntegerType()) {
5414 // convert rhs to the lhs floating point type.
5415 return lhs;
5416 }
5417 if (rhs->isComplexIntegerType()) {
5418 // convert rhs to the complex floating point type.
5419 return getComplexType(lhs);
5420 }
5421 if (lhs->isIntegerType()) {
5422 // convert lhs to the rhs floating point type.
5423 return rhs;
5424 }
Mike Stump1eb44332009-09-09 15:08:12 +00005425 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005426 // convert lhs to the complex floating point type.
5427 return getComplexType(rhs);
5428 }
5429 // We have two real floating types, float/complex combos were handled above.
5430 // Convert the smaller operand to the bigger result.
5431 int result = getFloatingTypeOrder(lhs, rhs);
5432 if (result > 0) // convert the rhs
5433 return lhs;
5434 assert(result < 0 && "illegal float comparison");
5435 return rhs; // convert the lhs
5436 }
5437 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5438 // Handle GCC complex int extension.
5439 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5440 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5441
5442 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005443 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005444 rhsComplexInt->getElementType()) >= 0)
5445 return lhs; // convert the rhs
5446 return rhs;
5447 } else if (lhsComplexInt && rhs->isIntegerType()) {
5448 // convert the rhs to the lhs complex type.
5449 return lhs;
5450 } else if (rhsComplexInt && lhs->isIntegerType()) {
5451 // convert the lhs to the rhs complex type.
5452 return rhs;
5453 }
5454 }
5455 // Finally, we have two differing integer types.
5456 // The rules for this case are in C99 6.3.1.8
5457 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005458 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5459 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005460 QualType destType;
5461 if (lhsSigned == rhsSigned) {
5462 // Same signedness; use the higher-ranked type
5463 destType = compare >= 0 ? lhs : rhs;
5464 } else if (compare != (lhsSigned ? 1 : -1)) {
5465 // The unsigned type has greater than or equal rank to the
5466 // signed type, so use the unsigned type
5467 destType = lhsSigned ? rhs : lhs;
5468 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5469 // The two types are different widths; if we are here, that
5470 // means the signed type is larger than the unsigned type, so
5471 // use the signed type.
5472 destType = lhsSigned ? lhs : rhs;
5473 } else {
5474 // The signed type is higher-ranked than the unsigned type,
5475 // but isn't actually any bigger (like unsigned int and long
5476 // on most 32-bit systems). Use the unsigned type corresponding
5477 // to the signed type.
5478 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5479 }
5480 return destType;
5481}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005482
5483GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5484 GVALinkage External = GVA_StrongExternal;
5485
5486 Linkage L = FD->getLinkage();
5487 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5488 FD->getType()->getLinkage() == UniqueExternalLinkage)
5489 L = UniqueExternalLinkage;
5490
5491 switch (L) {
5492 case NoLinkage:
5493 case InternalLinkage:
5494 case UniqueExternalLinkage:
5495 return GVA_Internal;
5496
5497 case ExternalLinkage:
5498 switch (FD->getTemplateSpecializationKind()) {
5499 case TSK_Undeclared:
5500 case TSK_ExplicitSpecialization:
5501 External = GVA_StrongExternal;
5502 break;
5503
5504 case TSK_ExplicitInstantiationDefinition:
5505 return GVA_ExplicitTemplateInstantiation;
5506
5507 case TSK_ExplicitInstantiationDeclaration:
5508 case TSK_ImplicitInstantiation:
5509 External = GVA_TemplateInstantiation;
5510 break;
5511 }
5512 }
5513
5514 if (!FD->isInlined())
5515 return External;
5516
5517 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5518 // GNU or C99 inline semantics. Determine whether this symbol should be
5519 // externally visible.
5520 if (FD->isInlineDefinitionExternallyVisible())
5521 return External;
5522
5523 // C99 inline semantics, where the symbol is not externally visible.
5524 return GVA_C99Inline;
5525 }
5526
5527 // C++0x [temp.explicit]p9:
5528 // [ Note: The intent is that an inline function that is the subject of
5529 // an explicit instantiation declaration will still be implicitly
5530 // instantiated when used so that the body can be considered for
5531 // inlining, but that no out-of-line copy of the inline function would be
5532 // generated in the translation unit. -- end note ]
5533 if (FD->getTemplateSpecializationKind()
5534 == TSK_ExplicitInstantiationDeclaration)
5535 return GVA_C99Inline;
5536
5537 return GVA_CXXInline;
5538}
5539
5540GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5541 // If this is a static data member, compute the kind of template
5542 // specialization. Otherwise, this variable is not part of a
5543 // template.
5544 TemplateSpecializationKind TSK = TSK_Undeclared;
5545 if (VD->isStaticDataMember())
5546 TSK = VD->getTemplateSpecializationKind();
5547
5548 Linkage L = VD->getLinkage();
5549 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5550 VD->getType()->getLinkage() == UniqueExternalLinkage)
5551 L = UniqueExternalLinkage;
5552
5553 switch (L) {
5554 case NoLinkage:
5555 case InternalLinkage:
5556 case UniqueExternalLinkage:
5557 return GVA_Internal;
5558
5559 case ExternalLinkage:
5560 switch (TSK) {
5561 case TSK_Undeclared:
5562 case TSK_ExplicitSpecialization:
5563 return GVA_StrongExternal;
5564
5565 case TSK_ExplicitInstantiationDeclaration:
5566 llvm_unreachable("Variable should not be instantiated");
5567 // Fall through to treat this like any other instantiation.
5568
5569 case TSK_ExplicitInstantiationDefinition:
5570 return GVA_ExplicitTemplateInstantiation;
5571
5572 case TSK_ImplicitInstantiation:
5573 return GVA_TemplateInstantiation;
5574 }
5575 }
5576
5577 return GVA_StrongExternal;
5578}
5579
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005580bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005581 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5582 if (!VD->isFileVarDecl())
5583 return false;
5584 } else if (!isa<FunctionDecl>(D))
5585 return false;
5586
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005587 // Weak references don't produce any output by themselves.
5588 if (D->hasAttr<WeakRefAttr>())
5589 return false;
5590
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005591 // Aliases and used decls are required.
5592 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5593 return true;
5594
5595 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5596 // Forward declarations aren't required.
5597 if (!FD->isThisDeclarationADefinition())
5598 return false;
5599
5600 // Constructors and destructors are required.
5601 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5602 return true;
5603
5604 // The key function for a class is required.
5605 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5606 const CXXRecordDecl *RD = MD->getParent();
5607 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5608 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5609 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5610 return true;
5611 }
5612 }
5613
5614 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5615
5616 // static, static inline, always_inline, and extern inline functions can
5617 // always be deferred. Normal inline functions can be deferred in C99/C++.
5618 // Implicit template instantiations can also be deferred in C++.
5619 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5620 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5621 return false;
5622 return true;
5623 }
5624
5625 const VarDecl *VD = cast<VarDecl>(D);
5626 assert(VD->isFileVarDecl() && "Expected file scoped var");
5627
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005628 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5629 return false;
5630
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005631 // Structs that have non-trivial constructors or destructors are required.
5632
5633 // FIXME: Handle references.
5634 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5635 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005636 if (RD->hasDefinition() &&
5637 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005638 return true;
5639 }
5640 }
5641
5642 GVALinkage L = GetGVALinkageForVariable(VD);
5643 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5644 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5645 return false;
5646 }
5647
5648 return true;
5649}
Charles Davis071cc7d2010-08-16 03:33:14 +00005650
5651CXXABI::~CXXABI() {}