blob: ef1138eee7238510e3bc2b08ad51bf5a4e2566fc [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000031
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Douglas Gregor9672f922010-07-03 00:47:00 +000034unsigned ASTContext::NumImplicitDefaultConstructors;
35unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000036unsigned ASTContext::NumImplicitCopyConstructors;
37unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000038unsigned ASTContext::NumImplicitCopyAssignmentOperators;
39unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000040unsigned ASTContext::NumImplicitDestructors;
41unsigned ASTContext::NumImplicitDestructorsDeclared;
42
Steve Naroff0af91202007-04-27 21:51:21 +000043enum FloatingRank {
44 FloatRank, DoubleRank, LongDoubleRank
45};
46
Douglas Gregor7dbfb462010-06-16 21:09:37 +000047void
48ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
49 TemplateTemplateParmDecl *Parm) {
50 ID.AddInteger(Parm->getDepth());
51 ID.AddInteger(Parm->getPosition());
52 // FIXME: Parameter pack
53
54 TemplateParameterList *Params = Parm->getTemplateParameters();
55 ID.AddInteger(Params->size());
56 for (TemplateParameterList::const_iterator P = Params->begin(),
57 PEnd = Params->end();
58 P != PEnd; ++P) {
59 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
60 ID.AddInteger(0);
61 ID.AddBoolean(TTP->isParameterPack());
62 continue;
63 }
64
65 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
66 ID.AddInteger(1);
67 // FIXME: Parameter pack
68 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
69 continue;
70 }
71
72 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
73 ID.AddInteger(2);
74 Profile(ID, TTP);
75 }
76}
77
78TemplateTemplateParmDecl *
79ASTContext::getCanonicalTemplateTemplateParmDecl(
80 TemplateTemplateParmDecl *TTP) {
81 // Check if we already have a canonical template template parameter.
82 llvm::FoldingSetNodeID ID;
83 CanonicalTemplateTemplateParm::Profile(ID, TTP);
84 void *InsertPos = 0;
85 CanonicalTemplateTemplateParm *Canonical
86 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
87 if (Canonical)
88 return Canonical->getParam();
89
90 // Build a canonical template parameter list.
91 TemplateParameterList *Params = TTP->getTemplateParameters();
92 llvm::SmallVector<NamedDecl *, 4> CanonParams;
93 CanonParams.reserve(Params->size());
94 for (TemplateParameterList::const_iterator P = Params->begin(),
95 PEnd = Params->end();
96 P != PEnd; ++P) {
97 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
98 CanonParams.push_back(
99 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
100 SourceLocation(), TTP->getDepth(),
101 TTP->getIndex(), 0, false,
102 TTP->isParameterPack()));
103 else if (NonTypeTemplateParmDecl *NTTP
104 = dyn_cast<NonTypeTemplateParmDecl>(*P))
105 CanonParams.push_back(
106 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
107 SourceLocation(), NTTP->getDepth(),
108 NTTP->getPosition(), 0,
109 getCanonicalType(NTTP->getType()),
110 0));
111 else
112 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
113 cast<TemplateTemplateParmDecl>(*P)));
114 }
115
116 TemplateTemplateParmDecl *CanonTTP
117 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
118 SourceLocation(), TTP->getDepth(),
119 TTP->getPosition(), 0,
120 TemplateParameterList::Create(*this, SourceLocation(),
121 SourceLocation(),
122 CanonParams.data(),
123 CanonParams.size(),
124 SourceLocation()));
125
126 // Get the new insert position for the node we care about.
127 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
128 assert(Canonical == 0 && "Shouldn't be in the map!");
129 (void)Canonical;
130
131 // Create the canonical template template parameter entry.
132 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
133 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
134 return CanonTTP;
135}
136
Chris Lattner465fa322008-10-05 17:34:18 +0000137ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000138 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000139 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000140 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000141 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000142 TemplateSpecializationTypes(this_()),
143 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000144 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
145 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000146 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000147 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000148 NullTypeSourceInfo(QualType()),
Douglas Gregor5b11d492010-07-25 17:53:33 +0000149 SourceMgr(SM), LangOpts(LOpts), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000150 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000151 BuiltinInfo(builtins),
152 DeclarationNames(*this),
153 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000154 LastSDM(0, 0),
155 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000156 ObjCIdRedefinitionType = QualType();
157 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000158 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000159 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000160 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000161 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000162}
163
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000164ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000165 // Release the DenseMaps associated with DeclContext objects.
166 // FIXME: Is this the ideal solution?
167 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000168
Douglas Gregor5b11d492010-07-25 17:53:33 +0000169 // Call all of the deallocation functions.
170 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
171 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000172
Douglas Gregor832940b2010-03-02 23:58:15 +0000173 // Release all of the memory associated with overridden C++ methods.
174 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
175 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
176 OM != OMEnd; ++OM)
177 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000178
Ted Kremenek076baeb2010-06-08 23:00:58 +0000179 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000180 // because they can contain DenseMaps.
181 for (llvm::DenseMap<const ObjCContainerDecl*,
182 const ASTRecordLayout*>::iterator
183 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
184 // Increment in loop to prevent using deallocated memory.
185 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
186 R->Destroy(*this);
187
Ted Kremenek076baeb2010-06-08 23:00:58 +0000188 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
189 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
190 // Increment in loop to prevent using deallocated memory.
191 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
192 R->Destroy(*this);
193 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000194 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000195
Douglas Gregor1a809332010-05-23 18:26:36 +0000196void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
197 Deallocations.push_back(std::make_pair(Callback, Data));
198}
199
Mike Stump11289f42009-09-09 15:08:12 +0000200void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000201ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
202 ExternalSource.reset(Source.take());
203}
204
Chris Lattner4eb445d2007-01-26 01:27:23 +0000205void ASTContext::PrintStats() const {
206 fprintf(stderr, "*** AST Context Stats:\n");
207 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000208
Douglas Gregora30d0462009-05-26 14:40:08 +0000209 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000210#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000211#define ABSTRACT_TYPE(Name, Parent)
212#include "clang/AST/TypeNodes.def"
213 0 // Extra
214 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000215
Chris Lattner4eb445d2007-01-26 01:27:23 +0000216 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
217 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000218 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000219 }
220
Douglas Gregora30d0462009-05-26 14:40:08 +0000221 unsigned Idx = 0;
222 unsigned TotalBytes = 0;
223#define TYPE(Name, Parent) \
224 if (counts[Idx]) \
225 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
226 TotalBytes += counts[Idx] * sizeof(Name##Type); \
227 ++Idx;
228#define ABSTRACT_TYPE(Name, Parent)
229#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000230
Douglas Gregora30d0462009-05-26 14:40:08 +0000231 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000232
Douglas Gregor7454c562010-07-02 20:37:36 +0000233 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000234 fprintf(stderr, " %u/%u implicit default constructors created\n",
235 NumImplicitDefaultConstructorsDeclared,
236 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000237 fprintf(stderr, " %u/%u implicit copy constructors created\n",
238 NumImplicitCopyConstructorsDeclared,
239 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000240 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
241 NumImplicitCopyAssignmentOperatorsDeclared,
242 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000243 fprintf(stderr, " %u/%u implicit destructors created\n",
244 NumImplicitDestructorsDeclared, NumImplicitDestructors);
245
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000246 if (ExternalSource.get()) {
247 fprintf(stderr, "\n");
248 ExternalSource->PrintStats();
249 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000250
Douglas Gregor5b11d492010-07-25 17:53:33 +0000251 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000252}
253
254
John McCall48f2d582009-10-23 23:03:21 +0000255void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000256 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000257 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000258 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000259}
260
Chris Lattner970e54e2006-11-12 00:37:36 +0000261void ASTContext::InitBuiltinTypes() {
262 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattner970e54e2006-11-12 00:37:36 +0000264 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000265 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000266
Chris Lattner970e54e2006-11-12 00:37:36 +0000267 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000268 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000269 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000270 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000271 InitBuiltinType(CharTy, BuiltinType::Char_S);
272 else
273 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000274 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000275 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
276 InitBuiltinType(ShortTy, BuiltinType::Short);
277 InitBuiltinType(IntTy, BuiltinType::Int);
278 InitBuiltinType(LongTy, BuiltinType::Long);
279 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner970e54e2006-11-12 00:37:36 +0000281 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000282 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
283 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
284 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
285 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
286 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattner970e54e2006-11-12 00:37:36 +0000288 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000289 InitBuiltinType(FloatTy, BuiltinType::Float);
290 InitBuiltinType(DoubleTy, BuiltinType::Double);
291 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000292
Chris Lattnerf122cef2009-04-30 02:43:43 +0000293 // GNU extension, 128-bit integers.
294 InitBuiltinType(Int128Ty, BuiltinType::Int128);
295 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
296
Chris Lattner007cb022009-02-26 23:43:47 +0000297 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
298 InitBuiltinType(WCharTy, BuiltinType::WChar);
299 else // C99
300 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000301
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000302 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
303 InitBuiltinType(Char16Ty, BuiltinType::Char16);
304 else // C99
305 Char16Ty = getFromTargetType(Target.getChar16Type());
306
307 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
308 InitBuiltinType(Char32Ty, BuiltinType::Char32);
309 else // C99
310 Char32Ty = getFromTargetType(Target.getChar32Type());
311
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000312 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000313 InitBuiltinType(OverloadTy, BuiltinType::Overload);
314
315 // Placeholder type for type-dependent expressions whose type is
316 // completely unknown. No code should ever check a type against
317 // DependentTy and users should never see it; however, it is here to
318 // help diagnose failures to properly check for type-dependent
319 // expressions.
320 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000321
Mike Stump11289f42009-09-09 15:08:12 +0000322 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000323 // not yet been deduced.
324 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattner970e54e2006-11-12 00:37:36 +0000326 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000327 FloatComplexTy = getComplexType(FloatTy);
328 DoubleComplexTy = getComplexType(DoubleTy);
329 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330
Steve Naroff66e9f332007-10-15 14:41:52 +0000331 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000332
Steve Naroff1329fa02009-07-15 18:40:39 +0000333 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
334 ObjCIdTypedefType = QualType();
335 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000336 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000337
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000338 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000339 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
340 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000341 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000342
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000343 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000344
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000345 // void * type
346 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000347
348 // nullptr type (C++0x 2.14.7)
349 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000350}
351
Douglas Gregor86d142a2009-10-08 07:24:58 +0000352MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000353ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000354 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000355 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000356 = InstantiatedFromStaticDataMember.find(Var);
357 if (Pos == InstantiatedFromStaticDataMember.end())
358 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000360 return Pos->second;
361}
362
Mike Stump11289f42009-09-09 15:08:12 +0000363void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000364ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000365 TemplateSpecializationKind TSK,
366 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000367 assert(Inst->isStaticDataMember() && "Not a static data member");
368 assert(Tmpl->isStaticDataMember() && "Not a static data member");
369 assert(!InstantiatedFromStaticDataMember[Inst] &&
370 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000371 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000372 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000373}
374
John McCalle61f2ba2009-11-18 02:36:19 +0000375NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000376ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000377 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000378 = InstantiatedFromUsingDecl.find(UUD);
379 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000380 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000381
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000382 return Pos->second;
383}
384
385void
John McCallb96ec562009-12-04 22:46:56 +0000386ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
387 assert((isa<UsingDecl>(Pattern) ||
388 isa<UnresolvedUsingValueDecl>(Pattern) ||
389 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
390 "pattern decl is not a using decl");
391 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
392 InstantiatedFromUsingDecl[Inst] = Pattern;
393}
394
395UsingShadowDecl *
396ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
397 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
398 = InstantiatedFromUsingShadowDecl.find(Inst);
399 if (Pos == InstantiatedFromUsingShadowDecl.end())
400 return 0;
401
402 return Pos->second;
403}
404
405void
406ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
407 UsingShadowDecl *Pattern) {
408 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
409 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000410}
411
Anders Carlsson5da84842009-09-01 04:26:58 +0000412FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
413 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
414 = InstantiatedFromUnnamedFieldDecl.find(Field);
415 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
416 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000417
Anders Carlsson5da84842009-09-01 04:26:58 +0000418 return Pos->second;
419}
420
421void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
422 FieldDecl *Tmpl) {
423 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
424 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
425 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
426 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000427
Anders Carlsson5da84842009-09-01 04:26:58 +0000428 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
429}
430
Douglas Gregor832940b2010-03-02 23:58:15 +0000431ASTContext::overridden_cxx_method_iterator
432ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
433 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
434 = OverriddenMethods.find(Method);
435 if (Pos == OverriddenMethods.end())
436 return 0;
437
438 return Pos->second.begin();
439}
440
441ASTContext::overridden_cxx_method_iterator
442ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
443 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
444 = OverriddenMethods.find(Method);
445 if (Pos == OverriddenMethods.end())
446 return 0;
447
448 return Pos->second.end();
449}
450
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000451unsigned
452ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
453 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
454 = OverriddenMethods.find(Method);
455 if (Pos == OverriddenMethods.end())
456 return 0;
457
458 return Pos->second.size();
459}
460
Douglas Gregor832940b2010-03-02 23:58:15 +0000461void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
462 const CXXMethodDecl *Overridden) {
463 OverriddenMethods[Method].push_back(Overridden);
464}
465
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000466namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000467 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 : std::binary_function<SourceRange, SourceRange, bool> {
469 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000471 public:
472 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000474 bool operator()(SourceRange X, SourceRange Y) {
475 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
476 }
477 };
478}
479
Chris Lattner53cfe802007-07-18 17:52:12 +0000480//===----------------------------------------------------------------------===//
481// Type Sizing and Analysis
482//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000483
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000484/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
485/// scalar floating point type.
486const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000487 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000488 assert(BT && "Not a floating point type!");
489 switch (BT->getKind()) {
490 default: assert(0 && "Not a floating point type!");
491 case BuiltinType::Float: return Target.getFloatFormat();
492 case BuiltinType::Double: return Target.getDoubleFormat();
493 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
494 }
495}
496
Ken Dyck160146e2010-01-27 17:10:57 +0000497/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000498/// specified decl. Note that bitfields do not have a valid alignment, so
499/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000500/// If @p RefAsPointee, references are treated like their underlying type
501/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000502CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000503 unsigned Align = Target.getCharWidth();
504
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000505 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000506 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000507
Chris Lattner68061312009-01-24 21:53:27 +0000508 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
509 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000510 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000511 if (RefAsPointee)
512 T = RT->getPointeeType();
513 else
514 T = getPointerType(RT->getPointeeType());
515 }
516 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000517 unsigned MinWidth = Target.getLargeArrayMinWidth();
518 unsigned ArrayAlign = Target.getLargeArrayAlign();
519 if (isa<VariableArrayType>(T) && MinWidth != 0)
520 Align = std::max(Align, ArrayAlign);
521 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
522 unsigned Size = getTypeSize(CT);
523 if (MinWidth != 0 && MinWidth <= Size)
524 Align = std::max(Align, ArrayAlign);
525 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000526 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000527 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
528 T = cast<ArrayType>(T)->getElementType();
529
530 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
531 }
Charles Davis3fc51072010-02-23 04:52:00 +0000532 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
533 // In the case of a field in a packed struct, we want the minimum
534 // of the alignment of the field and the alignment of the struct.
535 Align = std::min(Align,
536 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
537 }
Chris Lattner68061312009-01-24 21:53:27 +0000538 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000539
Ken Dyck160146e2010-01-27 17:10:57 +0000540 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000541}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000542
John McCall87fe5d52010-05-20 01:18:31 +0000543std::pair<CharUnits, CharUnits>
544ASTContext::getTypeInfoInChars(const Type *T) {
545 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
546 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
547 CharUnits::fromQuantity(Info.second / getCharWidth()));
548}
549
550std::pair<CharUnits, CharUnits>
551ASTContext::getTypeInfoInChars(QualType T) {
552 return getTypeInfoInChars(T.getTypePtr());
553}
554
Chris Lattner983a8bb2007-07-13 22:13:22 +0000555/// getTypeSize - Return the size of the specified type, in bits. This method
556/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000557///
558/// FIXME: Pointers into different addr spaces could have different sizes and
559/// alignment requirements: getPointerInfo should take an AddrSpace, this
560/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000561std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000562ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000563 uint64_t Width=0;
564 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000565 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000566#define TYPE(Class, Base)
567#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000568#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000569#define DEPENDENT_TYPE(Class, Base) case Type::Class:
570#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000571 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000572 break;
573
Chris Lattner355332d2007-07-13 22:27:08 +0000574 case Type::FunctionNoProto:
575 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000576 // GCC extension: alignof(function) = 32 bits
577 Width = 0;
578 Align = 32;
579 break;
580
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000581 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000582 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000583 Width = 0;
584 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
585 break;
586
Steve Naroff5c131802007-08-30 01:06:46 +0000587 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000588 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000589
Chris Lattner37e05872008-03-05 18:54:05 +0000590 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000591 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000592 Align = EltInfo.second;
593 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000594 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000595 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000596 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000597 const VectorType *VT = cast<VectorType>(T);
598 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
599 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000600 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000601 // If the alignment is not a power of 2, round up to the next power of 2.
602 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000603 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000604 Align = llvm::NextPowerOf2(Align);
605 Width = llvm::RoundUpToAlignment(Width, Align);
606 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000607 break;
608 }
Chris Lattner647fb222007-07-18 18:26:58 +0000609
Chris Lattner7570e9c2008-03-08 08:52:55 +0000610 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000611 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000612 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000613 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000614 // GCC extension: alignof(void) = 8 bits.
615 Width = 0;
616 Align = 8;
617 break;
618
Chris Lattner6a4f7452007-12-19 19:23:28 +0000619 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000620 Width = Target.getBoolWidth();
621 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000622 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000623 case BuiltinType::Char_S:
624 case BuiltinType::Char_U:
625 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000626 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000627 Width = Target.getCharWidth();
628 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000629 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000630 case BuiltinType::WChar:
631 Width = Target.getWCharWidth();
632 Align = Target.getWCharAlign();
633 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000634 case BuiltinType::Char16:
635 Width = Target.getChar16Width();
636 Align = Target.getChar16Align();
637 break;
638 case BuiltinType::Char32:
639 Width = Target.getChar32Width();
640 Align = Target.getChar32Align();
641 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000642 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000643 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000644 Width = Target.getShortWidth();
645 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000646 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000647 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000649 Width = Target.getIntWidth();
650 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000651 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000652 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000653 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000654 Width = Target.getLongWidth();
655 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000656 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000657 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000659 Width = Target.getLongLongWidth();
660 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000661 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000662 case BuiltinType::Int128:
663 case BuiltinType::UInt128:
664 Width = 128;
665 Align = 128; // int128_t is 128-bit aligned on all targets.
666 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000668 Width = Target.getFloatWidth();
669 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 break;
671 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000672 Width = Target.getDoubleWidth();
673 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 break;
675 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000676 Width = Target.getLongDoubleWidth();
677 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000678 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000679 case BuiltinType::NullPtr:
680 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
681 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000682 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000683 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000684 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000685 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000686 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000687 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000688 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000689 case Type::BlockPointer: {
690 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
691 Width = Target.getPointerWidth(AS);
692 Align = Target.getPointerAlign(AS);
693 break;
694 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000695 case Type::LValueReference:
696 case Type::RValueReference: {
697 // alignof and sizeof should never enter this code path here, so we go
698 // the pointer route.
699 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
700 Width = Target.getPointerWidth(AS);
701 Align = Target.getPointerAlign(AS);
702 break;
703 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000704 case Type::Pointer: {
705 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000706 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000707 Align = Target.getPointerAlign(AS);
708 break;
709 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000710 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000711 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000712 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000713 getTypeInfo(getPointerDiffType());
714 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000715 if (Pointee->isFunctionType())
716 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000717 Align = PtrDiffInfo.second;
718 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000719 }
Chris Lattner647fb222007-07-18 18:26:58 +0000720 case Type::Complex: {
721 // Complex types have the same alignment as their elements, but twice the
722 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000723 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000724 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000725 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000726 Align = EltInfo.second;
727 break;
728 }
John McCall8b07ec22010-05-15 11:32:37 +0000729 case Type::ObjCObject:
730 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000731 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000732 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000733 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
734 Width = Layout.getSize();
735 Align = Layout.getAlignment();
736 break;
737 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000738 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000739 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000740 const TagType *TT = cast<TagType>(T);
741
742 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000743 Width = 1;
744 Align = 1;
745 break;
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000748 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000749 return getTypeInfo(ET->getDecl()->getIntegerType());
750
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000751 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000752 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
753 Width = Layout.getSize();
754 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000755 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000756 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000757
Chris Lattner63d2b362009-10-22 05:17:15 +0000758 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000759 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
760 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000761
Douglas Gregoref462e62009-04-30 17:32:17 +0000762 case Type::Typedef: {
763 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000764 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000765 Align = std::max(Aligned->getMaxAlignment(),
766 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000767 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
768 } else
769 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000770 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000771 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000772
773 case Type::TypeOfExpr:
774 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
775 .getTypePtr());
776
777 case Type::TypeOf:
778 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
779
Anders Carlsson81df7b82009-06-24 19:06:50 +0000780 case Type::Decltype:
781 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
782 .getTypePtr());
783
Abramo Bagnara6150c882010-05-11 21:36:43 +0000784 case Type::Elaborated:
785 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000786
Douglas Gregoref462e62009-04-30 17:32:17 +0000787 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000788 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000789 "Cannot request the size of a dependent type");
790 // FIXME: this is likely to be wrong once we support template
791 // aliases, since a template alias could refer to a typedef that
792 // has an __aligned__ attribute on it.
793 return getTypeInfo(getCanonicalType(T));
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Chris Lattner53cfe802007-07-18 17:52:12 +0000796 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000797 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000798}
799
Ken Dyck8c89d592009-12-22 14:23:30 +0000800/// getTypeSizeInChars - Return the size of the specified type, in characters.
801/// This method does not work on incomplete types.
802CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000803 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000804}
805CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000806 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000807}
808
Ken Dycka6046ab2010-01-26 17:25:18 +0000809/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000810/// characters. This method does not work on incomplete types.
811CharUnits ASTContext::getTypeAlignInChars(QualType T) {
812 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
813}
814CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
815 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
816}
817
Chris Lattnera3402cd2009-01-27 18:08:34 +0000818/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
819/// type for the current target in bits. This can be different than the ABI
820/// alignment in cases where it is beneficial for performance to overalign
821/// a data type.
822unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
823 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000824
825 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000826 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000827 T = CT->getElementType().getTypePtr();
828 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
829 T->isSpecificBuiltinType(BuiltinType::LongLong))
830 return std::max(ABIAlign, (unsigned)getTypeSize(T));
831
Chris Lattnera3402cd2009-01-27 18:08:34 +0000832 return ABIAlign;
833}
834
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000835static void CollectLocalObjCIvars(ASTContext *Ctx,
836 const ObjCInterfaceDecl *OI,
837 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000838 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
839 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000840 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000841 if (!IVDecl->isInvalidDecl())
842 Fields.push_back(cast<FieldDecl>(IVDecl));
843 }
844}
845
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000846void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
847 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
848 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
849 CollectObjCIvars(SuperClass, Fields);
850 CollectLocalObjCIvars(this, OI, Fields);
851}
852
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000853/// ShallowCollectObjCIvars -
854/// Collect all ivars, including those synthesized, in the current class.
855///
856void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000857 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000858 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
859 E = OI->ivar_end(); I != E; ++I) {
860 Ivars.push_back(*I);
861 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000862
863 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000864}
865
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000866/// CollectNonClassIvars -
867/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000868/// This includes synthesized ivars (via @synthesize) and those in
869// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000870///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000871void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000872 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000873 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000874 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
875 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000876 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
877 E = CDecl->ivar_end(); I != E; ++I) {
878 Ivars.push_back(*I);
879 }
880 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000881
Ted Kremenek86838aa2010-03-11 19:44:54 +0000882 // Also add any ivar defined in this class's implementation. This
883 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000884 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
885 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
886 E = ImplDecl->ivar_end(); I != E; ++I)
887 Ivars.push_back(*I);
888 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000889}
890
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000891/// CollectInheritedProtocols - Collect all protocols in current class and
892/// those inherited by it.
893void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000894 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000895 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
896 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
897 PE = OI->protocol_end(); P != PE; ++P) {
898 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000899 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000900 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000901 PE = Proto->protocol_end(); P != PE; ++P) {
902 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000903 CollectInheritedProtocols(*P, Protocols);
904 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000905 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000906
907 // Categories of this Interface.
908 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
909 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
910 CollectInheritedProtocols(CDeclChain, Protocols);
911 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
912 while (SD) {
913 CollectInheritedProtocols(SD, Protocols);
914 SD = SD->getSuperClass();
915 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000916 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000917 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
918 PE = OC->protocol_end(); P != PE; ++P) {
919 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000920 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000921 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
922 PE = Proto->protocol_end(); P != PE; ++P)
923 CollectInheritedProtocols(*P, Protocols);
924 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000925 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000926 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
927 PE = OP->protocol_end(); P != PE; ++P) {
928 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000929 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000930 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
931 PE = Proto->protocol_end(); P != PE; ++P)
932 CollectInheritedProtocols(*P, Protocols);
933 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000934 }
935}
936
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000937unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
938 unsigned count = 0;
939 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000940 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
941 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000942 count += CDecl->ivar_size();
943
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000944 // Count ivar defined in this class's implementation. This
945 // includes synthesized ivars.
946 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000947 count += ImplDecl->ivar_size();
948
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000949 return count;
950}
951
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000952/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
953ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
954 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
955 I = ObjCImpls.find(D);
956 if (I != ObjCImpls.end())
957 return cast<ObjCImplementationDecl>(I->second);
958 return 0;
959}
960/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
961ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
962 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
963 I = ObjCImpls.find(D);
964 if (I != ObjCImpls.end())
965 return cast<ObjCCategoryImplDecl>(I->second);
966 return 0;
967}
968
969/// \brief Set the implementation of ObjCInterfaceDecl.
970void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
971 ObjCImplementationDecl *ImplD) {
972 assert(IFaceD && ImplD && "Passed null params");
973 ObjCImpls[IFaceD] = ImplD;
974}
975/// \brief Set the implementation of ObjCCategoryDecl.
976void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
977 ObjCCategoryImplDecl *ImplD) {
978 assert(CatD && ImplD && "Passed null params");
979 ObjCImpls[CatD] = ImplD;
980}
981
John McCallbcd03502009-12-07 02:54:59 +0000982/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000983///
John McCallbcd03502009-12-07 02:54:59 +0000984/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000985/// the TypeLoc wrappers.
986///
987/// \param T the type that will be the basis for type source info. This type
988/// should refer to how the declarator was written in source code, not to
989/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000990TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000991 unsigned DataSize) {
992 if (!DataSize)
993 DataSize = TypeLoc::getFullDataSizeForType(T);
994 else
995 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000996 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000997
John McCallbcd03502009-12-07 02:54:59 +0000998 TypeSourceInfo *TInfo =
999 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1000 new (TInfo) TypeSourceInfo(T);
1001 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001002}
1003
John McCallbcd03502009-12-07 02:54:59 +00001004TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001005 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001006 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001007 DI->getTypeLoc().initialize(L);
1008 return DI;
1009}
1010
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001011const ASTRecordLayout &
1012ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1013 return getObjCLayout(D, 0);
1014}
1015
1016const ASTRecordLayout &
1017ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1018 return getObjCLayout(D->getClassInterface(), D);
1019}
1020
Chris Lattner983a8bb2007-07-13 22:13:22 +00001021//===----------------------------------------------------------------------===//
1022// Type creation/memoization methods
1023//===----------------------------------------------------------------------===//
1024
John McCall8ccfcb52009-09-24 19:53:00 +00001025QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1026 unsigned Fast = Quals.getFastQualifiers();
1027 Quals.removeFastQualifiers();
1028
1029 // Check if we've already instantiated this type.
1030 llvm::FoldingSetNodeID ID;
1031 ExtQuals::Profile(ID, TypeNode, Quals);
1032 void *InsertPos = 0;
1033 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1034 assert(EQ->getQualifiers() == Quals);
1035 QualType T = QualType(EQ, Fast);
1036 return T;
1037 }
1038
John McCall90d1c2d2009-09-24 23:30:46 +00001039 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001040 ExtQualNodes.InsertNode(New, InsertPos);
1041 QualType T = QualType(New, Fast);
1042 return T;
1043}
1044
1045QualType ASTContext::getVolatileType(QualType T) {
1046 QualType CanT = getCanonicalType(T);
1047 if (CanT.isVolatileQualified()) return T;
1048
1049 QualifierCollector Quals;
1050 const Type *TypeNode = Quals.strip(T);
1051 Quals.addVolatile();
1052
1053 return getExtQualType(TypeNode, Quals);
1054}
1055
Fariborz Jahanianece85822009-02-17 18:27:45 +00001056QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001057 QualType CanT = getCanonicalType(T);
1058 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001059 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001060
John McCall8ccfcb52009-09-24 19:53:00 +00001061 // If we are composing extended qualifiers together, merge together
1062 // into one ExtQuals node.
1063 QualifierCollector Quals;
1064 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001065
John McCall8ccfcb52009-09-24 19:53:00 +00001066 // If this type already has an address space specified, it cannot get
1067 // another one.
1068 assert(!Quals.hasAddressSpace() &&
1069 "Type cannot be in multiple addr spaces!");
1070 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001071
John McCall8ccfcb52009-09-24 19:53:00 +00001072 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001073}
1074
Chris Lattnerd60183d2009-02-18 22:53:11 +00001075QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001076 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001077 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001078 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001079 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001080
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001081 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001082 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001083 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001084 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1085 return getPointerType(ResultType);
1086 }
1087 }
Mike Stump11289f42009-09-09 15:08:12 +00001088
John McCall8ccfcb52009-09-24 19:53:00 +00001089 // If we are composing extended qualifiers together, merge together
1090 // into one ExtQuals node.
1091 QualifierCollector Quals;
1092 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001093
John McCall8ccfcb52009-09-24 19:53:00 +00001094 // If this type already has an ObjCGC specified, it cannot get
1095 // another one.
1096 assert(!Quals.hasObjCGCAttr() &&
1097 "Type cannot have multiple ObjCGCs!");
1098 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001099
John McCall8ccfcb52009-09-24 19:53:00 +00001100 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001101}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001102
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001103static QualType getExtFunctionType(ASTContext& Context, QualType T,
1104 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001105 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001106 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1107 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001108 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001109 if (ResultType == Pointee)
1110 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001111
1112 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001113 } else if (const BlockPointerType *BlockPointer
1114 = T->getAs<BlockPointerType>()) {
1115 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001116 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001117 if (ResultType == Pointee)
1118 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001119
1120 ResultType = Context.getBlockPointerType(ResultType);
1121 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001122 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001123 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001124
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001125 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001126 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001127 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001128 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001129 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001130 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001131 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1132 FPT->getNumArgs(), FPT->isVariadic(),
1133 FPT->getTypeQuals(),
1134 FPT->hasExceptionSpec(),
1135 FPT->hasAnyExceptionSpec(),
1136 FPT->getNumExceptions(),
1137 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001138 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001139 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001140 } else
1141 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001142
1143 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1144}
1145
1146QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001147 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001148 return getExtFunctionType(*this, T,
1149 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001150}
1151
1152QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001153 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001154 return getExtFunctionType(*this, T,
1155 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001156}
1157
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001158QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1159 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1160 return getExtFunctionType(*this, T,
1161 Info.withRegParm(RegParm));
1162}
1163
Chris Lattnerc6395932007-06-22 20:56:16 +00001164/// getComplexType - Return the uniqued reference to the type for a complex
1165/// number with the specified element type.
1166QualType ASTContext::getComplexType(QualType T) {
1167 // Unique pointers, to guarantee there is only one pointer of a particular
1168 // structure.
1169 llvm::FoldingSetNodeID ID;
1170 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001171
Chris Lattnerc6395932007-06-22 20:56:16 +00001172 void *InsertPos = 0;
1173 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1174 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerc6395932007-06-22 20:56:16 +00001176 // If the pointee type isn't canonical, this won't be a canonical type either,
1177 // so fill in the canonical type field.
1178 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001179 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001180 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattnerc6395932007-06-22 20:56:16 +00001182 // Get the new insert position for the node we care about.
1183 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001184 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001185 }
John McCall90d1c2d2009-09-24 23:30:46 +00001186 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001187 Types.push_back(New);
1188 ComplexTypes.InsertNode(New, InsertPos);
1189 return QualType(New, 0);
1190}
1191
Chris Lattner970e54e2006-11-12 00:37:36 +00001192/// getPointerType - Return the uniqued reference to the type for a pointer to
1193/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001194QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001195 // Unique pointers, to guarantee there is only one pointer of a particular
1196 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001197 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001198 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattner67521df2007-01-27 01:29:36 +00001200 void *InsertPos = 0;
1201 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001202 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattner7ccecb92006-11-12 08:50:50 +00001204 // If the pointee type isn't canonical, this won't be a canonical type either,
1205 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001206 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001207 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001208 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner67521df2007-01-27 01:29:36 +00001210 // Get the new insert position for the node we care about.
1211 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001212 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001213 }
John McCall90d1c2d2009-09-24 23:30:46 +00001214 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001215 Types.push_back(New);
1216 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001217 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001218}
1219
Mike Stump11289f42009-09-09 15:08:12 +00001220/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001221/// a pointer to the specified block.
1222QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001223 assert(T->isFunctionType() && "block of function types only");
1224 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001225 // structure.
1226 llvm::FoldingSetNodeID ID;
1227 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001228
Steve Naroffec33ed92008-08-27 16:04:49 +00001229 void *InsertPos = 0;
1230 if (BlockPointerType *PT =
1231 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1232 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001233
1234 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001235 // type either so fill in the canonical type field.
1236 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001237 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001238 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001239
Steve Naroffec33ed92008-08-27 16:04:49 +00001240 // Get the new insert position for the node we care about.
1241 BlockPointerType *NewIP =
1242 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001243 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 }
John McCall90d1c2d2009-09-24 23:30:46 +00001245 BlockPointerType *New
1246 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001247 Types.push_back(New);
1248 BlockPointerTypes.InsertNode(New, InsertPos);
1249 return QualType(New, 0);
1250}
1251
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001252/// getLValueReferenceType - Return the uniqued reference to the type for an
1253/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001254QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001255 // Unique pointers, to guarantee there is only one pointer of a particular
1256 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001257 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001258 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001259
1260 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001261 if (LValueReferenceType *RT =
1262 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001263 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001264
John McCallfc93cf92009-10-22 22:37:11 +00001265 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1266
Bill Wendling3708c182007-05-27 10:15:43 +00001267 // If the referencee type isn't canonical, this won't be a canonical type
1268 // either, so fill in the canonical type field.
1269 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001270 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1271 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1272 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001273
Bill Wendling3708c182007-05-27 10:15:43 +00001274 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001275 LValueReferenceType *NewIP =
1276 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001277 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001278 }
1279
John McCall90d1c2d2009-09-24 23:30:46 +00001280 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001281 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1282 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001283 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001284 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001285
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001286 return QualType(New, 0);
1287}
1288
1289/// getRValueReferenceType - Return the uniqued reference to the type for an
1290/// rvalue reference to the specified type.
1291QualType ASTContext::getRValueReferenceType(QualType T) {
1292 // Unique pointers, to guarantee there is only one pointer of a particular
1293 // structure.
1294 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001295 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001296
1297 void *InsertPos = 0;
1298 if (RValueReferenceType *RT =
1299 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1300 return QualType(RT, 0);
1301
John McCallfc93cf92009-10-22 22:37:11 +00001302 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1303
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001304 // If the referencee type isn't canonical, this won't be a canonical type
1305 // either, so fill in the canonical type field.
1306 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001307 if (InnerRef || !T.isCanonical()) {
1308 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1309 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001310
1311 // Get the new insert position for the node we care about.
1312 RValueReferenceType *NewIP =
1313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1314 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1315 }
1316
John McCall90d1c2d2009-09-24 23:30:46 +00001317 RValueReferenceType *New
1318 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001319 Types.push_back(New);
1320 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001321 return QualType(New, 0);
1322}
1323
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001324/// getMemberPointerType - Return the uniqued reference to the type for a
1325/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001326QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001327 // Unique pointers, to guarantee there is only one pointer of a particular
1328 // structure.
1329 llvm::FoldingSetNodeID ID;
1330 MemberPointerType::Profile(ID, T, Cls);
1331
1332 void *InsertPos = 0;
1333 if (MemberPointerType *PT =
1334 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1335 return QualType(PT, 0);
1336
1337 // If the pointee or class type isn't canonical, this won't be a canonical
1338 // type either, so fill in the canonical type field.
1339 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001340 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001341 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1342
1343 // Get the new insert position for the node we care about.
1344 MemberPointerType *NewIP =
1345 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1346 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1347 }
John McCall90d1c2d2009-09-24 23:30:46 +00001348 MemberPointerType *New
1349 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001350 Types.push_back(New);
1351 MemberPointerTypes.InsertNode(New, InsertPos);
1352 return QualType(New, 0);
1353}
1354
Mike Stump11289f42009-09-09 15:08:12 +00001355/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001356/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001357QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001358 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001359 ArrayType::ArraySizeModifier ASM,
1360 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001361 assert((EltTy->isDependentType() ||
1362 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001363 "Constant array of VLAs is illegal!");
1364
Chris Lattnere2df3f92009-05-13 04:12:56 +00001365 // Convert the array size into a canonical width matching the pointer size for
1366 // the target.
1367 llvm::APInt ArySize(ArySizeIn);
1368 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattner23b7eb62007-06-15 23:05:46 +00001370 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001371 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattner36f8e652007-01-27 08:31:04 +00001373 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001374 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001375 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001376 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001377
Chris Lattner7ccecb92006-11-12 08:50:50 +00001378 // If the element type isn't canonical, this won't be a canonical type either,
1379 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001380 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001381 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001382 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001383 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001384 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001385 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001386 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001387 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001388 }
Mike Stump11289f42009-09-09 15:08:12 +00001389
John McCall90d1c2d2009-09-24 23:30:46 +00001390 ConstantArrayType *New = new(*this,TypeAlignment)
1391 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001392 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001393 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001394 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001395}
1396
Steve Naroffcadebd02007-08-30 18:14:25 +00001397/// getVariableArrayType - Returns a non-unique reference to the type for a
1398/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001399QualType ASTContext::getVariableArrayType(QualType EltTy,
1400 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001401 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001402 unsigned EltTypeQuals,
1403 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001404 // Since we don't unique expressions, it isn't possible to unique VLA's
1405 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001406 QualType CanonType;
1407
1408 if (!EltTy.isCanonical()) {
1409 if (NumElts)
1410 NumElts->Retain();
1411 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1412 EltTypeQuals, Brackets);
1413 }
1414
John McCall90d1c2d2009-09-24 23:30:46 +00001415 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001416 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001417
1418 VariableArrayTypes.push_back(New);
1419 Types.push_back(New);
1420 return QualType(New, 0);
1421}
1422
Douglas Gregor4619e432008-12-05 23:32:09 +00001423/// getDependentSizedArrayType - Returns a non-unique reference to
1424/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001425/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001426QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1427 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001428 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001429 unsigned EltTypeQuals,
1430 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001431 assert((!NumElts || NumElts->isTypeDependent() ||
1432 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001433 "Size must be type- or value-dependent!");
1434
Douglas Gregorf3f95522009-07-31 00:23:35 +00001435 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001436 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001437 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001438
1439 if (NumElts) {
1440 // Dependently-sized array types that do not have a specified
1441 // number of elements will have their sizes deduced from an
1442 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001443 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1444 EltTypeQuals, NumElts);
1445
1446 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1447 }
1448
Douglas Gregorf3f95522009-07-31 00:23:35 +00001449 DependentSizedArrayType *New;
1450 if (Canon) {
1451 // We already have a canonical version of this array type; use it as
1452 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001453 New = new (*this, TypeAlignment)
1454 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1455 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001456 } else {
1457 QualType CanonEltTy = getCanonicalType(EltTy);
1458 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001459 New = new (*this, TypeAlignment)
1460 DependentSizedArrayType(*this, EltTy, QualType(),
1461 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001462
Douglas Gregorc42075a2010-02-04 18:10:26 +00001463 if (NumElts) {
1464 DependentSizedArrayType *CanonCheck
1465 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1466 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1467 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001468 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001469 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001470 } else {
1471 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1472 ASM, EltTypeQuals,
1473 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001474 New = new (*this, TypeAlignment)
1475 DependentSizedArrayType(*this, EltTy, Canon,
1476 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001477 }
1478 }
Mike Stump11289f42009-09-09 15:08:12 +00001479
Douglas Gregor4619e432008-12-05 23:32:09 +00001480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
Eli Friedmanbd258282008-02-15 18:16:39 +00001484QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1485 ArrayType::ArraySizeModifier ASM,
1486 unsigned EltTypeQuals) {
1487 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001488 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001489
1490 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001491 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001492 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1493 return QualType(ATP, 0);
1494
1495 // If the element type isn't canonical, this won't be a canonical type
1496 // either, so fill in the canonical type field.
1497 QualType Canonical;
1498
John McCallb692a092009-10-22 20:10:53 +00001499 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001500 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001501 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001502
1503 // Get the new insert position for the node we care about.
1504 IncompleteArrayType *NewIP =
1505 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001506 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001507 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001508
John McCall90d1c2d2009-09-24 23:30:46 +00001509 IncompleteArrayType *New = new (*this, TypeAlignment)
1510 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001511
1512 IncompleteArrayTypes.InsertNode(New, InsertPos);
1513 Types.push_back(New);
1514 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001515}
1516
Steve Naroff91fcddb2007-07-18 18:00:27 +00001517/// getVectorType - Return the unique reference to a vector type of
1518/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001519QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001520 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001521 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattner76a00cf2008-04-06 22:59:24 +00001523 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001524 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001525
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001526 // Check if we've already instantiated a vector of this type.
1527 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001528 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1529
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001530 void *InsertPos = 0;
1531 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1532 return QualType(VTP, 0);
1533
1534 // If the element type isn't canonical, this won't be a canonical type either,
1535 // so fill in the canonical type field.
1536 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001537 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1538 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1539 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1540 // the equivalent GCC vector types
1541 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1542 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001544 // Get the new insert position for the node we care about.
1545 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001546 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001547 }
John McCall90d1c2d2009-09-24 23:30:46 +00001548 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001549 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001550 VectorTypes.InsertNode(New, InsertPos);
1551 Types.push_back(New);
1552 return QualType(New, 0);
1553}
1554
Nate Begemance4d7fc2008-04-18 23:10:10 +00001555/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001556/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001557QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001558 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattner76a00cf2008-04-06 22:59:24 +00001560 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001561 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001562
Steve Naroff91fcddb2007-07-18 18:00:27 +00001563 // Check if we've already instantiated a vector of this type.
1564 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001565 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1566 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001567 void *InsertPos = 0;
1568 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1569 return QualType(VTP, 0);
1570
1571 // If the element type isn't canonical, this won't be a canonical type either,
1572 // so fill in the canonical type field.
1573 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001574 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001575 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Steve Naroff91fcddb2007-07-18 18:00:27 +00001577 // Get the new insert position for the node we care about.
1578 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001579 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001580 }
John McCall90d1c2d2009-09-24 23:30:46 +00001581 ExtVectorType *New = new (*this, TypeAlignment)
1582 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001583 VectorTypes.InsertNode(New, InsertPos);
1584 Types.push_back(New);
1585 return QualType(New, 0);
1586}
1587
Mike Stump11289f42009-09-09 15:08:12 +00001588QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001589 Expr *SizeExpr,
1590 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001591 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001592 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001593 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001594
Douglas Gregor352169a2009-07-31 03:54:25 +00001595 void *InsertPos = 0;
1596 DependentSizedExtVectorType *Canon
1597 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1598 DependentSizedExtVectorType *New;
1599 if (Canon) {
1600 // We already have a canonical version of this array type; use it as
1601 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001602 New = new (*this, TypeAlignment)
1603 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1604 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001605 } else {
1606 QualType CanonVecTy = getCanonicalType(vecType);
1607 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001608 New = new (*this, TypeAlignment)
1609 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1610 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001611
1612 DependentSizedExtVectorType *CanonCheck
1613 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1614 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1615 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001616 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1617 } else {
1618 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1619 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001620 New = new (*this, TypeAlignment)
1621 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001622 }
1623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregor758a8692009-06-17 21:51:59 +00001625 Types.push_back(New);
1626 return QualType(New, 0);
1627}
1628
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001629/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001630///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001631QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1632 const FunctionType::ExtInfo &Info) {
1633 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001634 // Unique functions, to guarantee there is only one function of a particular
1635 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001636 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001637 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattner47955de2007-01-27 08:37:20 +00001639 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001640 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001641 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001642 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001643
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001644 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001645 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001646 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001647 Canonical =
1648 getFunctionNoProtoType(getCanonicalType(ResultTy),
1649 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattner47955de2007-01-27 08:37:20 +00001651 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001652 FunctionNoProtoType *NewIP =
1653 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001654 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
John McCall90d1c2d2009-09-24 23:30:46 +00001657 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001658 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001659 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001660 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001661 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001662}
1663
1664/// getFunctionType - Return a normal function type with a typed argument
1665/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001666QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001667 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001668 unsigned TypeQuals, bool hasExceptionSpec,
1669 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001670 const QualType *ExArray,
1671 const FunctionType::ExtInfo &Info) {
1672 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001673 // Unique functions, to guarantee there is only one function of a particular
1674 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001675 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001676 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001677 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001678 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001679
1680 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001681 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001682 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001683 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001684
1685 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001686 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001687 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001688 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001689 isCanonical = false;
1690
1691 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001692 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001693 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001694 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001695 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001696 CanonicalArgs.reserve(NumArgs);
1697 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001698 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001699
Chris Lattner76a00cf2008-04-06 22:59:24 +00001700 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001701 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001702 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001703 false, 0, 0,
1704 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001705
Chris Lattnerfd4de792007-01-27 01:15:32 +00001706 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001707 FunctionProtoType *NewIP =
1708 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001709 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001710 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001711
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001712 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001713 // for two variable size arrays (for parameter and exception types) at the
1714 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001715 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001716 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1717 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001718 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001719 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001720 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001721 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001722 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001723 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001724 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001725}
Chris Lattneref51c202006-11-10 07:17:23 +00001726
John McCalle78aac42010-03-10 03:28:59 +00001727#ifndef NDEBUG
1728static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1729 if (!isa<CXXRecordDecl>(D)) return false;
1730 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1731 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1732 return true;
1733 if (RD->getDescribedClassTemplate() &&
1734 !isa<ClassTemplateSpecializationDecl>(RD))
1735 return true;
1736 return false;
1737}
1738#endif
1739
1740/// getInjectedClassNameType - Return the unique reference to the
1741/// injected class name type for the specified templated declaration.
1742QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1743 QualType TST) {
1744 assert(NeedsInjectedClassNameType(Decl));
1745 if (Decl->TypeForDecl) {
1746 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001747 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001748 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1749 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1750 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1751 } else {
John McCall2408e322010-04-27 00:57:59 +00001752 Decl->TypeForDecl =
1753 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001754 Types.push_back(Decl->TypeForDecl);
1755 }
1756 return QualType(Decl->TypeForDecl, 0);
1757}
1758
Douglas Gregor83a586e2008-04-13 21:07:44 +00001759/// getTypeDeclType - Return the unique reference to the type for the
1760/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001761QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001762 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001763 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001764
John McCall81e38502010-02-16 03:57:14 +00001765 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001766 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001767
John McCall96f0b5f2010-03-10 06:48:02 +00001768 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1769 "Template type parameter types are always available.");
1770
John McCall81e38502010-02-16 03:57:14 +00001771 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001772 assert(!Record->getPreviousDeclaration() &&
1773 "struct/union has previous declaration");
1774 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001775 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001776 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001777 assert(!Enum->getPreviousDeclaration() &&
1778 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001779 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001780 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001781 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1782 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001783 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001784 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001785
John McCall96f0b5f2010-03-10 06:48:02 +00001786 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001787 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001788}
1789
Chris Lattner32d920b2007-01-26 02:01:53 +00001790/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001791/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001792QualType
1793ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001794 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001796 if (Canonical.isNull())
1797 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001798 Decl->TypeForDecl = new(*this, TypeAlignment)
1799 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001800 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001801 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001802}
1803
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001804QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1805 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1806
1807 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1808 if (PrevDecl->TypeForDecl)
1809 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1810
1811 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1812 Types.push_back(Decl->TypeForDecl);
1813 return QualType(Decl->TypeForDecl, 0);
1814}
1815
1816QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1817 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1818
1819 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1820 if (PrevDecl->TypeForDecl)
1821 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1822
1823 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1824 Types.push_back(Decl->TypeForDecl);
1825 return QualType(Decl->TypeForDecl, 0);
1826}
1827
John McCallcebee162009-10-18 09:09:24 +00001828/// \brief Retrieve a substitution-result type.
1829QualType
1830ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1831 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001832 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001833 && "replacement types must always be canonical");
1834
1835 llvm::FoldingSetNodeID ID;
1836 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1837 void *InsertPos = 0;
1838 SubstTemplateTypeParmType *SubstParm
1839 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1840
1841 if (!SubstParm) {
1842 SubstParm = new (*this, TypeAlignment)
1843 SubstTemplateTypeParmType(Parm, Replacement);
1844 Types.push_back(SubstParm);
1845 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1846 }
1847
1848 return QualType(SubstParm, 0);
1849}
1850
Douglas Gregoreff93e02009-02-05 23:33:38 +00001851/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001852/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001853/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001854QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001855 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001856 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001857 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001858 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001859 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001860 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001861 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1862
1863 if (TypeParm)
1864 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001866 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001867 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001868 TypeParm = new (*this, TypeAlignment)
1869 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001870
1871 TemplateTypeParmType *TypeCheck
1872 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1873 assert(!TypeCheck && "Template type parameter canonical type broken");
1874 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001875 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001876 TypeParm = new (*this, TypeAlignment)
1877 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001878
1879 Types.push_back(TypeParm);
1880 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1881
1882 return QualType(TypeParm, 0);
1883}
1884
John McCalle78aac42010-03-10 03:28:59 +00001885TypeSourceInfo *
1886ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1887 SourceLocation NameLoc,
1888 const TemplateArgumentListInfo &Args,
1889 QualType CanonType) {
1890 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1891
1892 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1893 TemplateSpecializationTypeLoc TL
1894 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1895 TL.setTemplateNameLoc(NameLoc);
1896 TL.setLAngleLoc(Args.getLAngleLoc());
1897 TL.setRAngleLoc(Args.getRAngleLoc());
1898 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1899 TL.setArgLocInfo(i, Args[i].getLocInfo());
1900 return DI;
1901}
1902
Mike Stump11289f42009-09-09 15:08:12 +00001903QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001904ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001905 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001906 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001907 unsigned NumArgs = Args.size();
1908
John McCall0ad16662009-10-29 08:12:44 +00001909 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1910 ArgVec.reserve(NumArgs);
1911 for (unsigned i = 0; i != NumArgs; ++i)
1912 ArgVec.push_back(Args[i].getArgument());
1913
John McCall2408e322010-04-27 00:57:59 +00001914 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001915 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001916}
1917
1918QualType
1919ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001920 const TemplateArgument *Args,
1921 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001922 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001923 if (!Canon.isNull())
1924 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001925 else
1926 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001927
Douglas Gregora8e02e72009-07-28 23:00:59 +00001928 // Allocate the (non-canonical) template specialization type, but don't
1929 // try to unique it: these types typically have location information that
1930 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001931 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001932 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001933 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001934 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001935 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001936 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001937 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001938
Douglas Gregor8bf42052009-02-09 18:46:07 +00001939 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001940 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001941}
1942
Mike Stump11289f42009-09-09 15:08:12 +00001943QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001944ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1945 const TemplateArgument *Args,
1946 unsigned NumArgs) {
1947 // Build the canonical template specialization type.
1948 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1949 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1950 CanonArgs.reserve(NumArgs);
1951 for (unsigned I = 0; I != NumArgs; ++I)
1952 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1953
1954 // Determine whether this canonical template specialization type already
1955 // exists.
1956 llvm::FoldingSetNodeID ID;
1957 TemplateSpecializationType::Profile(ID, CanonTemplate,
1958 CanonArgs.data(), NumArgs, *this);
1959
1960 void *InsertPos = 0;
1961 TemplateSpecializationType *Spec
1962 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1963
1964 if (!Spec) {
1965 // Allocate a new canonical template specialization type.
1966 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1967 sizeof(TemplateArgument) * NumArgs),
1968 TypeAlignment);
1969 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1970 CanonArgs.data(), NumArgs,
1971 QualType());
1972 Types.push_back(Spec);
1973 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1974 }
1975
1976 assert(Spec->isDependentType() &&
1977 "Non-dependent template-id type must have a canonical type");
1978 return QualType(Spec, 0);
1979}
1980
1981QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001982ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1983 NestedNameSpecifier *NNS,
1984 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001985 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001986 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001987
1988 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001989 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001990 if (T)
1991 return QualType(T, 0);
1992
Douglas Gregorc42075a2010-02-04 18:10:26 +00001993 QualType Canon = NamedType;
1994 if (!Canon.isCanonical()) {
1995 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001996 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001998 (void)CheckT;
1999 }
2000
Abramo Bagnara6150c882010-05-11 21:36:43 +00002001 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002002 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002003 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002004 return QualType(T, 0);
2005}
2006
Douglas Gregor02085352010-03-31 20:19:30 +00002007QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2008 NestedNameSpecifier *NNS,
2009 const IdentifierInfo *Name,
2010 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00002011 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2012
2013 if (Canon.isNull()) {
2014 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002015 ElaboratedTypeKeyword CanonKeyword = Keyword;
2016 if (Keyword == ETK_None)
2017 CanonKeyword = ETK_Typename;
2018
2019 if (CanonNNS != NNS || CanonKeyword != Keyword)
2020 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002021 }
2022
2023 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002024 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002025
2026 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002027 DependentNameType *T
2028 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002029 if (T)
2030 return QualType(T, 0);
2031
Douglas Gregor02085352010-03-31 20:19:30 +00002032 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002033 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002034 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002035 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002036}
2037
Mike Stump11289f42009-09-09 15:08:12 +00002038QualType
John McCallc392f372010-06-11 00:33:02 +00002039ASTContext::getDependentTemplateSpecializationType(
2040 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002041 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002042 const IdentifierInfo *Name,
2043 const TemplateArgumentListInfo &Args) {
2044 // TODO: avoid this copy
2045 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2046 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2047 ArgCopy.push_back(Args[I].getArgument());
2048 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2049 ArgCopy.size(),
2050 ArgCopy.data());
2051}
2052
2053QualType
2054ASTContext::getDependentTemplateSpecializationType(
2055 ElaboratedTypeKeyword Keyword,
2056 NestedNameSpecifier *NNS,
2057 const IdentifierInfo *Name,
2058 unsigned NumArgs,
2059 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002060 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2061
Douglas Gregorc42075a2010-02-04 18:10:26 +00002062 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002063 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2064 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002065
2066 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002067 DependentTemplateSpecializationType *T
2068 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002069 if (T)
2070 return QualType(T, 0);
2071
John McCallc392f372010-06-11 00:33:02 +00002072 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002073
John McCallc392f372010-06-11 00:33:02 +00002074 ElaboratedTypeKeyword CanonKeyword = Keyword;
2075 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2076
2077 bool AnyNonCanonArgs = false;
2078 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2079 for (unsigned I = 0; I != NumArgs; ++I) {
2080 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2081 if (!CanonArgs[I].structurallyEquals(Args[I]))
2082 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002083 }
2084
John McCallc392f372010-06-11 00:33:02 +00002085 QualType Canon;
2086 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2087 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2088 Name, NumArgs,
2089 CanonArgs.data());
2090
2091 // Find the insert position again.
2092 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2093 }
2094
2095 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2096 sizeof(TemplateArgument) * NumArgs),
2097 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002098 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002099 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002100 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002101 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002102 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002103}
2104
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002105/// CmpProtocolNames - Comparison predicate for sorting protocols
2106/// alphabetically.
2107static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2108 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002109 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002110}
2111
John McCall8b07ec22010-05-15 11:32:37 +00002112static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002113 unsigned NumProtocols) {
2114 if (NumProtocols == 0) return true;
2115
2116 for (unsigned i = 1; i != NumProtocols; ++i)
2117 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2118 return false;
2119 return true;
2120}
2121
2122static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002123 unsigned &NumProtocols) {
2124 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002126 // Sort protocols, keyed by name.
2127 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2128
2129 // Remove duplicates.
2130 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2131 NumProtocols = ProtocolsEnd-Protocols;
2132}
2133
John McCall8b07ec22010-05-15 11:32:37 +00002134QualType ASTContext::getObjCObjectType(QualType BaseType,
2135 ObjCProtocolDecl * const *Protocols,
2136 unsigned NumProtocols) {
2137 // If the base type is an interface and there aren't any protocols
2138 // to add, then the interface type will do just fine.
2139 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2140 return BaseType;
2141
2142 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002143 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002144 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002145 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002146 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2147 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002148
John McCall8b07ec22010-05-15 11:32:37 +00002149 // Build the canonical type, which has the canonical base type and
2150 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002151 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002152 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2153 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2154 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002155 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2156 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002157 unsigned UniqueCount = NumProtocols;
2158
John McCallfc93cf92009-10-22 22:37:11 +00002159 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002160 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2161 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002162 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002163 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2164 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002165 }
2166
2167 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002168 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2169 }
2170
2171 unsigned Size = sizeof(ObjCObjectTypeImpl);
2172 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2173 void *Mem = Allocate(Size, TypeAlignment);
2174 ObjCObjectTypeImpl *T =
2175 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2176
2177 Types.push_back(T);
2178 ObjCObjectTypes.InsertNode(T, InsertPos);
2179 return QualType(T, 0);
2180}
2181
2182/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2183/// the given object type.
2184QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2185 llvm::FoldingSetNodeID ID;
2186 ObjCObjectPointerType::Profile(ID, ObjectT);
2187
2188 void *InsertPos = 0;
2189 if (ObjCObjectPointerType *QT =
2190 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2191 return QualType(QT, 0);
2192
2193 // Find the canonical object type.
2194 QualType Canonical;
2195 if (!ObjectT.isCanonical()) {
2196 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2197
2198 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002199 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2200 }
2201
Douglas Gregorf85bee62010-02-08 22:59:26 +00002202 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002203 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2204 ObjCObjectPointerType *QType =
2205 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002206
Steve Narofffb4330f2009-06-17 22:40:22 +00002207 Types.push_back(QType);
2208 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002209 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002210}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002211
Steve Naroffc277ad12009-07-18 15:33:26 +00002212/// getObjCInterfaceType - Return the unique reference to the type for the
2213/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002214QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2215 if (Decl->TypeForDecl)
2216 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002217
John McCall8b07ec22010-05-15 11:32:37 +00002218 // FIXME: redeclarations?
2219 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2220 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2221 Decl->TypeForDecl = T;
2222 Types.push_back(T);
2223 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002224}
2225
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002226/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2227/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002228/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002229/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002230/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002231QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002232 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002233 if (tofExpr->isTypeDependent()) {
2234 llvm::FoldingSetNodeID ID;
2235 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002237 void *InsertPos = 0;
2238 DependentTypeOfExprType *Canon
2239 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2240 if (Canon) {
2241 // We already have a "canonical" version of an identical, dependent
2242 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002243 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002244 QualType((TypeOfExprType*)Canon, 0));
2245 }
2246 else {
2247 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002248 Canon
2249 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002250 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2251 toe = Canon;
2252 }
2253 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002254 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002255 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002256 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002257 Types.push_back(toe);
2258 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002259}
2260
Steve Naroffa773cd52007-08-01 18:02:17 +00002261/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2262/// TypeOfType AST's. The only motivation to unique these nodes would be
2263/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002264/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002265/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002266QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002267 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002268 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002269 Types.push_back(tot);
2270 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002271}
2272
Anders Carlssonad6bd352009-06-24 21:24:56 +00002273/// getDecltypeForExpr - Given an expr, will return the decltype for that
2274/// expression, according to the rules in C++0x [dcl.type.simple]p4
2275static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002276 if (e->isTypeDependent())
2277 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002278
Anders Carlssonad6bd352009-06-24 21:24:56 +00002279 // If e is an id expression or a class member access, decltype(e) is defined
2280 // as the type of the entity named by e.
2281 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2282 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2283 return VD->getType();
2284 }
2285 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2286 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2287 return FD->getType();
2288 }
2289 // If e is a function call or an invocation of an overloaded operator,
2290 // (parentheses around e are ignored), decltype(e) is defined as the
2291 // return type of that function.
2292 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2293 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002294
Anders Carlssonad6bd352009-06-24 21:24:56 +00002295 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002296
2297 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002298 // defined as T&, otherwise decltype(e) is defined as T.
2299 if (e->isLvalue(Context) == Expr::LV_Valid)
2300 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002301
Anders Carlssonad6bd352009-06-24 21:24:56 +00002302 return T;
2303}
2304
Anders Carlsson81df7b82009-06-24 19:06:50 +00002305/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2306/// DecltypeType AST's. The only motivation to unique these nodes would be
2307/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002308/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002309/// on canonical type's (which are always unique).
2310QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002311 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002312 if (e->isTypeDependent()) {
2313 llvm::FoldingSetNodeID ID;
2314 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Douglas Gregora21f6c32009-07-30 23:36:40 +00002316 void *InsertPos = 0;
2317 DependentDecltypeType *Canon
2318 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2319 if (Canon) {
2320 // We already have a "canonical" version of an equivalent, dependent
2321 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002322 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002323 QualType((DecltypeType*)Canon, 0));
2324 }
2325 else {
2326 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002327 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002328 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2329 dt = Canon;
2330 }
2331 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002332 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002333 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002334 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002335 Types.push_back(dt);
2336 return QualType(dt, 0);
2337}
2338
Chris Lattnerfb072462007-01-23 05:45:31 +00002339/// getTagDeclType - Return the unique reference to the type for the
2340/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002341QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002342 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002343 // FIXME: What is the design on getTagDeclType when it requires casting
2344 // away const? mutable?
2345 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002346}
2347
Mike Stump11289f42009-09-09 15:08:12 +00002348/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2349/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2350/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002351CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002352 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002353}
Chris Lattnerfb072462007-01-23 05:45:31 +00002354
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002355/// getSignedWCharType - Return the type of "signed wchar_t".
2356/// Used when in C++, as a GCC extension.
2357QualType ASTContext::getSignedWCharType() const {
2358 // FIXME: derive from "Target" ?
2359 return WCharTy;
2360}
2361
2362/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2363/// Used when in C++, as a GCC extension.
2364QualType ASTContext::getUnsignedWCharType() const {
2365 // FIXME: derive from "Target" ?
2366 return UnsignedIntTy;
2367}
2368
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002369/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2370/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2371QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002372 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002373}
2374
Chris Lattnera21ad802008-04-02 05:18:44 +00002375//===----------------------------------------------------------------------===//
2376// Type Operators
2377//===----------------------------------------------------------------------===//
2378
John McCallfc93cf92009-10-22 22:37:11 +00002379CanQualType ASTContext::getCanonicalParamType(QualType T) {
2380 // Push qualifiers into arrays, and then discard any remaining
2381 // qualifiers.
2382 T = getCanonicalType(T);
2383 const Type *Ty = T.getTypePtr();
2384
2385 QualType Result;
2386 if (isa<ArrayType>(Ty)) {
2387 Result = getArrayDecayedType(QualType(Ty,0));
2388 } else if (isa<FunctionType>(Ty)) {
2389 Result = getPointerType(QualType(Ty, 0));
2390 } else {
2391 Result = QualType(Ty, 0);
2392 }
2393
2394 return CanQualType::CreateUnsafe(Result);
2395}
2396
Chris Lattnered0d0792008-04-06 22:41:35 +00002397/// getCanonicalType - Return the canonical (structural) type corresponding to
2398/// the specified potentially non-canonical type. The non-canonical version
2399/// of a type may have many "decorated" versions of types. Decorators can
2400/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2401/// to be free of any of these, allowing two canonical types to be compared
2402/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002403CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002404 QualifierCollector Quals;
2405 const Type *Ptr = Quals.strip(T);
2406 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002407
John McCall8ccfcb52009-09-24 19:53:00 +00002408 // The canonical internal type will be the canonical type *except*
2409 // that we push type qualifiers down through array types.
2410
2411 // If there are no new qualifiers to push down, stop here.
2412 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002413 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002414
John McCall8ccfcb52009-09-24 19:53:00 +00002415 // If the type qualifiers are on an array type, get the canonical
2416 // type of the array with the qualifiers applied to the element
2417 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002418 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2419 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002420 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002421
Chris Lattner7adf0762008-08-04 07:31:14 +00002422 // Get the canonical version of the element with the extra qualifiers on it.
2423 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002424 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002425 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002426
Chris Lattner7adf0762008-08-04 07:31:14 +00002427 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002428 return CanQualType::CreateUnsafe(
2429 getConstantArrayType(NewEltTy, CAT->getSize(),
2430 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002431 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002432 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002433 return CanQualType::CreateUnsafe(
2434 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002435 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002436
Douglas Gregor4619e432008-12-05 23:32:09 +00002437 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002438 return CanQualType::CreateUnsafe(
2439 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002440 DSAT->getSizeExpr() ?
2441 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002442 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002443 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002444 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002445
Chris Lattner7adf0762008-08-04 07:31:14 +00002446 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002447 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002448 VAT->getSizeExpr() ?
2449 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002450 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002451 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002452 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002453}
2454
Chandler Carruth607f38e2009-12-29 07:16:59 +00002455QualType ASTContext::getUnqualifiedArrayType(QualType T,
2456 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002457 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002458 const ArrayType *AT = getAsArrayType(T);
2459 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002460 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002461 }
2462
Chandler Carruth607f38e2009-12-29 07:16:59 +00002463 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002464 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002465 if (Elt == UnqualElt)
2466 return T;
2467
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002468 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002469 return getConstantArrayType(UnqualElt, CAT->getSize(),
2470 CAT->getSizeModifier(), 0);
2471 }
2472
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002473 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002474 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2475 }
2476
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002477 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2478 return getVariableArrayType(UnqualElt,
2479 VAT->getSizeExpr() ?
2480 VAT->getSizeExpr()->Retain() : 0,
2481 VAT->getSizeModifier(),
2482 VAT->getIndexTypeCVRQualifiers(),
2483 VAT->getBracketsRange());
2484 }
2485
2486 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002487 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2488 DSAT->getSizeModifier(), 0,
2489 SourceRange());
2490}
2491
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002492/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2493/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2494/// they point to and return true. If T1 and T2 aren't pointer types
2495/// or pointer-to-member types, or if they are not similar at this
2496/// level, returns false and leaves T1 and T2 unchanged. Top-level
2497/// qualifiers on T1 and T2 are ignored. This function will typically
2498/// be called in a loop that successively "unwraps" pointer and
2499/// pointer-to-member types to compare them at each level.
2500bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2501 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2502 *T2PtrType = T2->getAs<PointerType>();
2503 if (T1PtrType && T2PtrType) {
2504 T1 = T1PtrType->getPointeeType();
2505 T2 = T2PtrType->getPointeeType();
2506 return true;
2507 }
2508
2509 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2510 *T2MPType = T2->getAs<MemberPointerType>();
2511 if (T1MPType && T2MPType &&
2512 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2513 QualType(T2MPType->getClass(), 0))) {
2514 T1 = T1MPType->getPointeeType();
2515 T2 = T2MPType->getPointeeType();
2516 return true;
2517 }
2518
2519 if (getLangOptions().ObjC1) {
2520 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2521 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2522 if (T1OPType && T2OPType) {
2523 T1 = T1OPType->getPointeeType();
2524 T2 = T2OPType->getPointeeType();
2525 return true;
2526 }
2527 }
2528
2529 // FIXME: Block pointers, too?
2530
2531 return false;
2532}
2533
John McCall847e2a12009-11-24 18:42:40 +00002534DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2535 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2536 return TD->getDeclName();
2537
2538 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2539 if (DTN->isIdentifier()) {
2540 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2541 } else {
2542 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2543 }
2544 }
2545
John McCalld28ae272009-12-02 08:04:21 +00002546 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2547 assert(Storage);
2548 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002549}
2550
Douglas Gregor6bc50582009-05-07 06:41:52 +00002551TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002552 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2553 if (TemplateTemplateParmDecl *TTP
2554 = dyn_cast<TemplateTemplateParmDecl>(Template))
2555 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2556
2557 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002558 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002559 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002560
John McCalld28ae272009-12-02 08:04:21 +00002561 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregor6bc50582009-05-07 06:41:52 +00002563 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2564 assert(DTN && "Non-dependent template names must refer to template decls.");
2565 return DTN->CanonicalTemplateName;
2566}
2567
Douglas Gregoradee3e32009-11-11 23:06:43 +00002568bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2569 X = getCanonicalTemplateName(X);
2570 Y = getCanonicalTemplateName(Y);
2571 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2572}
2573
Mike Stump11289f42009-09-09 15:08:12 +00002574TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002575ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2576 switch (Arg.getKind()) {
2577 case TemplateArgument::Null:
2578 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002579
Douglas Gregora8e02e72009-07-28 23:00:59 +00002580 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002581 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregora8e02e72009-07-28 23:00:59 +00002583 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002584 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002586 case TemplateArgument::Template:
2587 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2588
Douglas Gregora8e02e72009-07-28 23:00:59 +00002589 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002590 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002591 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002592
Douglas Gregora8e02e72009-07-28 23:00:59 +00002593 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002594 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002595
Douglas Gregora8e02e72009-07-28 23:00:59 +00002596 case TemplateArgument::Pack: {
2597 // FIXME: Allocate in ASTContext
2598 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2599 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002600 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002601 AEnd = Arg.pack_end();
2602 A != AEnd; (void)++A, ++Idx)
2603 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002604
Douglas Gregora8e02e72009-07-28 23:00:59 +00002605 TemplateArgument Result;
2606 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2607 return Result;
2608 }
2609 }
2610
2611 // Silence GCC warning
2612 assert(false && "Unhandled template argument kind");
2613 return TemplateArgument();
2614}
2615
Douglas Gregor333489b2009-03-27 23:10:48 +00002616NestedNameSpecifier *
2617ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002618 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002619 return 0;
2620
2621 switch (NNS->getKind()) {
2622 case NestedNameSpecifier::Identifier:
2623 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002624 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002625 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2626 NNS->getAsIdentifier());
2627
2628 case NestedNameSpecifier::Namespace:
2629 // A namespace is canonical; build a nested-name-specifier with
2630 // this namespace and no prefix.
2631 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2632
2633 case NestedNameSpecifier::TypeSpec:
2634 case NestedNameSpecifier::TypeSpecWithTemplate: {
2635 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002636 return NestedNameSpecifier::Create(*this, 0,
2637 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002638 T.getTypePtr());
2639 }
2640
2641 case NestedNameSpecifier::Global:
2642 // The global specifier is canonical and unique.
2643 return NNS;
2644 }
2645
2646 // Required to silence a GCC warning
2647 return 0;
2648}
2649
Chris Lattner7adf0762008-08-04 07:31:14 +00002650
2651const ArrayType *ASTContext::getAsArrayType(QualType T) {
2652 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002653 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002654 // Handle the common positive case fast.
2655 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2656 return AT;
2657 }
Mike Stump11289f42009-09-09 15:08:12 +00002658
John McCall8ccfcb52009-09-24 19:53:00 +00002659 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002660 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002661 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002662 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002663
John McCall8ccfcb52009-09-24 19:53:00 +00002664 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002665 // implements C99 6.7.3p8: "If the specification of an array type includes
2666 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002667
Chris Lattner7adf0762008-08-04 07:31:14 +00002668 // If we get here, we either have type qualifiers on the type, or we have
2669 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002670 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002671
John McCall8ccfcb52009-09-24 19:53:00 +00002672 QualifierCollector Qs;
2673 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002674
Chris Lattner7adf0762008-08-04 07:31:14 +00002675 // If we have a simple case, just return now.
2676 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002677 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002678 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002679
Chris Lattner7adf0762008-08-04 07:31:14 +00002680 // Otherwise, we have an array and we have qualifiers on it. Push the
2681 // qualifiers into the array element type and return a new array type.
2682 // Get the canonical version of the element with the extra qualifiers on it.
2683 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002684 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002685
Chris Lattner7adf0762008-08-04 07:31:14 +00002686 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2687 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2688 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002689 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002690 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2691 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2692 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002693 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002694
Mike Stump11289f42009-09-09 15:08:12 +00002695 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002696 = dyn_cast<DependentSizedArrayType>(ATy))
2697 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002698 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002699 DSAT->getSizeExpr() ?
2700 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002701 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002702 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002703 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002704
Chris Lattner7adf0762008-08-04 07:31:14 +00002705 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002706 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002707 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002708 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002709 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002710 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002711 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002712}
2713
2714
Chris Lattnera21ad802008-04-02 05:18:44 +00002715/// getArrayDecayedType - Return the properly qualified result of decaying the
2716/// specified array type to a pointer. This operation is non-trivial when
2717/// handling typedefs etc. The canonical type of "T" must be an array type,
2718/// this returns a pointer to a properly qualified element of the array.
2719///
2720/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2721QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002722 // Get the element type with 'getAsArrayType' so that we don't lose any
2723 // typedefs in the element type of the array. This also handles propagation
2724 // of type qualifiers from the array type into the element type if present
2725 // (C99 6.7.3p8).
2726 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2727 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002728
Chris Lattner7adf0762008-08-04 07:31:14 +00002729 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002730
2731 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002732 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002733}
2734
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002735QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002736 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002737 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2738 QT = AT->getElementType();
2739 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002740}
2741
Anders Carlsson4bf82142009-09-25 01:23:32 +00002742QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2743 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002744
Anders Carlsson4bf82142009-09-25 01:23:32 +00002745 if (const ArrayType *AT = getAsArrayType(ElemTy))
2746 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002747
Anders Carlssone0808df2008-12-21 03:44:36 +00002748 return ElemTy;
2749}
2750
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002751/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002752uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002753ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2754 uint64_t ElementCount = 1;
2755 do {
2756 ElementCount *= CA->getSize().getZExtValue();
2757 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2758 } while (CA);
2759 return ElementCount;
2760}
2761
Steve Naroff0af91202007-04-27 21:51:21 +00002762/// getFloatingRank - Return a relative rank for floating point types.
2763/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002764static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002765 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002766 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002767
John McCall9dd450b2009-09-21 23:43:11 +00002768 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2769 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002770 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002771 case BuiltinType::Float: return FloatRank;
2772 case BuiltinType::Double: return DoubleRank;
2773 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002774 }
2775}
2776
Mike Stump11289f42009-09-09 15:08:12 +00002777/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2778/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002779/// 'typeDomain' is a real floating point or complex type.
2780/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002781QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2782 QualType Domain) const {
2783 FloatingRank EltRank = getFloatingRank(Size);
2784 if (Domain->isComplexType()) {
2785 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002786 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002787 case FloatRank: return FloatComplexTy;
2788 case DoubleRank: return DoubleComplexTy;
2789 case LongDoubleRank: return LongDoubleComplexTy;
2790 }
Steve Naroff0af91202007-04-27 21:51:21 +00002791 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002792
2793 assert(Domain->isRealFloatingType() && "Unknown domain!");
2794 switch (EltRank) {
2795 default: assert(0 && "getFloatingRank(): illegal value for rank");
2796 case FloatRank: return FloatTy;
2797 case DoubleRank: return DoubleTy;
2798 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002799 }
Steve Naroffe4718892007-04-27 18:30:00 +00002800}
2801
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002802/// getFloatingTypeOrder - Compare the rank of the two specified floating
2803/// point types, ignoring the domain of the type (i.e. 'double' ==
2804/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002805/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002806int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2807 FloatingRank LHSR = getFloatingRank(LHS);
2808 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002809
Chris Lattnerb90739d2008-04-06 23:38:49 +00002810 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002811 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002812 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002813 return 1;
2814 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002815}
2816
Chris Lattner76a00cf2008-04-06 22:59:24 +00002817/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2818/// routine will assert if passed a built-in type that isn't an integer or enum,
2819/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002820unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002821 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002822 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002823 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002824
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002825 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2826 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2827
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002828 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2829 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2830
2831 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2832 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2833
Chris Lattner76a00cf2008-04-06 22:59:24 +00002834 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002835 default: assert(0 && "getIntegerRank(): not a built-in integer");
2836 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002837 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002838 case BuiltinType::Char_S:
2839 case BuiltinType::Char_U:
2840 case BuiltinType::SChar:
2841 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002842 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002843 case BuiltinType::Short:
2844 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002845 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002846 case BuiltinType::Int:
2847 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002848 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002849 case BuiltinType::Long:
2850 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002851 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002852 case BuiltinType::LongLong:
2853 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002854 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002855 case BuiltinType::Int128:
2856 case BuiltinType::UInt128:
2857 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002858 }
2859}
2860
Eli Friedman629ffb92009-08-20 04:21:42 +00002861/// \brief Whether this is a promotable bitfield reference according
2862/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2863///
2864/// \returns the type this bit-field will promote to, or NULL if no
2865/// promotion occurs.
2866QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002867 if (E->isTypeDependent() || E->isValueDependent())
2868 return QualType();
2869
Eli Friedman629ffb92009-08-20 04:21:42 +00002870 FieldDecl *Field = E->getBitField();
2871 if (!Field)
2872 return QualType();
2873
2874 QualType FT = Field->getType();
2875
2876 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2877 uint64_t BitWidth = BitWidthAP.getZExtValue();
2878 uint64_t IntSize = getTypeSize(IntTy);
2879 // GCC extension compatibility: if the bit-field size is less than or equal
2880 // to the size of int, it gets promoted no matter what its type is.
2881 // For instance, unsigned long bf : 4 gets promoted to signed int.
2882 if (BitWidth < IntSize)
2883 return IntTy;
2884
2885 if (BitWidth == IntSize)
2886 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2887
2888 // Types bigger than int are not subject to promotions, and therefore act
2889 // like the base type.
2890 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2891 // is ridiculous.
2892 return QualType();
2893}
2894
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002895/// getPromotedIntegerType - Returns the type that Promotable will
2896/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2897/// integer type.
2898QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2899 assert(!Promotable.isNull());
2900 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002901 if (const EnumType *ET = Promotable->getAs<EnumType>())
2902 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002903 if (Promotable->isSignedIntegerType())
2904 return IntTy;
2905 uint64_t PromotableSize = getTypeSize(Promotable);
2906 uint64_t IntSize = getTypeSize(IntTy);
2907 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2908 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2909}
2910
Mike Stump11289f42009-09-09 15:08:12 +00002911/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002912/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002913/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002914int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002915 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2916 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002917 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002918
Chris Lattner76a00cf2008-04-06 22:59:24 +00002919 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2920 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002921
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002922 unsigned LHSRank = getIntegerRank(LHSC);
2923 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002924
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002925 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2926 if (LHSRank == RHSRank) return 0;
2927 return LHSRank > RHSRank ? 1 : -1;
2928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002930 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2931 if (LHSUnsigned) {
2932 // If the unsigned [LHS] type is larger, return it.
2933 if (LHSRank >= RHSRank)
2934 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002935
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002936 // If the signed type can represent all values of the unsigned type, it
2937 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002938 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002939 return -1;
2940 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002941
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002942 // If the unsigned [RHS] type is larger, return it.
2943 if (RHSRank >= LHSRank)
2944 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002945
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002946 // If the signed type can represent all values of the unsigned type, it
2947 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002948 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002949 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002950}
Anders Carlsson98f07902007-08-17 05:31:46 +00002951
Anders Carlsson6d417272009-11-14 21:45:58 +00002952static RecordDecl *
2953CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2954 SourceLocation L, IdentifierInfo *Id) {
2955 if (Ctx.getLangOptions().CPlusPlus)
2956 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2957 else
2958 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2959}
2960
Mike Stump11289f42009-09-09 15:08:12 +00002961// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002962QualType ASTContext::getCFConstantStringType() {
2963 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002964 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002965 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002966 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002967 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002968
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002969 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002970
Anders Carlsson98f07902007-08-17 05:31:46 +00002971 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002972 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002973 // int flags;
2974 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002975 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002976 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002977 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002978 FieldTypes[3] = LongTy;
2979
Anders Carlsson98f07902007-08-17 05:31:46 +00002980 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002981 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002982 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002983 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002984 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002985 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002986 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002987 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002988 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002989 }
2990
Douglas Gregord5058122010-02-11 01:19:42 +00002991 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002992 }
Mike Stump11289f42009-09-09 15:08:12 +00002993
Anders Carlsson98f07902007-08-17 05:31:46 +00002994 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002995}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002996
Douglas Gregor512b0772009-04-23 22:29:11 +00002997void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002998 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002999 assert(Rec && "Invalid CFConstantStringType");
3000 CFConstantStringTypeDecl = Rec->getDecl();
3001}
3002
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003003// getNSConstantStringType - Return the type used for constant NSStrings.
3004QualType ASTContext::getNSConstantStringType() {
3005 if (!NSConstantStringTypeDecl) {
3006 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003007 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003008 &Idents.get("__builtin_NSString"));
3009 NSConstantStringTypeDecl->startDefinition();
3010
3011 QualType FieldTypes[3];
3012
3013 // const int *isa;
3014 FieldTypes[0] = getPointerType(IntTy.withConst());
3015 // const char *str;
3016 FieldTypes[1] = getPointerType(CharTy.withConst());
3017 // unsigned int length;
3018 FieldTypes[2] = UnsignedIntTy;
3019
3020 // Create fields
3021 for (unsigned i = 0; i < 3; ++i) {
3022 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3023 SourceLocation(), 0,
3024 FieldTypes[i], /*TInfo=*/0,
3025 /*BitWidth=*/0,
3026 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003027 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003028 NSConstantStringTypeDecl->addDecl(Field);
3029 }
3030
3031 NSConstantStringTypeDecl->completeDefinition();
3032 }
3033
3034 return getTagDeclType(NSConstantStringTypeDecl);
3035}
3036
3037void ASTContext::setNSConstantStringType(QualType T) {
3038 const RecordType *Rec = T->getAs<RecordType>();
3039 assert(Rec && "Invalid NSConstantStringType");
3040 NSConstantStringTypeDecl = Rec->getDecl();
3041}
3042
Mike Stump11289f42009-09-09 15:08:12 +00003043QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003044 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003045 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003046 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003047 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003048 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003049
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003050 QualType FieldTypes[] = {
3051 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003052 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003053 getPointerType(UnsignedLongTy),
3054 getConstantArrayType(UnsignedLongTy,
3055 llvm::APInt(32, 5), ArrayType::Normal, 0)
3056 };
Mike Stump11289f42009-09-09 15:08:12 +00003057
Douglas Gregor91f84212008-12-11 16:49:14 +00003058 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003059 FieldDecl *Field = FieldDecl::Create(*this,
3060 ObjCFastEnumerationStateTypeDecl,
3061 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003062 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003063 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003064 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003065 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003066 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003067 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003068 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003069 if (CXXRecordDecl *CXXRD =
3070 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003071 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003072
Douglas Gregord5058122010-02-11 01:19:42 +00003073 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003074 }
Mike Stump11289f42009-09-09 15:08:12 +00003075
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003076 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3077}
3078
Mike Stumpd0153282009-10-20 02:12:22 +00003079QualType ASTContext::getBlockDescriptorType() {
3080 if (BlockDescriptorType)
3081 return getTagDeclType(BlockDescriptorType);
3082
3083 RecordDecl *T;
3084 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003085 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003086 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003087 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003088
3089 QualType FieldTypes[] = {
3090 UnsignedLongTy,
3091 UnsignedLongTy,
3092 };
3093
3094 const char *FieldNames[] = {
3095 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003096 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003097 };
3098
3099 for (size_t i = 0; i < 2; ++i) {
3100 FieldDecl *Field = FieldDecl::Create(*this,
3101 T,
3102 SourceLocation(),
3103 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003104 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003105 /*BitWidth=*/0,
3106 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003107 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003108 T->addDecl(Field);
3109 }
3110
Douglas Gregord5058122010-02-11 01:19:42 +00003111 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003112
3113 BlockDescriptorType = T;
3114
3115 return getTagDeclType(BlockDescriptorType);
3116}
3117
3118void ASTContext::setBlockDescriptorType(QualType T) {
3119 const RecordType *Rec = T->getAs<RecordType>();
3120 assert(Rec && "Invalid BlockDescriptorType");
3121 BlockDescriptorType = Rec->getDecl();
3122}
3123
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003124QualType ASTContext::getBlockDescriptorExtendedType() {
3125 if (BlockDescriptorExtendedType)
3126 return getTagDeclType(BlockDescriptorExtendedType);
3127
3128 RecordDecl *T;
3129 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003130 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003131 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003132 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003133
3134 QualType FieldTypes[] = {
3135 UnsignedLongTy,
3136 UnsignedLongTy,
3137 getPointerType(VoidPtrTy),
3138 getPointerType(VoidPtrTy)
3139 };
3140
3141 const char *FieldNames[] = {
3142 "reserved",
3143 "Size",
3144 "CopyFuncPtr",
3145 "DestroyFuncPtr"
3146 };
3147
3148 for (size_t i = 0; i < 4; ++i) {
3149 FieldDecl *Field = FieldDecl::Create(*this,
3150 T,
3151 SourceLocation(),
3152 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003153 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003154 /*BitWidth=*/0,
3155 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003156 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003157 T->addDecl(Field);
3158 }
3159
Douglas Gregord5058122010-02-11 01:19:42 +00003160 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003161
3162 BlockDescriptorExtendedType = T;
3163
3164 return getTagDeclType(BlockDescriptorExtendedType);
3165}
3166
3167void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3168 const RecordType *Rec = T->getAs<RecordType>();
3169 assert(Rec && "Invalid BlockDescriptorType");
3170 BlockDescriptorExtendedType = Rec->getDecl();
3171}
3172
Mike Stump94967902009-10-21 18:16:27 +00003173bool ASTContext::BlockRequiresCopying(QualType Ty) {
3174 if (Ty->isBlockPointerType())
3175 return true;
3176 if (isObjCNSObjectType(Ty))
3177 return true;
3178 if (Ty->isObjCObjectPointerType())
3179 return true;
3180 return false;
3181}
3182
3183QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3184 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003185 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003186 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003187 // unsigned int __flags;
3188 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003189 // void *__copy_helper; // as needed
3190 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003191 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003192 // } *
3193
Mike Stump94967902009-10-21 18:16:27 +00003194 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3195
3196 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003197 llvm::SmallString<36> Name;
3198 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3199 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003200 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003201 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003202 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003203 T->startDefinition();
3204 QualType Int32Ty = IntTy;
3205 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3206 QualType FieldTypes[] = {
3207 getPointerType(VoidPtrTy),
3208 getPointerType(getTagDeclType(T)),
3209 Int32Ty,
3210 Int32Ty,
3211 getPointerType(VoidPtrTy),
3212 getPointerType(VoidPtrTy),
3213 Ty
3214 };
3215
3216 const char *FieldNames[] = {
3217 "__isa",
3218 "__forwarding",
3219 "__flags",
3220 "__size",
3221 "__copy_helper",
3222 "__destroy_helper",
3223 DeclName,
3224 };
3225
3226 for (size_t i = 0; i < 7; ++i) {
3227 if (!HasCopyAndDispose && i >=4 && i <= 5)
3228 continue;
3229 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3230 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003231 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003232 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003233 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003234 T->addDecl(Field);
3235 }
3236
Douglas Gregord5058122010-02-11 01:19:42 +00003237 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003238
3239 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003240}
3241
3242
3243QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003244 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003245 llvm::SmallVectorImpl<const Expr *> &Layout) {
3246
Mike Stumpd0153282009-10-20 02:12:22 +00003247 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003248 llvm::SmallString<36> Name;
3249 llvm::raw_svector_ostream(Name) << "__block_literal_"
3250 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003251 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003252 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003253 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003254 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003255 QualType FieldTypes[] = {
3256 getPointerType(VoidPtrTy),
3257 IntTy,
3258 IntTy,
3259 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003260 (BlockHasCopyDispose ?
3261 getPointerType(getBlockDescriptorExtendedType()) :
3262 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003263 };
3264
3265 const char *FieldNames[] = {
3266 "__isa",
3267 "__flags",
3268 "__reserved",
3269 "__FuncPtr",
3270 "__descriptor"
3271 };
3272
3273 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003274 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003275 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003276 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003277 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003278 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003279 T->addDecl(Field);
3280 }
3281
John McCall87fe5d52010-05-20 01:18:31 +00003282 for (unsigned i = 0; i < Layout.size(); ++i) {
3283 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003284
John McCall87fe5d52010-05-20 01:18:31 +00003285 QualType FieldType = E->getType();
3286 IdentifierInfo *FieldName = 0;
3287 if (isa<CXXThisExpr>(E)) {
3288 FieldName = &Idents.get("this");
3289 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3290 const ValueDecl *D = BDRE->getDecl();
3291 FieldName = D->getIdentifier();
3292 if (BDRE->isByRef())
3293 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3294 } else {
3295 // Padding.
3296 assert(isa<ConstantArrayType>(FieldType) &&
3297 isa<DeclRefExpr>(E) &&
3298 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3299 "doesn't match characteristics of padding decl");
3300 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003301
3302 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003303 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003304 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003305 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003306 T->addDecl(Field);
3307 }
3308
Douglas Gregord5058122010-02-11 01:19:42 +00003309 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003310
3311 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003312}
3313
Douglas Gregor512b0772009-04-23 22:29:11 +00003314void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003315 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003316 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3317 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3318}
3319
Anders Carlsson18acd442007-10-29 06:33:42 +00003320// This returns true if a type has been typedefed to BOOL:
3321// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003322static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003323 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003324 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3325 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003326
Anders Carlssond8499822007-10-29 05:01:08 +00003327 return false;
3328}
3329
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003330/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003331/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003332CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003333 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003334
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003335 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003336 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003337 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003338 // Treat arrays as pointers, since that's how they're passed in.
3339 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003340 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003341 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003342}
3343
3344static inline
3345std::string charUnitsToString(const CharUnits &CU) {
3346 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003347}
3348
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003349/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003350/// declaration.
3351void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3352 std::string& S) {
3353 const BlockDecl *Decl = Expr->getBlockDecl();
3354 QualType BlockTy =
3355 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3356 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003357 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003358 // Compute size of all parameters.
3359 // Start with computing size of a pointer in number of bytes.
3360 // FIXME: There might(should) be a better way of doing this computation!
3361 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003362 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3363 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003364 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003365 E = Decl->param_end(); PI != E; ++PI) {
3366 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003367 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003368 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003369 ParmOffset += sz;
3370 }
3371 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003372 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003373 // Block pointer and offset.
3374 S += "@?0";
3375 ParmOffset = PtrSize;
3376
3377 // Argument types.
3378 ParmOffset = PtrSize;
3379 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3380 Decl->param_end(); PI != E; ++PI) {
3381 ParmVarDecl *PVDecl = *PI;
3382 QualType PType = PVDecl->getOriginalType();
3383 if (const ArrayType *AT =
3384 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3385 // Use array's original type only if it has known number of
3386 // elements.
3387 if (!isa<ConstantArrayType>(AT))
3388 PType = PVDecl->getType();
3389 } else if (PType->isFunctionType())
3390 PType = PVDecl->getType();
3391 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003392 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003393 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003394 }
3395}
3396
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003397/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003398/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003399void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003400 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003401 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003402 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003403 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003404 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003405 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003406 // Compute size of all parameters.
3407 // Start with computing size of a pointer in number of bytes.
3408 // FIXME: There might(should) be a better way of doing this computation!
3409 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003410 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003411 // The first two arguments (self and _cmd) are pointers; account for
3412 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003413 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003414 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003415 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003416 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003417 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003418 assert (sz.isPositive() &&
3419 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003420 ParmOffset += sz;
3421 }
Ken Dyck40775002010-01-11 17:06:35 +00003422 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003423 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003424 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003425
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003426 // Argument types.
3427 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003428 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003429 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003430 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003431 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003432 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003433 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3434 // Use array's original type only if it has known number of
3435 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003436 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003437 PType = PVDecl->getType();
3438 } else if (PType->isFunctionType())
3439 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003440 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003441 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003442 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003443 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003444 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003445 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003446 }
3447}
3448
Daniel Dunbar4932b362008-08-28 04:38:10 +00003449/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003450/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003451/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3452/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003453/// Property attributes are stored as a comma-delimited C string. The simple
3454/// attributes readonly and bycopy are encoded as single characters. The
3455/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3456/// encoded as single characters, followed by an identifier. Property types
3457/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003458/// these attributes are defined by the following enumeration:
3459/// @code
3460/// enum PropertyAttributes {
3461/// kPropertyReadOnly = 'R', // property is read-only.
3462/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3463/// kPropertyByref = '&', // property is a reference to the value last assigned
3464/// kPropertyDynamic = 'D', // property is dynamic
3465/// kPropertyGetter = 'G', // followed by getter selector name
3466/// kPropertySetter = 'S', // followed by setter selector name
3467/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3468/// kPropertyType = 't' // followed by old-style type encoding.
3469/// kPropertyWeak = 'W' // 'weak' property
3470/// kPropertyStrong = 'P' // property GC'able
3471/// kPropertyNonAtomic = 'N' // property non-atomic
3472/// };
3473/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003474void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003475 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003476 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003477 // Collect information from the property implementation decl(s).
3478 bool Dynamic = false;
3479 ObjCPropertyImplDecl *SynthesizePID = 0;
3480
3481 // FIXME: Duplicated code due to poor abstraction.
3482 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003483 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003484 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3485 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003486 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003487 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003488 ObjCPropertyImplDecl *PID = *i;
3489 if (PID->getPropertyDecl() == PD) {
3490 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3491 Dynamic = true;
3492 } else {
3493 SynthesizePID = PID;
3494 }
3495 }
3496 }
3497 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003498 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003499 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003500 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003501 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003502 ObjCPropertyImplDecl *PID = *i;
3503 if (PID->getPropertyDecl() == PD) {
3504 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3505 Dynamic = true;
3506 } else {
3507 SynthesizePID = PID;
3508 }
3509 }
Mike Stump11289f42009-09-09 15:08:12 +00003510 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003511 }
3512 }
3513
3514 // FIXME: This is not very efficient.
3515 S = "T";
3516
3517 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003518 // GCC has some special rules regarding encoding of properties which
3519 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003520 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003521 true /* outermost type */,
3522 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003523
3524 if (PD->isReadOnly()) {
3525 S += ",R";
3526 } else {
3527 switch (PD->getSetterKind()) {
3528 case ObjCPropertyDecl::Assign: break;
3529 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003530 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003531 }
3532 }
3533
3534 // It really isn't clear at all what this means, since properties
3535 // are "dynamic by default".
3536 if (Dynamic)
3537 S += ",D";
3538
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003539 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3540 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003541
Daniel Dunbar4932b362008-08-28 04:38:10 +00003542 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3543 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003544 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003545 }
3546
3547 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3548 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003549 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003550 }
3551
3552 if (SynthesizePID) {
3553 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3554 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003555 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003556 }
3557
3558 // FIXME: OBJCGC: weak & strong
3559}
3560
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003561/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003562/// Another legacy compatibility encoding: 32-bit longs are encoded as
3563/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003564/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3565///
3566void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003567 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003568 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003569 if (BT->getKind() == BuiltinType::ULong &&
3570 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003571 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003572 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003573 if (BT->getKind() == BuiltinType::Long &&
3574 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003575 PointeeTy = IntTy;
3576 }
3577 }
3578}
3579
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003580void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003581 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003582 // We follow the behavior of gcc, expanding structures which are
3583 // directly pointed to, and expanding embedded structures. Note that
3584 // these rules are sufficient to prevent recursive encoding of the
3585 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003586 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003587 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003588}
3589
David Chisnallb190a2c2010-06-04 01:10:52 +00003590static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3591 switch (T->getAs<BuiltinType>()->getKind()) {
3592 default: assert(0 && "Unhandled builtin type kind");
3593 case BuiltinType::Void: return 'v';
3594 case BuiltinType::Bool: return 'B';
3595 case BuiltinType::Char_U:
3596 case BuiltinType::UChar: return 'C';
3597 case BuiltinType::UShort: return 'S';
3598 case BuiltinType::UInt: return 'I';
3599 case BuiltinType::ULong:
3600 return
3601 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3602 case BuiltinType::UInt128: return 'T';
3603 case BuiltinType::ULongLong: return 'Q';
3604 case BuiltinType::Char_S:
3605 case BuiltinType::SChar: return 'c';
3606 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003607 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003608 case BuiltinType::Int: return 'i';
3609 case BuiltinType::Long:
3610 return
3611 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3612 case BuiltinType::LongLong: return 'q';
3613 case BuiltinType::Int128: return 't';
3614 case BuiltinType::Float: return 'f';
3615 case BuiltinType::Double: return 'd';
3616 case BuiltinType::LongDouble: return 'd';
3617 }
3618}
3619
Mike Stump11289f42009-09-09 15:08:12 +00003620static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003621 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003622 const Expr *E = FD->getBitWidth();
3623 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3624 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003625 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003626 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3627 // The GNU runtime requires more information; bitfields are encoded as b,
3628 // then the offset (in bits) of the first element, then the type of the
3629 // bitfield, then the size in bits. For example, in this structure:
3630 //
3631 // struct
3632 // {
3633 // int integer;
3634 // int flags:2;
3635 // };
3636 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3637 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3638 // information is not especially sensible, but we're stuck with it for
3639 // compatibility with GCC, although providing it breaks anything that
3640 // actually uses runtime introspection and wants to work on both runtimes...
3641 if (!Ctx->getLangOptions().NeXTRuntime) {
3642 const RecordDecl *RD = FD->getParent();
3643 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3644 // FIXME: This same linear search is also used in ExprConstant - it might
3645 // be better if the FieldDecl stored its offset. We'd be increasing the
3646 // size of the object slightly, but saving some time every time it is used.
3647 unsigned i = 0;
3648 for (RecordDecl::field_iterator Field = RD->field_begin(),
3649 FieldEnd = RD->field_end();
3650 Field != FieldEnd; (void)++Field, ++i) {
3651 if (*Field == FD)
3652 break;
3653 }
3654 S += llvm::utostr(RL.getFieldOffset(i));
3655 S += ObjCEncodingForPrimitiveKind(Context, T);
3656 }
3657 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003658 S += llvm::utostr(N);
3659}
3660
Daniel Dunbar07d07852009-10-18 21:17:35 +00003661// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003662void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3663 bool ExpandPointedToStructures,
3664 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003665 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003666 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003667 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003668 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003669 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003670 return EncodeBitField(this, S, T, FD);
3671 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003672 return;
3673 }
Mike Stump11289f42009-09-09 15:08:12 +00003674
John McCall9dd450b2009-09-21 23:43:11 +00003675 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003676 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003677 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003678 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003679 return;
3680 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003681
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003682 // encoding for pointer or r3eference types.
3683 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003684 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003685 if (PT->isObjCSelType()) {
3686 S += ':';
3687 return;
3688 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003689 PointeeTy = PT->getPointeeType();
3690 }
3691 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3692 PointeeTy = RT->getPointeeType();
3693 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003694 bool isReadOnly = false;
3695 // For historical/compatibility reasons, the read-only qualifier of the
3696 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3697 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003698 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003699 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003700 if (OutermostType && T.isConstQualified()) {
3701 isReadOnly = true;
3702 S += 'r';
3703 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003704 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003705 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003706 while (P->getAs<PointerType>())
3707 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003708 if (P.isConstQualified()) {
3709 isReadOnly = true;
3710 S += 'r';
3711 }
3712 }
3713 if (isReadOnly) {
3714 // Another legacy compatibility encoding. Some ObjC qualifier and type
3715 // combinations need to be rearranged.
3716 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003717 if (llvm::StringRef(S).endswith("nr"))
3718 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003719 }
Mike Stump11289f42009-09-09 15:08:12 +00003720
Anders Carlssond8499822007-10-29 05:01:08 +00003721 if (PointeeTy->isCharType()) {
3722 // char pointer types should be encoded as '*' unless it is a
3723 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003724 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003725 S += '*';
3726 return;
3727 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003728 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003729 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3730 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3731 S += '#';
3732 return;
3733 }
3734 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3735 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3736 S += '@';
3737 return;
3738 }
3739 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003740 }
Anders Carlssond8499822007-10-29 05:01:08 +00003741 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003742 getLegacyIntegralTypeEncoding(PointeeTy);
3743
Mike Stump11289f42009-09-09 15:08:12 +00003744 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003745 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003746 return;
3747 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003748
Chris Lattnere7cabb92009-07-13 00:10:46 +00003749 if (const ArrayType *AT =
3750 // Ignore type qualifiers etc.
3751 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003752 if (isa<IncompleteArrayType>(AT)) {
3753 // Incomplete arrays are encoded as a pointer to the array element.
3754 S += '^';
3755
Mike Stump11289f42009-09-09 15:08:12 +00003756 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003757 false, ExpandStructures, FD);
3758 } else {
3759 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003760
Anders Carlssond05f44b2009-02-22 01:38:57 +00003761 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3762 S += llvm::utostr(CAT->getSize().getZExtValue());
3763 else {
3764 //Variable length arrays are encoded as a regular array with 0 elements.
3765 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3766 S += '0';
3767 }
Mike Stump11289f42009-09-09 15:08:12 +00003768
3769 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003770 false, ExpandStructures, FD);
3771 S += ']';
3772 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003773 return;
3774 }
Mike Stump11289f42009-09-09 15:08:12 +00003775
John McCall9dd450b2009-09-21 23:43:11 +00003776 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003777 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003778 return;
3779 }
Mike Stump11289f42009-09-09 15:08:12 +00003780
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003781 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003782 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003783 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003784 // Anonymous structures print as '?'
3785 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3786 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003787 if (ClassTemplateSpecializationDecl *Spec
3788 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3789 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3790 std::string TemplateArgsStr
3791 = TemplateSpecializationType::PrintTemplateArgumentList(
3792 TemplateArgs.getFlatArgumentList(),
3793 TemplateArgs.flat_size(),
3794 (*this).PrintingPolicy);
3795
3796 S += TemplateArgsStr;
3797 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003798 } else {
3799 S += '?';
3800 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003801 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003802 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003803 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3804 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003805 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003806 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003807 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003808 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003809 S += '"';
3810 }
Mike Stump11289f42009-09-09 15:08:12 +00003811
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003812 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003813 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003814 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003815 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003816 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003817 QualType qt = Field->getType();
3818 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003819 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003820 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003821 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003822 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003823 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003824 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003825 return;
3826 }
Mike Stump11289f42009-09-09 15:08:12 +00003827
Chris Lattnere7cabb92009-07-13 00:10:46 +00003828 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003829 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003830 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003831 else
3832 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003833 return;
3834 }
Mike Stump11289f42009-09-09 15:08:12 +00003835
Chris Lattnere7cabb92009-07-13 00:10:46 +00003836 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003837 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003838 return;
3839 }
Mike Stump11289f42009-09-09 15:08:12 +00003840
John McCall8b07ec22010-05-15 11:32:37 +00003841 // Ignore protocol qualifiers when mangling at this level.
3842 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3843 T = OT->getBaseType();
3844
John McCall8ccfcb52009-09-24 19:53:00 +00003845 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003846 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003847 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003848 S += '{';
3849 const IdentifierInfo *II = OI->getIdentifier();
3850 S += II->getName();
3851 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003852 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003853 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003854 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003855 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003856 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003857 RecFields[i]);
3858 else
Mike Stump11289f42009-09-09 15:08:12 +00003859 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003860 FD);
3861 }
3862 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003863 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003864 }
Mike Stump11289f42009-09-09 15:08:12 +00003865
John McCall9dd450b2009-09-21 23:43:11 +00003866 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003867 if (OPT->isObjCIdType()) {
3868 S += '@';
3869 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003870 }
Mike Stump11289f42009-09-09 15:08:12 +00003871
Steve Narofff0c86112009-10-28 22:03:49 +00003872 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3873 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3874 // Since this is a binary compatibility issue, need to consult with runtime
3875 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003876 S += '#';
3877 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003878 }
Mike Stump11289f42009-09-09 15:08:12 +00003879
Chris Lattnere7cabb92009-07-13 00:10:46 +00003880 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003881 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003882 ExpandPointedToStructures,
3883 ExpandStructures, FD);
3884 if (FD || EncodingProperty) {
3885 // Note that we do extended encoding of protocol qualifer list
3886 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003887 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003888 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3889 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003890 S += '<';
3891 S += (*I)->getNameAsString();
3892 S += '>';
3893 }
3894 S += '"';
3895 }
3896 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003897 }
Mike Stump11289f42009-09-09 15:08:12 +00003898
Chris Lattnere7cabb92009-07-13 00:10:46 +00003899 QualType PointeeTy = OPT->getPointeeType();
3900 if (!EncodingProperty &&
3901 isa<TypedefType>(PointeeTy.getTypePtr())) {
3902 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003903 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003904 // {...};
3905 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003906 getObjCEncodingForTypeImpl(PointeeTy, S,
3907 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003908 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003909 return;
3910 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003911
3912 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003913 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003914 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003915 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003916 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3917 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003918 S += '<';
3919 S += (*I)->getNameAsString();
3920 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003921 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003922 S += '"';
3923 }
3924 return;
3925 }
Mike Stump11289f42009-09-09 15:08:12 +00003926
John McCalla9e6e8d2010-05-17 23:56:34 +00003927 // gcc just blithely ignores member pointers.
3928 // TODO: maybe there should be a mangling for these
3929 if (T->getAs<MemberPointerType>())
3930 return;
3931
Chris Lattnere7cabb92009-07-13 00:10:46 +00003932 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003933}
3934
Mike Stump11289f42009-09-09 15:08:12 +00003935void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003936 std::string& S) const {
3937 if (QT & Decl::OBJC_TQ_In)
3938 S += 'n';
3939 if (QT & Decl::OBJC_TQ_Inout)
3940 S += 'N';
3941 if (QT & Decl::OBJC_TQ_Out)
3942 S += 'o';
3943 if (QT & Decl::OBJC_TQ_Bycopy)
3944 S += 'O';
3945 if (QT & Decl::OBJC_TQ_Byref)
3946 S += 'R';
3947 if (QT & Decl::OBJC_TQ_Oneway)
3948 S += 'V';
3949}
3950
Chris Lattnere7cabb92009-07-13 00:10:46 +00003951void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003952 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003953
Anders Carlsson87c149b2007-10-11 01:00:40 +00003954 BuiltinVaListType = T;
3955}
3956
Chris Lattnere7cabb92009-07-13 00:10:46 +00003957void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003958 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003959}
3960
Chris Lattnere7cabb92009-07-13 00:10:46 +00003961void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003962 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003963}
3964
Chris Lattnere7cabb92009-07-13 00:10:46 +00003965void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003966 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003967}
3968
Chris Lattnere7cabb92009-07-13 00:10:46 +00003969void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003970 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003971}
3972
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003973void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003974 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003975 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003976
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003977 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003978}
3979
John McCalld28ae272009-12-02 08:04:21 +00003980/// \brief Retrieve the template name that corresponds to a non-empty
3981/// lookup.
John McCallad371252010-01-20 00:46:10 +00003982TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3983 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003984 unsigned size = End - Begin;
3985 assert(size > 1 && "set is not overloaded!");
3986
3987 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3988 size * sizeof(FunctionTemplateDecl*));
3989 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3990
3991 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003992 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003993 NamedDecl *D = *I;
3994 assert(isa<FunctionTemplateDecl>(D) ||
3995 (isa<UsingShadowDecl>(D) &&
3996 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3997 *Storage++ = D;
3998 }
3999
4000 return TemplateName(OT);
4001}
4002
Douglas Gregordc572a32009-03-30 22:58:21 +00004003/// \brief Retrieve the template name that represents a qualified
4004/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00004005TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004006 bool TemplateKeyword,
4007 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004008 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004009 llvm::FoldingSetNodeID ID;
4010 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4011
4012 void *InsertPos = 0;
4013 QualifiedTemplateName *QTN =
4014 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4015 if (!QTN) {
4016 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4017 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4018 }
4019
4020 return TemplateName(QTN);
4021}
4022
4023/// \brief Retrieve the template name that represents a dependent
4024/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004025TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004026 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004027 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004028 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004029
4030 llvm::FoldingSetNodeID ID;
4031 DependentTemplateName::Profile(ID, NNS, Name);
4032
4033 void *InsertPos = 0;
4034 DependentTemplateName *QTN =
4035 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4036
4037 if (QTN)
4038 return TemplateName(QTN);
4039
4040 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4041 if (CanonNNS == NNS) {
4042 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4043 } else {
4044 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4045 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004046 DependentTemplateName *CheckQTN =
4047 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4048 assert(!CheckQTN && "Dependent type name canonicalization broken");
4049 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004050 }
4051
4052 DependentTemplateNames.InsertNode(QTN, InsertPos);
4053 return TemplateName(QTN);
4054}
4055
Douglas Gregor71395fa2009-11-04 00:56:37 +00004056/// \brief Retrieve the template name that represents a dependent
4057/// template name such as \c MetaFun::template operator+.
4058TemplateName
4059ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4060 OverloadedOperatorKind Operator) {
4061 assert((!NNS || NNS->isDependent()) &&
4062 "Nested name specifier must be dependent");
4063
4064 llvm::FoldingSetNodeID ID;
4065 DependentTemplateName::Profile(ID, NNS, Operator);
4066
4067 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004068 DependentTemplateName *QTN
4069 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004070
4071 if (QTN)
4072 return TemplateName(QTN);
4073
4074 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4075 if (CanonNNS == NNS) {
4076 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4077 } else {
4078 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4079 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004080
4081 DependentTemplateName *CheckQTN
4082 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4083 assert(!CheckQTN && "Dependent template name canonicalization broken");
4084 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004085 }
4086
4087 DependentTemplateNames.InsertNode(QTN, InsertPos);
4088 return TemplateName(QTN);
4089}
4090
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004091/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004092/// TargetInfo, produce the corresponding type. The unsigned @p Type
4093/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004094CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004095 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004096 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004097 case TargetInfo::SignedShort: return ShortTy;
4098 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4099 case TargetInfo::SignedInt: return IntTy;
4100 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4101 case TargetInfo::SignedLong: return LongTy;
4102 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4103 case TargetInfo::SignedLongLong: return LongLongTy;
4104 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4105 }
4106
4107 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004108 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004109}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004110
4111//===----------------------------------------------------------------------===//
4112// Type Predicates.
4113//===----------------------------------------------------------------------===//
4114
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004115/// isObjCNSObjectType - Return true if this is an NSObject object using
4116/// NSObject attribute on a c-style pointer type.
4117/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004118/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004119///
4120bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4121 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4122 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004123 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004124 return true;
4125 }
Mike Stump11289f42009-09-09 15:08:12 +00004126 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004127}
4128
Fariborz Jahanian96207692009-02-18 21:49:28 +00004129/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4130/// garbage collection attribute.
4131///
John McCall8ccfcb52009-09-24 19:53:00 +00004132Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4133 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004134 if (getLangOptions().ObjC1 &&
4135 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004136 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004137 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004138 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004139 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004140 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004141 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004142 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004143 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004144 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004145 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004146 // Non-pointers have none gc'able attribute regardless of the attribute
4147 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004148 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004149 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004150 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004151 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004152}
4153
Chris Lattner49af6a42008-04-07 06:51:04 +00004154//===----------------------------------------------------------------------===//
4155// Type Compatibility Testing
4156//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004157
Mike Stump11289f42009-09-09 15:08:12 +00004158/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004159/// compatible.
4160static bool areCompatVectorTypes(const VectorType *LHS,
4161 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004162 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004163 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004164 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004165}
4166
Steve Naroff8e6aee52009-07-23 01:01:38 +00004167//===----------------------------------------------------------------------===//
4168// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4169//===----------------------------------------------------------------------===//
4170
4171/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4172/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004173bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4174 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004175 if (lProto == rProto)
4176 return true;
4177 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4178 E = rProto->protocol_end(); PI != E; ++PI)
4179 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4180 return true;
4181 return false;
4182}
4183
Steve Naroff8e6aee52009-07-23 01:01:38 +00004184/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4185/// return true if lhs's protocols conform to rhs's protocol; false
4186/// otherwise.
4187bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4188 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4189 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4190 return false;
4191}
4192
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004193/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4194/// Class<p1, ...>.
4195bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4196 QualType rhs) {
4197 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4198 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4199 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4200
4201 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4202 E = lhsQID->qual_end(); I != E; ++I) {
4203 bool match = false;
4204 ObjCProtocolDecl *lhsProto = *I;
4205 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4206 E = rhsOPT->qual_end(); J != E; ++J) {
4207 ObjCProtocolDecl *rhsProto = *J;
4208 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4209 match = true;
4210 break;
4211 }
4212 }
4213 if (!match)
4214 return false;
4215 }
4216 return true;
4217}
4218
Steve Naroff8e6aee52009-07-23 01:01:38 +00004219/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4220/// ObjCQualifiedIDType.
4221bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4222 bool compare) {
4223 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004224 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004225 lhs->isObjCIdType() || lhs->isObjCClassType())
4226 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004227 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004228 rhs->isObjCIdType() || rhs->isObjCClassType())
4229 return true;
4230
4231 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004232 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004233
Steve Naroff8e6aee52009-07-23 01:01:38 +00004234 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004235
Steve Naroff8e6aee52009-07-23 01:01:38 +00004236 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004237 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004238 // make sure we check the class hierarchy.
4239 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4240 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4241 E = lhsQID->qual_end(); I != E; ++I) {
4242 // when comparing an id<P> on lhs with a static type on rhs,
4243 // see if static class implements all of id's protocols, directly or
4244 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004245 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004246 return false;
4247 }
4248 }
4249 // If there are no qualifiers and no interface, we have an 'id'.
4250 return true;
4251 }
Mike Stump11289f42009-09-09 15:08:12 +00004252 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004253 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4254 E = lhsQID->qual_end(); I != E; ++I) {
4255 ObjCProtocolDecl *lhsProto = *I;
4256 bool match = false;
4257
4258 // when comparing an id<P> on lhs with a static type on rhs,
4259 // see if static class implements all of id's protocols, directly or
4260 // through its super class and categories.
4261 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4262 E = rhsOPT->qual_end(); J != E; ++J) {
4263 ObjCProtocolDecl *rhsProto = *J;
4264 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4265 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4266 match = true;
4267 break;
4268 }
4269 }
Mike Stump11289f42009-09-09 15:08:12 +00004270 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004271 // make sure we check the class hierarchy.
4272 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4273 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4274 E = lhsQID->qual_end(); I != E; ++I) {
4275 // when comparing an id<P> on lhs with a static type on rhs,
4276 // see if static class implements all of id's protocols, directly or
4277 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004278 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004279 match = true;
4280 break;
4281 }
4282 }
4283 }
4284 if (!match)
4285 return false;
4286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
Steve Naroff8e6aee52009-07-23 01:01:38 +00004288 return true;
4289 }
Mike Stump11289f42009-09-09 15:08:12 +00004290
Steve Naroff8e6aee52009-07-23 01:01:38 +00004291 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4292 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4293
Mike Stump11289f42009-09-09 15:08:12 +00004294 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004295 lhs->getAsObjCInterfacePointerType()) {
4296 if (lhsOPT->qual_empty()) {
4297 bool match = false;
4298 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4299 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4300 E = rhsQID->qual_end(); I != E; ++I) {
4301 // when comparing an id<P> on lhs with a static type on rhs,
4302 // see if static class implements all of id's protocols, directly or
4303 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004304 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004305 match = true;
4306 break;
4307 }
4308 }
4309 if (!match)
4310 return false;
4311 }
4312 return true;
4313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004315 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4316 E = lhsOPT->qual_end(); I != E; ++I) {
4317 ObjCProtocolDecl *lhsProto = *I;
4318 bool match = false;
4319
4320 // when comparing an id<P> on lhs with a static type on rhs,
4321 // see if static class implements all of id's protocols, directly or
4322 // through its super class and categories.
4323 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4324 E = rhsQID->qual_end(); J != E; ++J) {
4325 ObjCProtocolDecl *rhsProto = *J;
4326 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4327 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4328 match = true;
4329 break;
4330 }
4331 }
4332 if (!match)
4333 return false;
4334 }
4335 return true;
4336 }
4337 return false;
4338}
4339
Eli Friedman47f77112008-08-22 00:56:42 +00004340/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004341/// compatible for assignment from RHS to LHS. This handles validation of any
4342/// protocol qualifiers on the LHS or RHS.
4343///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004344bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4345 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004346 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4347 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4348
Steve Naroff1329fa02009-07-15 18:40:39 +00004349 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004350 if (LHS->isObjCUnqualifiedIdOrClass() ||
4351 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004352 return true;
4353
John McCall8b07ec22010-05-15 11:32:37 +00004354 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004355 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4356 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004357 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004358
4359 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4360 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4361 QualType(RHSOPT,0));
4362
John McCall8b07ec22010-05-15 11:32:37 +00004363 // If we have 2 user-defined types, fall into that path.
4364 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004365 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004366
Steve Naroff8e6aee52009-07-23 01:01:38 +00004367 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004368}
4369
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004370/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4371/// for providing type-safty for objective-c pointers used to pass/return
4372/// arguments in block literals. When passed as arguments, passing 'A*' where
4373/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4374/// not OK. For the return type, the opposite is not OK.
4375bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4376 const ObjCObjectPointerType *LHSOPT,
4377 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004378 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004379 return true;
4380
4381 if (LHSOPT->isObjCBuiltinType()) {
4382 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4383 }
4384
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004385 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004386 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4387 QualType(RHSOPT,0),
4388 false);
4389
4390 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4391 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4392 if (LHS && RHS) { // We have 2 user-defined types.
4393 if (LHS != RHS) {
4394 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4395 return false;
4396 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4397 return true;
4398 }
4399 else
4400 return true;
4401 }
4402 return false;
4403}
4404
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004405/// getIntersectionOfProtocols - This routine finds the intersection of set
4406/// of protocols inherited from two distinct objective-c pointer objects.
4407/// It is used to build composite qualifier list of the composite type of
4408/// the conditional expression involving two objective-c pointer objects.
4409static
4410void getIntersectionOfProtocols(ASTContext &Context,
4411 const ObjCObjectPointerType *LHSOPT,
4412 const ObjCObjectPointerType *RHSOPT,
4413 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4414
John McCall8b07ec22010-05-15 11:32:37 +00004415 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4416 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4417 assert(LHS->getInterface() && "LHS must have an interface base");
4418 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004419
4420 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4421 unsigned LHSNumProtocols = LHS->getNumProtocols();
4422 if (LHSNumProtocols > 0)
4423 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4424 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004425 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004426 Context.CollectInheritedProtocols(LHS->getInterface(),
4427 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004428 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4429 LHSInheritedProtocols.end());
4430 }
4431
4432 unsigned RHSNumProtocols = RHS->getNumProtocols();
4433 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004434 ObjCProtocolDecl **RHSProtocols =
4435 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004436 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4437 if (InheritedProtocolSet.count(RHSProtocols[i]))
4438 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4439 }
4440 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004441 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004442 Context.CollectInheritedProtocols(RHS->getInterface(),
4443 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004444 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4445 RHSInheritedProtocols.begin(),
4446 E = RHSInheritedProtocols.end(); I != E; ++I)
4447 if (InheritedProtocolSet.count((*I)))
4448 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004449 }
4450}
4451
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004452/// areCommonBaseCompatible - Returns common base class of the two classes if
4453/// one found. Note that this is O'2 algorithm. But it will be called as the
4454/// last type comparison in a ?-exp of ObjC pointer types before a
4455/// warning is issued. So, its invokation is extremely rare.
4456QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004457 const ObjCObjectPointerType *Lptr,
4458 const ObjCObjectPointerType *Rptr) {
4459 const ObjCObjectType *LHS = Lptr->getObjectType();
4460 const ObjCObjectType *RHS = Rptr->getObjectType();
4461 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4462 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4463 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004464 return QualType();
4465
John McCall8b07ec22010-05-15 11:32:37 +00004466 while ((LDecl = LDecl->getSuperClass())) {
4467 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004468 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004469 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4470 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4471
4472 QualType Result = QualType(LHS, 0);
4473 if (!Protocols.empty())
4474 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4475 Result = getObjCObjectPointerType(Result);
4476 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004477 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004478 }
4479
4480 return QualType();
4481}
4482
John McCall8b07ec22010-05-15 11:32:37 +00004483bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4484 const ObjCObjectType *RHS) {
4485 assert(LHS->getInterface() && "LHS is not an interface type");
4486 assert(RHS->getInterface() && "RHS is not an interface type");
4487
Chris Lattner49af6a42008-04-07 06:51:04 +00004488 // Verify that the base decls are compatible: the RHS must be a subclass of
4489 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004490 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004491 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004492
Chris Lattner49af6a42008-04-07 06:51:04 +00004493 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4494 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004495 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004496 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004497
Chris Lattner49af6a42008-04-07 06:51:04 +00004498 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4499 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004500 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004501 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004502
John McCall8b07ec22010-05-15 11:32:37 +00004503 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4504 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004505 LHSPI != LHSPE; LHSPI++) {
4506 bool RHSImplementsProtocol = false;
4507
4508 // If the RHS doesn't implement the protocol on the left, the types
4509 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004510 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4511 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004512 RHSPI != RHSPE; RHSPI++) {
4513 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004514 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004515 break;
4516 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004517 }
4518 // FIXME: For better diagnostics, consider passing back the protocol name.
4519 if (!RHSImplementsProtocol)
4520 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004521 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004522 // The RHS implements all protocols listed on the LHS.
4523 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004524}
4525
Steve Naroffb7605152009-02-12 17:52:19 +00004526bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4527 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004528 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4529 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004530
Steve Naroff7cae42b2009-07-10 23:34:53 +00004531 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004532 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004533
4534 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4535 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004536}
4537
Mike Stump11289f42009-09-09 15:08:12 +00004538/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004539/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004540/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004541/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004542bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4543 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004544 if (getLangOptions().CPlusPlus)
4545 return hasSameType(LHS, RHS);
4546
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004547 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004548}
4549
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004550bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4551 return !mergeTypes(LHS, RHS, true).isNull();
4552}
4553
4554QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004555 bool OfBlockPointer,
4556 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004557 const FunctionType *lbase = lhs->getAs<FunctionType>();
4558 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004559 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4560 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004561 bool allLTypes = true;
4562 bool allRTypes = true;
4563
4564 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004565 QualType retType;
4566 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004567 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4568 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004569 else
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004570 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4571 false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004572 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004573
4574 if (Unqualified)
4575 retType = retType.getUnqualifiedType();
4576
4577 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4578 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4579 if (Unqualified) {
4580 LRetType = LRetType.getUnqualifiedType();
4581 RRetType = RRetType.getUnqualifiedType();
4582 }
4583
4584 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004585 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004586 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004587 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004588 // FIXME: double check this
4589 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4590 // rbase->getRegParmAttr() != 0 &&
4591 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004592 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4593 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004594 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4595 lbaseInfo.getRegParm();
4596 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4597 if (NoReturn != lbaseInfo.getNoReturn() ||
4598 RegParm != lbaseInfo.getRegParm())
4599 allLTypes = false;
4600 if (NoReturn != rbaseInfo.getNoReturn() ||
4601 RegParm != rbaseInfo.getRegParm())
4602 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004603 CallingConv lcc = lbaseInfo.getCC();
4604 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004605 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004606 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004607 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004608
Eli Friedman47f77112008-08-22 00:56:42 +00004609 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004610 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4611 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004612 unsigned lproto_nargs = lproto->getNumArgs();
4613 unsigned rproto_nargs = rproto->getNumArgs();
4614
4615 // Compatible functions must have the same number of arguments
4616 if (lproto_nargs != rproto_nargs)
4617 return QualType();
4618
4619 // Variadic and non-variadic functions aren't compatible
4620 if (lproto->isVariadic() != rproto->isVariadic())
4621 return QualType();
4622
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004623 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4624 return QualType();
4625
Eli Friedman47f77112008-08-22 00:56:42 +00004626 // Check argument compatibility
4627 llvm::SmallVector<QualType, 10> types;
4628 for (unsigned i = 0; i < lproto_nargs; i++) {
4629 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4630 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004631 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4632 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004633 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004634
4635 if (Unqualified)
4636 argtype = argtype.getUnqualifiedType();
4637
Eli Friedman47f77112008-08-22 00:56:42 +00004638 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004639 if (Unqualified) {
4640 largtype = largtype.getUnqualifiedType();
4641 rargtype = rargtype.getUnqualifiedType();
4642 }
4643
Chris Lattner465fa322008-10-05 17:34:18 +00004644 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4645 allLTypes = false;
4646 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4647 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004648 }
4649 if (allLTypes) return lhs;
4650 if (allRTypes) return rhs;
4651 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004652 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004653 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004654 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004655 }
4656
4657 if (lproto) allRTypes = false;
4658 if (rproto) allLTypes = false;
4659
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004660 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004661 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004662 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004663 if (proto->isVariadic()) return QualType();
4664 // Check that the types are compatible with the types that
4665 // would result from default argument promotions (C99 6.7.5.3p15).
4666 // The only types actually affected are promotable integer
4667 // types and floats, which would be passed as a different
4668 // type depending on whether the prototype is visible.
4669 unsigned proto_nargs = proto->getNumArgs();
4670 for (unsigned i = 0; i < proto_nargs; ++i) {
4671 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004672
4673 // Look at the promotion type of enum types, since that is the type used
4674 // to pass enum values.
4675 if (const EnumType *Enum = argTy->getAs<EnumType>())
4676 argTy = Enum->getDecl()->getPromotionType();
4677
Eli Friedman47f77112008-08-22 00:56:42 +00004678 if (argTy->isPromotableIntegerType() ||
4679 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4680 return QualType();
4681 }
4682
4683 if (allLTypes) return lhs;
4684 if (allRTypes) return rhs;
4685 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004686 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004687 proto->getTypeQuals(),
4688 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004689 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004690 }
4691
4692 if (allLTypes) return lhs;
4693 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004694 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004695 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004696}
4697
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004698QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004699 bool OfBlockPointer,
4700 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004701 // C++ [expr]: If an expression initially has the type "reference to T", the
4702 // type is adjusted to "T" prior to any further analysis, the expression
4703 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004704 // expression is an lvalue unless the reference is an rvalue reference and
4705 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004706 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4707 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004708
4709 if (Unqualified) {
4710 LHS = LHS.getUnqualifiedType();
4711 RHS = RHS.getUnqualifiedType();
4712 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00004713
Eli Friedman47f77112008-08-22 00:56:42 +00004714 QualType LHSCan = getCanonicalType(LHS),
4715 RHSCan = getCanonicalType(RHS);
4716
4717 // If two types are identical, they are compatible.
4718 if (LHSCan == RHSCan)
4719 return LHS;
4720
John McCall8ccfcb52009-09-24 19:53:00 +00004721 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004722 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4723 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004724 if (LQuals != RQuals) {
4725 // If any of these qualifiers are different, we have a type
4726 // mismatch.
4727 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4728 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4729 return QualType();
4730
4731 // Exactly one GC qualifier difference is allowed: __strong is
4732 // okay if the other type has no GC qualifier but is an Objective
4733 // C object pointer (i.e. implicitly strong by default). We fix
4734 // this by pretending that the unqualified type was actually
4735 // qualified __strong.
4736 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4737 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4738 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4739
4740 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4741 return QualType();
4742
4743 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4744 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4745 }
4746 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4747 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4748 }
Eli Friedman47f77112008-08-22 00:56:42 +00004749 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004750 }
4751
4752 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004753
Eli Friedmandcca6332009-06-01 01:22:52 +00004754 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4755 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004756
Chris Lattnerfd652912008-01-14 05:45:46 +00004757 // We want to consider the two function types to be the same for these
4758 // comparisons, just force one to the other.
4759 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4760 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004761
4762 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004763 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4764 LHSClass = Type::ConstantArray;
4765 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4766 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004767
John McCall8b07ec22010-05-15 11:32:37 +00004768 // ObjCInterfaces are just specialized ObjCObjects.
4769 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4770 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4771
Nate Begemance4d7fc2008-04-18 23:10:10 +00004772 // Canonicalize ExtVector -> Vector.
4773 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4774 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004775
Chris Lattner95554662008-04-07 05:43:21 +00004776 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004777 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004778 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004779 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004780 // Compatibility is based on the underlying type, not the promotion
4781 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004782 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004783 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4784 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004785 }
John McCall9dd450b2009-09-21 23:43:11 +00004786 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004787 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4788 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004789 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004790
Eli Friedman47f77112008-08-22 00:56:42 +00004791 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004792 }
Eli Friedman47f77112008-08-22 00:56:42 +00004793
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004794 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004795 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004796#define TYPE(Class, Base)
4797#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004798#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004799#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4800#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4801#include "clang/AST/TypeNodes.def"
4802 assert(false && "Non-canonical and dependent types shouldn't get here");
4803 return QualType();
4804
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004805 case Type::LValueReference:
4806 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004807 case Type::MemberPointer:
4808 assert(false && "C++ should never be in mergeTypes");
4809 return QualType();
4810
John McCall8b07ec22010-05-15 11:32:37 +00004811 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004812 case Type::IncompleteArray:
4813 case Type::VariableArray:
4814 case Type::FunctionProto:
4815 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004816 assert(false && "Types are eliminated above");
4817 return QualType();
4818
Chris Lattnerfd652912008-01-14 05:45:46 +00004819 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004820 {
4821 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004822 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4823 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004824 if (Unqualified) {
4825 LHSPointee = LHSPointee.getUnqualifiedType();
4826 RHSPointee = RHSPointee.getUnqualifiedType();
4827 }
4828 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4829 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004830 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004831 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004832 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004833 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004834 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004835 return getPointerType(ResultType);
4836 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004837 case Type::BlockPointer:
4838 {
4839 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004840 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4841 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004842 if (Unqualified) {
4843 LHSPointee = LHSPointee.getUnqualifiedType();
4844 RHSPointee = RHSPointee.getUnqualifiedType();
4845 }
4846 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4847 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00004848 if (ResultType.isNull()) return QualType();
4849 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4850 return LHS;
4851 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4852 return RHS;
4853 return getBlockPointerType(ResultType);
4854 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004855 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004856 {
4857 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4858 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4859 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4860 return QualType();
4861
4862 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4863 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004864 if (Unqualified) {
4865 LHSElem = LHSElem.getUnqualifiedType();
4866 RHSElem = RHSElem.getUnqualifiedType();
4867 }
4868
4869 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004870 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004871 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4872 return LHS;
4873 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4874 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004875 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4876 ArrayType::ArraySizeModifier(), 0);
4877 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4878 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004879 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4880 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004881 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4882 return LHS;
4883 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4884 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004885 if (LVAT) {
4886 // FIXME: This isn't correct! But tricky to implement because
4887 // the array's size has to be the size of LHS, but the type
4888 // has to be different.
4889 return LHS;
4890 }
4891 if (RVAT) {
4892 // FIXME: This isn't correct! But tricky to implement because
4893 // the array's size has to be the size of RHS, but the type
4894 // has to be different.
4895 return RHS;
4896 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004897 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4898 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004899 return getIncompleteArrayType(ResultType,
4900 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004901 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004902 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004903 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004904 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004905 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004906 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004907 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004908 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004909 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004910 case Type::Complex:
4911 // Distinct complex types are incompatible.
4912 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004913 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004914 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004915 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4916 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004917 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004918 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004919 case Type::ObjCObject: {
4920 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004921 // FIXME: This should be type compatibility, e.g. whether
4922 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004923 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4924 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4925 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004926 return LHS;
4927
Eli Friedman47f77112008-08-22 00:56:42 +00004928 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004929 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004930 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004931 if (OfBlockPointer) {
4932 if (canAssignObjCInterfacesInBlockPointer(
4933 LHS->getAs<ObjCObjectPointerType>(),
4934 RHS->getAs<ObjCObjectPointerType>()))
4935 return LHS;
4936 return QualType();
4937 }
John McCall9dd450b2009-09-21 23:43:11 +00004938 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4939 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004940 return LHS;
4941
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004942 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004943 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004944 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004945
4946 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004947}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004948
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004949/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4950/// 'RHS' attributes and returns the merged version; including for function
4951/// return types.
4952QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4953 QualType LHSCan = getCanonicalType(LHS),
4954 RHSCan = getCanonicalType(RHS);
4955 // If two types are identical, they are compatible.
4956 if (LHSCan == RHSCan)
4957 return LHS;
4958 if (RHSCan->isFunctionType()) {
4959 if (!LHSCan->isFunctionType())
4960 return QualType();
4961 QualType OldReturnType =
4962 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4963 QualType NewReturnType =
4964 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4965 QualType ResReturnType =
4966 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4967 if (ResReturnType.isNull())
4968 return QualType();
4969 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4970 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4971 // In either case, use OldReturnType to build the new function type.
4972 const FunctionType *F = LHS->getAs<FunctionType>();
4973 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4974 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4975 QualType ResultType
4976 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4977 FPT->getNumArgs(), FPT->isVariadic(),
4978 FPT->getTypeQuals(),
4979 FPT->hasExceptionSpec(),
4980 FPT->hasAnyExceptionSpec(),
4981 FPT->getNumExceptions(),
4982 FPT->exception_begin(),
4983 Info);
4984 return ResultType;
4985 }
4986 }
4987 return QualType();
4988 }
4989
4990 // If the qualifiers are different, the types can still be merged.
4991 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4992 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4993 if (LQuals != RQuals) {
4994 // If any of these qualifiers are different, we have a type mismatch.
4995 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4996 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4997 return QualType();
4998
4999 // Exactly one GC qualifier difference is allowed: __strong is
5000 // okay if the other type has no GC qualifier but is an Objective
5001 // C object pointer (i.e. implicitly strong by default). We fix
5002 // this by pretending that the unqualified type was actually
5003 // qualified __strong.
5004 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5005 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5006 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5007
5008 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5009 return QualType();
5010
5011 if (GC_L == Qualifiers::Strong)
5012 return LHS;
5013 if (GC_R == Qualifiers::Strong)
5014 return RHS;
5015 return QualType();
5016 }
5017
5018 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5019 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5020 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5021 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5022 if (ResQT == LHSBaseQT)
5023 return LHS;
5024 if (ResQT == RHSBaseQT)
5025 return RHS;
5026 }
5027 return QualType();
5028}
5029
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005030//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005031// Integer Predicates
5032//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005033
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005034unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00005035 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005036 return 1;
John McCall56774992009-12-09 09:09:27 +00005037 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005038 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00005039 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005040 return (unsigned)getTypeSize(T);
5041}
5042
5043QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005044 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005045
5046 // Turn <4 x signed int> -> <4 x unsigned int>
5047 if (const VectorType *VTy = T->getAs<VectorType>())
5048 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00005049 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005050
5051 // For enums, we return the unsigned version of the base type.
5052 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005053 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005054
5055 const BuiltinType *BTy = T->getAs<BuiltinType>();
5056 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005057 switch (BTy->getKind()) {
5058 case BuiltinType::Char_S:
5059 case BuiltinType::SChar:
5060 return UnsignedCharTy;
5061 case BuiltinType::Short:
5062 return UnsignedShortTy;
5063 case BuiltinType::Int:
5064 return UnsignedIntTy;
5065 case BuiltinType::Long:
5066 return UnsignedLongTy;
5067 case BuiltinType::LongLong:
5068 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005069 case BuiltinType::Int128:
5070 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005071 default:
5072 assert(0 && "Unexpected signed integer type");
5073 return QualType();
5074 }
5075}
5076
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005077ExternalASTSource::~ExternalASTSource() { }
5078
5079void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005080
5081
5082//===----------------------------------------------------------------------===//
5083// Builtin Type Computation
5084//===----------------------------------------------------------------------===//
5085
5086/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5087/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00005088static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005089 ASTContext::GetBuiltinTypeError &Error,
5090 bool AllowTypeModifiers = true) {
5091 // Modifiers.
5092 int HowLong = 0;
5093 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00005094
Chris Lattnerecd79c62009-06-14 00:45:47 +00005095 // Read the modifiers first.
5096 bool Done = false;
5097 while (!Done) {
5098 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005099 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005100 case 'S':
5101 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5102 assert(!Signed && "Can't use 'S' modifier multiple times!");
5103 Signed = true;
5104 break;
5105 case 'U':
5106 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5107 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5108 Unsigned = true;
5109 break;
5110 case 'L':
5111 assert(HowLong <= 2 && "Can't have LLLL modifier");
5112 ++HowLong;
5113 break;
5114 }
5115 }
5116
5117 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005118
Chris Lattnerecd79c62009-06-14 00:45:47 +00005119 // Read the base type.
5120 switch (*Str++) {
5121 default: assert(0 && "Unknown builtin type letter!");
5122 case 'v':
5123 assert(HowLong == 0 && !Signed && !Unsigned &&
5124 "Bad modifiers used with 'v'!");
5125 Type = Context.VoidTy;
5126 break;
5127 case 'f':
5128 assert(HowLong == 0 && !Signed && !Unsigned &&
5129 "Bad modifiers used with 'f'!");
5130 Type = Context.FloatTy;
5131 break;
5132 case 'd':
5133 assert(HowLong < 2 && !Signed && !Unsigned &&
5134 "Bad modifiers used with 'd'!");
5135 if (HowLong)
5136 Type = Context.LongDoubleTy;
5137 else
5138 Type = Context.DoubleTy;
5139 break;
5140 case 's':
5141 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5142 if (Unsigned)
5143 Type = Context.UnsignedShortTy;
5144 else
5145 Type = Context.ShortTy;
5146 break;
5147 case 'i':
5148 if (HowLong == 3)
5149 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5150 else if (HowLong == 2)
5151 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5152 else if (HowLong == 1)
5153 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5154 else
5155 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5156 break;
5157 case 'c':
5158 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5159 if (Signed)
5160 Type = Context.SignedCharTy;
5161 else if (Unsigned)
5162 Type = Context.UnsignedCharTy;
5163 else
5164 Type = Context.CharTy;
5165 break;
5166 case 'b': // boolean
5167 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5168 Type = Context.BoolTy;
5169 break;
5170 case 'z': // size_t.
5171 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5172 Type = Context.getSizeType();
5173 break;
5174 case 'F':
5175 Type = Context.getCFConstantStringType();
5176 break;
5177 case 'a':
5178 Type = Context.getBuiltinVaListType();
5179 assert(!Type.isNull() && "builtin va list type not initialized!");
5180 break;
5181 case 'A':
5182 // This is a "reference" to a va_list; however, what exactly
5183 // this means depends on how va_list is defined. There are two
5184 // different kinds of va_list: ones passed by value, and ones
5185 // passed by reference. An example of a by-value va_list is
5186 // x86, where va_list is a char*. An example of by-ref va_list
5187 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5188 // we want this argument to be a char*&; for x86-64, we want
5189 // it to be a __va_list_tag*.
5190 Type = Context.getBuiltinVaListType();
5191 assert(!Type.isNull() && "builtin va list type not initialized!");
5192 if (Type->isArrayType()) {
5193 Type = Context.getArrayDecayedType(Type);
5194 } else {
5195 Type = Context.getLValueReferenceType(Type);
5196 }
5197 break;
5198 case 'V': {
5199 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005200 unsigned NumElements = strtoul(Str, &End, 10);
5201 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005202
Chris Lattnerecd79c62009-06-14 00:45:47 +00005203 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005204
Chris Lattnerecd79c62009-06-14 00:45:47 +00005205 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005206 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005207 Type = Context.getVectorType(ElementType, NumElements,
5208 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005209 break;
5210 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005211 case 'X': {
5212 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5213 Type = Context.getComplexType(ElementType);
5214 break;
5215 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005216 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005217 Type = Context.getFILEType();
5218 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005219 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005220 return QualType();
5221 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005222 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005223 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005224 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005225 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005226 else
5227 Type = Context.getjmp_bufType();
5228
Mike Stump2adb4da2009-07-28 23:47:15 +00005229 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005230 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005231 return QualType();
5232 }
5233 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005234 }
Mike Stump11289f42009-09-09 15:08:12 +00005235
Chris Lattnerecd79c62009-06-14 00:45:47 +00005236 if (!AllowTypeModifiers)
5237 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005238
Chris Lattnerecd79c62009-06-14 00:45:47 +00005239 Done = false;
5240 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005241 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005242 default: Done = true; --Str; break;
5243 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005244 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005245 {
5246 // Both pointers and references can have their pointee types
5247 // qualified with an address space.
5248 char *End;
5249 unsigned AddrSpace = strtoul(Str, &End, 10);
5250 if (End != Str && AddrSpace != 0) {
5251 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5252 Str = End;
5253 }
5254 }
5255 if (c == '*')
5256 Type = Context.getPointerType(Type);
5257 else
5258 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005259 break;
5260 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5261 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005262 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005263 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005264 case 'D':
5265 Type = Context.getVolatileType(Type);
5266 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005267 }
5268 }
Mike Stump11289f42009-09-09 15:08:12 +00005269
Chris Lattnerecd79c62009-06-14 00:45:47 +00005270 return Type;
5271}
5272
5273/// GetBuiltinType - Return the type for the specified builtin.
5274QualType ASTContext::GetBuiltinType(unsigned id,
5275 GetBuiltinTypeError &Error) {
5276 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005277
Chris Lattnerecd79c62009-06-14 00:45:47 +00005278 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005279
Chris Lattnerecd79c62009-06-14 00:45:47 +00005280 Error = GE_None;
5281 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5282 if (Error != GE_None)
5283 return QualType();
5284 while (TypeStr[0] && TypeStr[0] != '.') {
5285 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5286 if (Error != GE_None)
5287 return QualType();
5288
5289 // Do array -> pointer decay. The builtin should use the decayed type.
5290 if (Ty->isArrayType())
5291 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005292
Chris Lattnerecd79c62009-06-14 00:45:47 +00005293 ArgTypes.push_back(Ty);
5294 }
5295
5296 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5297 "'.' should only occur at end of builtin type list!");
5298
5299 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5300 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5301 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005302
5303 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005304 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005305 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005306 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005307}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005308
5309QualType
5310ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5311 // Perform the usual unary conversions. We do this early so that
5312 // integral promotions to "int" can allow us to exit early, in the
5313 // lhs == rhs check. Also, for conversion purposes, we ignore any
5314 // qualifiers. For example, "const float" and "float" are
5315 // equivalent.
5316 if (lhs->isPromotableIntegerType())
5317 lhs = getPromotedIntegerType(lhs);
5318 else
5319 lhs = lhs.getUnqualifiedType();
5320 if (rhs->isPromotableIntegerType())
5321 rhs = getPromotedIntegerType(rhs);
5322 else
5323 rhs = rhs.getUnqualifiedType();
5324
5325 // If both types are identical, no conversion is needed.
5326 if (lhs == rhs)
5327 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005328
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005329 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5330 // The caller can deal with this (e.g. pointer + int).
5331 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5332 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005333
5334 // At this point, we have two different arithmetic types.
5335
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005336 // Handle complex types first (C99 6.3.1.8p1).
5337 if (lhs->isComplexType() || rhs->isComplexType()) {
5338 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005339 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005340 // convert the rhs to the lhs complex type.
5341 return lhs;
5342 }
Mike Stump11289f42009-09-09 15:08:12 +00005343 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005344 // convert the lhs to the rhs complex type.
5345 return rhs;
5346 }
5347 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005348 // When both operands are complex, the shorter operand is converted to the
5349 // type of the longer, and that is the type of the result. This corresponds
5350 // to what is done when combining two real floating-point operands.
5351 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005352 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005353 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005354 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005355 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005356 // "double _Complex" is promoted to "long double _Complex".
5357 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005358
5359 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005360 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005361 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005362 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005363 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005364 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5365 // domains match. This is a requirement for our implementation, C99
5366 // does not require this promotion.
5367 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5368 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5369 return rhs;
5370 } else { // handle "_Complex double, double".
5371 return lhs;
5372 }
5373 }
5374 return lhs; // The domain/size match exactly.
5375 }
5376 // Now handle "real" floating types (i.e. float, double, long double).
5377 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5378 // if we have an integer operand, the result is the real floating type.
5379 if (rhs->isIntegerType()) {
5380 // convert rhs to the lhs floating point type.
5381 return lhs;
5382 }
5383 if (rhs->isComplexIntegerType()) {
5384 // convert rhs to the complex floating point type.
5385 return getComplexType(lhs);
5386 }
5387 if (lhs->isIntegerType()) {
5388 // convert lhs to the rhs floating point type.
5389 return rhs;
5390 }
Mike Stump11289f42009-09-09 15:08:12 +00005391 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005392 // convert lhs to the complex floating point type.
5393 return getComplexType(rhs);
5394 }
5395 // We have two real floating types, float/complex combos were handled above.
5396 // Convert the smaller operand to the bigger result.
5397 int result = getFloatingTypeOrder(lhs, rhs);
5398 if (result > 0) // convert the rhs
5399 return lhs;
5400 assert(result < 0 && "illegal float comparison");
5401 return rhs; // convert the lhs
5402 }
5403 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5404 // Handle GCC complex int extension.
5405 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5406 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5407
5408 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005409 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005410 rhsComplexInt->getElementType()) >= 0)
5411 return lhs; // convert the rhs
5412 return rhs;
5413 } else if (lhsComplexInt && rhs->isIntegerType()) {
5414 // convert the rhs to the lhs complex type.
5415 return lhs;
5416 } else if (rhsComplexInt && lhs->isIntegerType()) {
5417 // convert the lhs to the rhs complex type.
5418 return rhs;
5419 }
5420 }
5421 // Finally, we have two differing integer types.
5422 // The rules for this case are in C99 6.3.1.8
5423 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005424 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5425 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005426 QualType destType;
5427 if (lhsSigned == rhsSigned) {
5428 // Same signedness; use the higher-ranked type
5429 destType = compare >= 0 ? lhs : rhs;
5430 } else if (compare != (lhsSigned ? 1 : -1)) {
5431 // The unsigned type has greater than or equal rank to the
5432 // signed type, so use the unsigned type
5433 destType = lhsSigned ? rhs : lhs;
5434 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5435 // The two types are different widths; if we are here, that
5436 // means the signed type is larger than the unsigned type, so
5437 // use the signed type.
5438 destType = lhsSigned ? lhs : rhs;
5439 } else {
5440 // The signed type is higher-ranked than the unsigned type,
5441 // but isn't actually any bigger (like unsigned int and long
5442 // on most 32-bit systems). Use the unsigned type corresponding
5443 // to the signed type.
5444 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5445 }
5446 return destType;
5447}
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005448
5449GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5450 GVALinkage External = GVA_StrongExternal;
5451
5452 Linkage L = FD->getLinkage();
5453 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5454 FD->getType()->getLinkage() == UniqueExternalLinkage)
5455 L = UniqueExternalLinkage;
5456
5457 switch (L) {
5458 case NoLinkage:
5459 case InternalLinkage:
5460 case UniqueExternalLinkage:
5461 return GVA_Internal;
5462
5463 case ExternalLinkage:
5464 switch (FD->getTemplateSpecializationKind()) {
5465 case TSK_Undeclared:
5466 case TSK_ExplicitSpecialization:
5467 External = GVA_StrongExternal;
5468 break;
5469
5470 case TSK_ExplicitInstantiationDefinition:
5471 return GVA_ExplicitTemplateInstantiation;
5472
5473 case TSK_ExplicitInstantiationDeclaration:
5474 case TSK_ImplicitInstantiation:
5475 External = GVA_TemplateInstantiation;
5476 break;
5477 }
5478 }
5479
5480 if (!FD->isInlined())
5481 return External;
5482
5483 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5484 // GNU or C99 inline semantics. Determine whether this symbol should be
5485 // externally visible.
5486 if (FD->isInlineDefinitionExternallyVisible())
5487 return External;
5488
5489 // C99 inline semantics, where the symbol is not externally visible.
5490 return GVA_C99Inline;
5491 }
5492
5493 // C++0x [temp.explicit]p9:
5494 // [ Note: The intent is that an inline function that is the subject of
5495 // an explicit instantiation declaration will still be implicitly
5496 // instantiated when used so that the body can be considered for
5497 // inlining, but that no out-of-line copy of the inline function would be
5498 // generated in the translation unit. -- end note ]
5499 if (FD->getTemplateSpecializationKind()
5500 == TSK_ExplicitInstantiationDeclaration)
5501 return GVA_C99Inline;
5502
5503 return GVA_CXXInline;
5504}
5505
5506GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5507 // If this is a static data member, compute the kind of template
5508 // specialization. Otherwise, this variable is not part of a
5509 // template.
5510 TemplateSpecializationKind TSK = TSK_Undeclared;
5511 if (VD->isStaticDataMember())
5512 TSK = VD->getTemplateSpecializationKind();
5513
5514 Linkage L = VD->getLinkage();
5515 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5516 VD->getType()->getLinkage() == UniqueExternalLinkage)
5517 L = UniqueExternalLinkage;
5518
5519 switch (L) {
5520 case NoLinkage:
5521 case InternalLinkage:
5522 case UniqueExternalLinkage:
5523 return GVA_Internal;
5524
5525 case ExternalLinkage:
5526 switch (TSK) {
5527 case TSK_Undeclared:
5528 case TSK_ExplicitSpecialization:
5529 return GVA_StrongExternal;
5530
5531 case TSK_ExplicitInstantiationDeclaration:
5532 llvm_unreachable("Variable should not be instantiated");
5533 // Fall through to treat this like any other instantiation.
5534
5535 case TSK_ExplicitInstantiationDefinition:
5536 return GVA_ExplicitTemplateInstantiation;
5537
5538 case TSK_ImplicitInstantiation:
5539 return GVA_TemplateInstantiation;
5540 }
5541 }
5542
5543 return GVA_StrongExternal;
5544}
5545
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005546bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005547 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5548 if (!VD->isFileVarDecl())
5549 return false;
5550 } else if (!isa<FunctionDecl>(D))
5551 return false;
5552
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005553 // Weak references don't produce any output by themselves.
5554 if (D->hasAttr<WeakRefAttr>())
5555 return false;
5556
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005557 // Aliases and used decls are required.
5558 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5559 return true;
5560
5561 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5562 // Forward declarations aren't required.
5563 if (!FD->isThisDeclarationADefinition())
5564 return false;
5565
5566 // Constructors and destructors are required.
5567 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5568 return true;
5569
5570 // The key function for a class is required.
5571 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5572 const CXXRecordDecl *RD = MD->getParent();
5573 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5574 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5575 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5576 return true;
5577 }
5578 }
5579
5580 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5581
5582 // static, static inline, always_inline, and extern inline functions can
5583 // always be deferred. Normal inline functions can be deferred in C99/C++.
5584 // Implicit template instantiations can also be deferred in C++.
5585 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5586 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5587 return false;
5588 return true;
5589 }
5590
5591 const VarDecl *VD = cast<VarDecl>(D);
5592 assert(VD->isFileVarDecl() && "Expected file scoped var");
5593
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005594 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5595 return false;
5596
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005597 // Structs that have non-trivial constructors or destructors are required.
5598
5599 // FIXME: Handle references.
5600 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5601 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5602 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
5603 return true;
5604 }
5605 }
5606
5607 GVALinkage L = GetGVALinkageForVariable(VD);
5608 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5609 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5610 return false;
5611 }
5612
5613 return true;
5614}