blob: 6e7bb0773cf619c6948b1711aff0514d1ae0b612 [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
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner465fa322008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +000044 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000045 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000046 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Douglas Gregor9507d462010-03-19 22:13:20 +000047 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +000049 BuiltinInfo(builtins),
50 DeclarationNames(*this),
51 ExternalSource(0), PrintingPolicy(LOpts),
John McCallc62bb642010-03-24 05:22:00 +000052 LastSDM(0, 0) {
David Chisnall9f57c292009-08-17 16:35:33 +000053 ObjCIdRedefinitionType = QualType();
54 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000055 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000056 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000057 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000058 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000059}
60
Chris Lattnerd5973eb2006-11-12 00:53:46 +000061ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000062 // Release the DenseMaps associated with DeclContext objects.
63 // FIXME: Is this the ideal solution?
64 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +000065
Douglas Gregor1a809332010-05-23 18:26:36 +000066 if (!FreeMemory) {
67 // Call all of the deallocation functions.
68 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
69 Deallocations[I].first(Deallocations[I].second);
70 }
71
Douglas Gregor832940b2010-03-02 23:58:15 +000072 // Release all of the memory associated with overridden C++ methods.
73 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
74 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
75 OM != OMEnd; ++OM)
76 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +000077
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000078 if (FreeMemory) {
79 // Deallocate all the types.
80 while (!Types.empty()) {
81 Types.back()->Destroy(*this);
82 Types.pop_back();
83 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000084
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000085 for (llvm::FoldingSet<ExtQuals>::iterator
86 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
87 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000088 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000089 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000090
Ted Kremenekc3015a92010-03-08 20:56:29 +000091 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
92 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
93 // Increment in loop to prevent using deallocated memory.
94 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
95 R->Destroy(*this);
96 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000097
Ted Kremenekc3015a92010-03-08 20:56:29 +000098 for (llvm::DenseMap<const ObjCContainerDecl*,
99 const ASTRecordLayout*>::iterator
100 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
101 // Increment in loop to prevent using deallocated memory.
102 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
103 R->Destroy(*this);
104 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000105 }
106
Douglas Gregorf21eb492009-03-26 23:50:42 +0000107 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000108 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
109 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000110 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000111 NNS != NNSEnd; ) {
112 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000113 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000114 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000115
116 if (GlobalNestedNameSpecifier)
117 GlobalNestedNameSpecifier->Destroy(*this);
118
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000119 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000120}
121
Douglas Gregor1a809332010-05-23 18:26:36 +0000122void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
123 Deallocations.push_back(std::make_pair(Callback, Data));
124}
125
Mike Stump11289f42009-09-09 15:08:12 +0000126void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000127ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
128 ExternalSource.reset(Source.take());
129}
130
Chris Lattner4eb445d2007-01-26 01:27:23 +0000131void ASTContext::PrintStats() const {
132 fprintf(stderr, "*** AST Context Stats:\n");
133 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000134
Douglas Gregora30d0462009-05-26 14:40:08 +0000135 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000136#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000137#define ABSTRACT_TYPE(Name, Parent)
138#include "clang/AST/TypeNodes.def"
139 0 // Extra
140 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000141
Chris Lattner4eb445d2007-01-26 01:27:23 +0000142 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
143 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000144 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000145 }
146
Douglas Gregora30d0462009-05-26 14:40:08 +0000147 unsigned Idx = 0;
148 unsigned TotalBytes = 0;
149#define TYPE(Name, Parent) \
150 if (counts[Idx]) \
151 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
152 TotalBytes += counts[Idx] * sizeof(Name##Type); \
153 ++Idx;
154#define ABSTRACT_TYPE(Name, Parent)
155#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000156
Douglas Gregora30d0462009-05-26 14:40:08 +0000157 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000158
159 if (ExternalSource.get()) {
160 fprintf(stderr, "\n");
161 ExternalSource->PrintStats();
162 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000163}
164
165
John McCall48f2d582009-10-23 23:03:21 +0000166void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000167 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000168 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000169 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000170}
171
Chris Lattner970e54e2006-11-12 00:37:36 +0000172void ASTContext::InitBuiltinTypes() {
173 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattner970e54e2006-11-12 00:37:36 +0000175 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000176 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000177
Chris Lattner970e54e2006-11-12 00:37:36 +0000178 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000179 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000180 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000181 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000182 InitBuiltinType(CharTy, BuiltinType::Char_S);
183 else
184 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000185 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000186 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
187 InitBuiltinType(ShortTy, BuiltinType::Short);
188 InitBuiltinType(IntTy, BuiltinType::Int);
189 InitBuiltinType(LongTy, BuiltinType::Long);
190 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattner970e54e2006-11-12 00:37:36 +0000192 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000193 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
194 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
195 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
196 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
197 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner970e54e2006-11-12 00:37:36 +0000199 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000200 InitBuiltinType(FloatTy, BuiltinType::Float);
201 InitBuiltinType(DoubleTy, BuiltinType::Double);
202 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000203
Chris Lattnerf122cef2009-04-30 02:43:43 +0000204 // GNU extension, 128-bit integers.
205 InitBuiltinType(Int128Ty, BuiltinType::Int128);
206 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
207
Chris Lattner007cb022009-02-26 23:43:47 +0000208 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
209 InitBuiltinType(WCharTy, BuiltinType::WChar);
210 else // C99
211 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000212
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000213 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
214 InitBuiltinType(Char16Ty, BuiltinType::Char16);
215 else // C99
216 Char16Ty = getFromTargetType(Target.getChar16Type());
217
218 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
219 InitBuiltinType(Char32Ty, BuiltinType::Char32);
220 else // C99
221 Char32Ty = getFromTargetType(Target.getChar32Type());
222
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000224 InitBuiltinType(OverloadTy, BuiltinType::Overload);
225
226 // Placeholder type for type-dependent expressions whose type is
227 // completely unknown. No code should ever check a type against
228 // DependentTy and users should never see it; however, it is here to
229 // help diagnose failures to properly check for type-dependent
230 // expressions.
231 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232
Mike Stump11289f42009-09-09 15:08:12 +0000233 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000234 // not yet been deduced.
235 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner970e54e2006-11-12 00:37:36 +0000237 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000238 FloatComplexTy = getComplexType(FloatTy);
239 DoubleComplexTy = getComplexType(DoubleTy);
240 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000241
Steve Naroff66e9f332007-10-15 14:41:52 +0000242 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000243
Steve Naroff1329fa02009-07-15 18:40:39 +0000244 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
245 ObjCIdTypedefType = QualType();
246 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000247 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000248
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000249 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000250 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
251 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000252 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000253
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000254 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000255
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000256 // void * type
257 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000258
259 // nullptr type (C++0x 2.14.7)
260 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000261}
262
Douglas Gregor86d142a2009-10-08 07:24:58 +0000263MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000264ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000265 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000266 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000267 = InstantiatedFromStaticDataMember.find(Var);
268 if (Pos == InstantiatedFromStaticDataMember.end())
269 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000270
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000271 return Pos->second;
272}
273
Mike Stump11289f42009-09-09 15:08:12 +0000274void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000275ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
276 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000277 assert(Inst->isStaticDataMember() && "Not a static data member");
278 assert(Tmpl->isStaticDataMember() && "Not a static data member");
279 assert(!InstantiatedFromStaticDataMember[Inst] &&
280 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000281 InstantiatedFromStaticDataMember[Inst]
282 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000283}
284
John McCalle61f2ba2009-11-18 02:36:19 +0000285NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000286ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000287 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000288 = InstantiatedFromUsingDecl.find(UUD);
289 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000290 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000291
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000292 return Pos->second;
293}
294
295void
John McCallb96ec562009-12-04 22:46:56 +0000296ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
297 assert((isa<UsingDecl>(Pattern) ||
298 isa<UnresolvedUsingValueDecl>(Pattern) ||
299 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
300 "pattern decl is not a using decl");
301 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
302 InstantiatedFromUsingDecl[Inst] = Pattern;
303}
304
305UsingShadowDecl *
306ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
307 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
308 = InstantiatedFromUsingShadowDecl.find(Inst);
309 if (Pos == InstantiatedFromUsingShadowDecl.end())
310 return 0;
311
312 return Pos->second;
313}
314
315void
316ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
317 UsingShadowDecl *Pattern) {
318 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
319 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000320}
321
Anders Carlsson5da84842009-09-01 04:26:58 +0000322FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
323 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
324 = InstantiatedFromUnnamedFieldDecl.find(Field);
325 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
326 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Anders Carlsson5da84842009-09-01 04:26:58 +0000328 return Pos->second;
329}
330
331void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
332 FieldDecl *Tmpl) {
333 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
334 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
335 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
336 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000337
Anders Carlsson5da84842009-09-01 04:26:58 +0000338 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
339}
340
Douglas Gregor832940b2010-03-02 23:58:15 +0000341ASTContext::overridden_cxx_method_iterator
342ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
343 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
344 = OverriddenMethods.find(Method);
345 if (Pos == OverriddenMethods.end())
346 return 0;
347
348 return Pos->second.begin();
349}
350
351ASTContext::overridden_cxx_method_iterator
352ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
353 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
354 = OverriddenMethods.find(Method);
355 if (Pos == OverriddenMethods.end())
356 return 0;
357
358 return Pos->second.end();
359}
360
361void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
362 const CXXMethodDecl *Overridden) {
363 OverriddenMethods[Method].push_back(Overridden);
364}
365
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000366namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000367 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000368 : std::binary_function<SourceRange, SourceRange, bool> {
369 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000371 public:
372 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000373
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000374 bool operator()(SourceRange X, SourceRange Y) {
375 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
376 }
377 };
378}
379
Chris Lattner53cfe802007-07-18 17:52:12 +0000380//===----------------------------------------------------------------------===//
381// Type Sizing and Analysis
382//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000383
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000384/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
385/// scalar floating point type.
386const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000387 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000388 assert(BT && "Not a floating point type!");
389 switch (BT->getKind()) {
390 default: assert(0 && "Not a floating point type!");
391 case BuiltinType::Float: return Target.getFloatFormat();
392 case BuiltinType::Double: return Target.getDoubleFormat();
393 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
394 }
395}
396
Ken Dyck160146e2010-01-27 17:10:57 +0000397/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000398/// specified decl. Note that bitfields do not have a valid alignment, so
399/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000400/// If @p RefAsPointee, references are treated like their underlying type
401/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000402CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000403 unsigned Align = Target.getCharWidth();
404
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000405 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000406 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000407
Chris Lattner68061312009-01-24 21:53:27 +0000408 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
409 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000410 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000411 if (RefAsPointee)
412 T = RT->getPointeeType();
413 else
414 T = getPointerType(RT->getPointeeType());
415 }
416 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000417 unsigned MinWidth = Target.getLargeArrayMinWidth();
418 unsigned ArrayAlign = Target.getLargeArrayAlign();
419 if (isa<VariableArrayType>(T) && MinWidth != 0)
420 Align = std::max(Align, ArrayAlign);
421 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
422 unsigned Size = getTypeSize(CT);
423 if (MinWidth != 0 && MinWidth <= Size)
424 Align = std::max(Align, ArrayAlign);
425 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000426 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000427 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
428 T = cast<ArrayType>(T)->getElementType();
429
430 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
431 }
Charles Davis3fc51072010-02-23 04:52:00 +0000432 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
433 // In the case of a field in a packed struct, we want the minimum
434 // of the alignment of the field and the alignment of the struct.
435 Align = std::min(Align,
436 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
437 }
Chris Lattner68061312009-01-24 21:53:27 +0000438 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000439
Ken Dyck160146e2010-01-27 17:10:57 +0000440 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000441}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000442
John McCall87fe5d52010-05-20 01:18:31 +0000443std::pair<CharUnits, CharUnits>
444ASTContext::getTypeInfoInChars(const Type *T) {
445 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
446 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
447 CharUnits::fromQuantity(Info.second / getCharWidth()));
448}
449
450std::pair<CharUnits, CharUnits>
451ASTContext::getTypeInfoInChars(QualType T) {
452 return getTypeInfoInChars(T.getTypePtr());
453}
454
Chris Lattner983a8bb2007-07-13 22:13:22 +0000455/// getTypeSize - Return the size of the specified type, in bits. This method
456/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000457///
458/// FIXME: Pointers into different addr spaces could have different sizes and
459/// alignment requirements: getPointerInfo should take an AddrSpace, this
460/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000461std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000462ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000463 uint64_t Width=0;
464 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000465 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000466#define TYPE(Class, Base)
467#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000468#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000469#define DEPENDENT_TYPE(Class, Base) case Type::Class:
470#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000471 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000472 break;
473
Chris Lattner355332d2007-07-13 22:27:08 +0000474 case Type::FunctionNoProto:
475 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000476 // GCC extension: alignof(function) = 32 bits
477 Width = 0;
478 Align = 32;
479 break;
480
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000481 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000482 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000483 Width = 0;
484 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
485 break;
486
Steve Naroff5c131802007-08-30 01:06:46 +0000487 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000488 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000489
Chris Lattner37e05872008-03-05 18:54:05 +0000490 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000491 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000492 Align = EltInfo.second;
493 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000494 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000495 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000496 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000497 const VectorType *VT = cast<VectorType>(T);
498 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
499 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000500 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000501 // If the alignment is not a power of 2, round up to the next power of 2.
502 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000503 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000504 Align = llvm::NextPowerOf2(Align);
505 Width = llvm::RoundUpToAlignment(Width, Align);
506 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000507 break;
508 }
Chris Lattner647fb222007-07-18 18:26:58 +0000509
Chris Lattner7570e9c2008-03-08 08:52:55 +0000510 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000511 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000512 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000513 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000514 // GCC extension: alignof(void) = 8 bits.
515 Width = 0;
516 Align = 8;
517 break;
518
Chris Lattner6a4f7452007-12-19 19:23:28 +0000519 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000520 Width = Target.getBoolWidth();
521 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000522 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000523 case BuiltinType::Char_S:
524 case BuiltinType::Char_U:
525 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000526 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000527 Width = Target.getCharWidth();
528 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000529 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000530 case BuiltinType::WChar:
531 Width = Target.getWCharWidth();
532 Align = Target.getWCharAlign();
533 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000534 case BuiltinType::Char16:
535 Width = Target.getChar16Width();
536 Align = Target.getChar16Align();
537 break;
538 case BuiltinType::Char32:
539 Width = Target.getChar32Width();
540 Align = Target.getChar32Align();
541 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000542 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000543 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000544 Width = Target.getShortWidth();
545 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000546 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000547 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000548 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000549 Width = Target.getIntWidth();
550 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000551 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000552 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000553 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000554 Width = Target.getLongWidth();
555 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000556 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000557 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000558 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000559 Width = Target.getLongLongWidth();
560 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000561 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000562 case BuiltinType::Int128:
563 case BuiltinType::UInt128:
564 Width = 128;
565 Align = 128; // int128_t is 128-bit aligned on all targets.
566 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000567 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000568 Width = Target.getFloatWidth();
569 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000570 break;
571 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000572 Width = Target.getDoubleWidth();
573 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000574 break;
575 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000576 Width = Target.getLongDoubleWidth();
577 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000578 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000579 case BuiltinType::NullPtr:
580 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
581 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000582 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000583 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000584 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000585 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000586 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000587 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000588 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000589 case Type::BlockPointer: {
590 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
591 Width = Target.getPointerWidth(AS);
592 Align = Target.getPointerAlign(AS);
593 break;
594 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000595 case Type::LValueReference:
596 case Type::RValueReference: {
597 // alignof and sizeof should never enter this code path here, so we go
598 // the pointer route.
599 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
600 Width = Target.getPointerWidth(AS);
601 Align = Target.getPointerAlign(AS);
602 break;
603 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000604 case Type::Pointer: {
605 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000606 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000607 Align = Target.getPointerAlign(AS);
608 break;
609 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000610 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000611 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000612 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000613 getTypeInfo(getPointerDiffType());
614 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000615 if (Pointee->isFunctionType())
616 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000617 Align = PtrDiffInfo.second;
618 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000619 }
Chris Lattner647fb222007-07-18 18:26:58 +0000620 case Type::Complex: {
621 // Complex types have the same alignment as their elements, but twice the
622 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000623 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000624 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000625 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000626 Align = EltInfo.second;
627 break;
628 }
John McCall8b07ec22010-05-15 11:32:37 +0000629 case Type::ObjCObject:
630 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000631 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000632 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000633 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
634 Width = Layout.getSize();
635 Align = Layout.getAlignment();
636 break;
637 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000638 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000639 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000640 const TagType *TT = cast<TagType>(T);
641
642 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000643 Width = 1;
644 Align = 1;
645 break;
646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000648 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000649 return getTypeInfo(ET->getDecl()->getIntegerType());
650
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000651 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000652 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
653 Width = Layout.getSize();
654 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000655 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000656 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000657
Chris Lattner63d2b362009-10-22 05:17:15 +0000658 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000659 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
660 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000661
Douglas Gregoref462e62009-04-30 17:32:17 +0000662 case Type::Typedef: {
663 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000664 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000665 Align = std::max(Aligned->getMaxAlignment(),
666 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000667 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
668 } else
669 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000670 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000671 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000672
673 case Type::TypeOfExpr:
674 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
675 .getTypePtr());
676
677 case Type::TypeOf:
678 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
679
Anders Carlsson81df7b82009-06-24 19:06:50 +0000680 case Type::Decltype:
681 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
682 .getTypePtr());
683
Abramo Bagnara6150c882010-05-11 21:36:43 +0000684 case Type::Elaborated:
685 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000686
Douglas Gregoref462e62009-04-30 17:32:17 +0000687 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000688 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000689 "Cannot request the size of a dependent type");
690 // FIXME: this is likely to be wrong once we support template
691 // aliases, since a template alias could refer to a typedef that
692 // has an __aligned__ attribute on it.
693 return getTypeInfo(getCanonicalType(T));
694 }
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner53cfe802007-07-18 17:52:12 +0000696 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000697 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000698}
699
Ken Dyck8c89d592009-12-22 14:23:30 +0000700/// getTypeSizeInChars - Return the size of the specified type, in characters.
701/// This method does not work on incomplete types.
702CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000703 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000704}
705CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000706 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000707}
708
Ken Dycka6046ab2010-01-26 17:25:18 +0000709/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000710/// characters. This method does not work on incomplete types.
711CharUnits ASTContext::getTypeAlignInChars(QualType T) {
712 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
713}
714CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
715 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
716}
717
Chris Lattnera3402cd2009-01-27 18:08:34 +0000718/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
719/// type for the current target in bits. This can be different than the ABI
720/// alignment in cases where it is beneficial for performance to overalign
721/// a data type.
722unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
723 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000724
725 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000726 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000727 T = CT->getElementType().getTypePtr();
728 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
729 T->isSpecificBuiltinType(BuiltinType::LongLong))
730 return std::max(ABIAlign, (unsigned)getTypeSize(T));
731
Chris Lattnera3402cd2009-01-27 18:08:34 +0000732 return ABIAlign;
733}
734
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000735static void CollectLocalObjCIvars(ASTContext *Ctx,
736 const ObjCInterfaceDecl *OI,
737 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000738 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
739 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000740 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000741 if (!IVDecl->isInvalidDecl())
742 Fields.push_back(cast<FieldDecl>(IVDecl));
743 }
744}
745
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000746void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
747 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
748 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
749 CollectObjCIvars(SuperClass, Fields);
750 CollectLocalObjCIvars(this, OI, Fields);
751}
752
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000753/// ShallowCollectObjCIvars -
754/// Collect all ivars, including those synthesized, in the current class.
755///
756void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000757 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000758 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
759 E = OI->ivar_end(); I != E; ++I) {
760 Ivars.push_back(*I);
761 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000762
763 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000764}
765
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000766/// CollectNonClassIvars -
767/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000768/// This includes synthesized ivars (via @synthesize) and those in
769// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000770///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000771void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000772 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000773 // Find ivars declared in class extension.
774 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
775 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
776 E = CDecl->ivar_end(); I != E; ++I) {
777 Ivars.push_back(*I);
778 }
779 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000780
Ted Kremenek86838aa2010-03-11 19:44:54 +0000781 // Also add any ivar defined in this class's implementation. This
782 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000783 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
784 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
785 E = ImplDecl->ivar_end(); I != E; ++I)
786 Ivars.push_back(*I);
787 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000788}
789
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000790/// CollectInheritedProtocols - Collect all protocols in current class and
791/// those inherited by it.
792void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000793 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000794 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
795 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
796 PE = OI->protocol_end(); P != PE; ++P) {
797 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000798 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000799 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000800 PE = Proto->protocol_end(); P != PE; ++P) {
801 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000802 CollectInheritedProtocols(*P, Protocols);
803 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000804 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000805
806 // Categories of this Interface.
807 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
808 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
809 CollectInheritedProtocols(CDeclChain, Protocols);
810 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
811 while (SD) {
812 CollectInheritedProtocols(SD, Protocols);
813 SD = SD->getSuperClass();
814 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000815 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000816 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
817 PE = OC->protocol_end(); P != PE; ++P) {
818 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000819 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000820 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
821 PE = Proto->protocol_end(); P != PE; ++P)
822 CollectInheritedProtocols(*P, Protocols);
823 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000824 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000825 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
826 PE = OP->protocol_end(); P != PE; ++P) {
827 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000828 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000829 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
830 PE = Proto->protocol_end(); P != PE; ++P)
831 CollectInheritedProtocols(*P, Protocols);
832 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000833 }
834}
835
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000836unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
837 unsigned count = 0;
838 // Count ivars declared in class extension.
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000839 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension())
840 count += CDecl->ivar_size();
841
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000842 // Count ivar defined in this class's implementation. This
843 // includes synthesized ivars.
844 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000845 count += ImplDecl->ivar_size();
846
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000847 return count;
848}
849
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000850/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
851ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
852 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
853 I = ObjCImpls.find(D);
854 if (I != ObjCImpls.end())
855 return cast<ObjCImplementationDecl>(I->second);
856 return 0;
857}
858/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
859ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
860 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
861 I = ObjCImpls.find(D);
862 if (I != ObjCImpls.end())
863 return cast<ObjCCategoryImplDecl>(I->second);
864 return 0;
865}
866
867/// \brief Set the implementation of ObjCInterfaceDecl.
868void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
869 ObjCImplementationDecl *ImplD) {
870 assert(IFaceD && ImplD && "Passed null params");
871 ObjCImpls[IFaceD] = ImplD;
872}
873/// \brief Set the implementation of ObjCCategoryDecl.
874void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
875 ObjCCategoryImplDecl *ImplD) {
876 assert(CatD && ImplD && "Passed null params");
877 ObjCImpls[CatD] = ImplD;
878}
879
John McCallbcd03502009-12-07 02:54:59 +0000880/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000881///
John McCallbcd03502009-12-07 02:54:59 +0000882/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000883/// the TypeLoc wrappers.
884///
885/// \param T the type that will be the basis for type source info. This type
886/// should refer to how the declarator was written in source code, not to
887/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000888TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000889 unsigned DataSize) {
890 if (!DataSize)
891 DataSize = TypeLoc::getFullDataSizeForType(T);
892 else
893 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000894 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000895
John McCallbcd03502009-12-07 02:54:59 +0000896 TypeSourceInfo *TInfo =
897 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
898 new (TInfo) TypeSourceInfo(T);
899 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000900}
901
John McCallbcd03502009-12-07 02:54:59 +0000902TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +0000903 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +0000904 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +0000905 DI->getTypeLoc().initialize(L);
906 return DI;
907}
908
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000909const ASTRecordLayout &
910ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
911 return getObjCLayout(D, 0);
912}
913
914const ASTRecordLayout &
915ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
916 return getObjCLayout(D->getClassInterface(), D);
917}
918
Chris Lattner983a8bb2007-07-13 22:13:22 +0000919//===----------------------------------------------------------------------===//
920// Type creation/memoization methods
921//===----------------------------------------------------------------------===//
922
John McCall8ccfcb52009-09-24 19:53:00 +0000923QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
924 unsigned Fast = Quals.getFastQualifiers();
925 Quals.removeFastQualifiers();
926
927 // Check if we've already instantiated this type.
928 llvm::FoldingSetNodeID ID;
929 ExtQuals::Profile(ID, TypeNode, Quals);
930 void *InsertPos = 0;
931 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
932 assert(EQ->getQualifiers() == Quals);
933 QualType T = QualType(EQ, Fast);
934 return T;
935 }
936
John McCall90d1c2d2009-09-24 23:30:46 +0000937 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +0000938 ExtQualNodes.InsertNode(New, InsertPos);
939 QualType T = QualType(New, Fast);
940 return T;
941}
942
943QualType ASTContext::getVolatileType(QualType T) {
944 QualType CanT = getCanonicalType(T);
945 if (CanT.isVolatileQualified()) return T;
946
947 QualifierCollector Quals;
948 const Type *TypeNode = Quals.strip(T);
949 Quals.addVolatile();
950
951 return getExtQualType(TypeNode, Quals);
952}
953
Fariborz Jahanianece85822009-02-17 18:27:45 +0000954QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +0000955 QualType CanT = getCanonicalType(T);
956 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +0000957 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +0000958
John McCall8ccfcb52009-09-24 19:53:00 +0000959 // If we are composing extended qualifiers together, merge together
960 // into one ExtQuals node.
961 QualifierCollector Quals;
962 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +0000963
John McCall8ccfcb52009-09-24 19:53:00 +0000964 // If this type already has an address space specified, it cannot get
965 // another one.
966 assert(!Quals.hasAddressSpace() &&
967 "Type cannot be in multiple addr spaces!");
968 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +0000969
John McCall8ccfcb52009-09-24 19:53:00 +0000970 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +0000971}
972
Chris Lattnerd60183d2009-02-18 22:53:11 +0000973QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +0000974 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +0000975 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +0000976 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +0000977 return T;
Mike Stump11289f42009-09-09 15:08:12 +0000978
Fariborz Jahanianb68215c2009-06-03 17:15:17 +0000979 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000980 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +0000981 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +0000982 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
983 return getPointerType(ResultType);
984 }
985 }
Mike Stump11289f42009-09-09 15:08:12 +0000986
John McCall8ccfcb52009-09-24 19:53:00 +0000987 // If we are composing extended qualifiers together, merge together
988 // into one ExtQuals node.
989 QualifierCollector Quals;
990 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +0000991
John McCall8ccfcb52009-09-24 19:53:00 +0000992 // If this type already has an ObjCGC specified, it cannot get
993 // another one.
994 assert(!Quals.hasObjCGCAttr() &&
995 "Type cannot have multiple ObjCGCs!");
996 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +0000997
John McCall8ccfcb52009-09-24 19:53:00 +0000998 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +0000999}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001000
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001001static QualType getExtFunctionType(ASTContext& Context, QualType T,
1002 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001003 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001004 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1005 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001006 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001007 if (ResultType == Pointee)
1008 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001009
1010 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001011 } else if (const BlockPointerType *BlockPointer
1012 = T->getAs<BlockPointerType>()) {
1013 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001014 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001015 if (ResultType == Pointee)
1016 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001017
1018 ResultType = Context.getBlockPointerType(ResultType);
1019 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001020 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001021 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001022
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001023 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001024 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001025 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001026 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001027 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001028 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001029 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1030 FPT->getNumArgs(), FPT->isVariadic(),
1031 FPT->getTypeQuals(),
1032 FPT->hasExceptionSpec(),
1033 FPT->hasAnyExceptionSpec(),
1034 FPT->getNumExceptions(),
1035 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001036 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001037 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001038 } else
1039 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001040
1041 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1042}
1043
1044QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001045 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001046 return getExtFunctionType(*this, T,
1047 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001048}
1049
1050QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001051 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001052 return getExtFunctionType(*this, T,
1053 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001054}
1055
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001056QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1057 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1058 return getExtFunctionType(*this, T,
1059 Info.withRegParm(RegParm));
1060}
1061
Chris Lattnerc6395932007-06-22 20:56:16 +00001062/// getComplexType - Return the uniqued reference to the type for a complex
1063/// number with the specified element type.
1064QualType ASTContext::getComplexType(QualType T) {
1065 // Unique pointers, to guarantee there is only one pointer of a particular
1066 // structure.
1067 llvm::FoldingSetNodeID ID;
1068 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattnerc6395932007-06-22 20:56:16 +00001070 void *InsertPos = 0;
1071 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1072 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattnerc6395932007-06-22 20:56:16 +00001074 // If the pointee type isn't canonical, this won't be a canonical type either,
1075 // so fill in the canonical type field.
1076 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001077 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001078 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattnerc6395932007-06-22 20:56:16 +00001080 // Get the new insert position for the node we care about.
1081 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001082 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001083 }
John McCall90d1c2d2009-09-24 23:30:46 +00001084 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001085 Types.push_back(New);
1086 ComplexTypes.InsertNode(New, InsertPos);
1087 return QualType(New, 0);
1088}
1089
Chris Lattner970e54e2006-11-12 00:37:36 +00001090/// getPointerType - Return the uniqued reference to the type for a pointer to
1091/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001092QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001093 // Unique pointers, to guarantee there is only one pointer of a particular
1094 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001095 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001096 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001097
Chris Lattner67521df2007-01-27 01:29:36 +00001098 void *InsertPos = 0;
1099 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001100 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner7ccecb92006-11-12 08:50:50 +00001102 // If the pointee type isn't canonical, this won't be a canonical type either,
1103 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001104 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001105 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001106 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattner67521df2007-01-27 01:29:36 +00001108 // Get the new insert position for the node we care about.
1109 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001110 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001111 }
John McCall90d1c2d2009-09-24 23:30:46 +00001112 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001113 Types.push_back(New);
1114 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001115 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001116}
1117
Mike Stump11289f42009-09-09 15:08:12 +00001118/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001119/// a pointer to the specified block.
1120QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001121 assert(T->isFunctionType() && "block of function types only");
1122 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001123 // structure.
1124 llvm::FoldingSetNodeID ID;
1125 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001126
Steve Naroffec33ed92008-08-27 16:04:49 +00001127 void *InsertPos = 0;
1128 if (BlockPointerType *PT =
1129 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1130 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001131
1132 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001133 // type either so fill in the canonical type field.
1134 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001135 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001136 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001137
Steve Naroffec33ed92008-08-27 16:04:49 +00001138 // Get the new insert position for the node we care about.
1139 BlockPointerType *NewIP =
1140 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001141 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001142 }
John McCall90d1c2d2009-09-24 23:30:46 +00001143 BlockPointerType *New
1144 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001145 Types.push_back(New);
1146 BlockPointerTypes.InsertNode(New, InsertPos);
1147 return QualType(New, 0);
1148}
1149
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001150/// getLValueReferenceType - Return the uniqued reference to the type for an
1151/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001152QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001153 // Unique pointers, to guarantee there is only one pointer of a particular
1154 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001155 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001156 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001157
1158 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001159 if (LValueReferenceType *RT =
1160 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001161 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001162
John McCallfc93cf92009-10-22 22:37:11 +00001163 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1164
Bill Wendling3708c182007-05-27 10:15:43 +00001165 // If the referencee type isn't canonical, this won't be a canonical type
1166 // either, so fill in the canonical type field.
1167 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001168 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1169 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1170 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001171
Bill Wendling3708c182007-05-27 10:15:43 +00001172 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001173 LValueReferenceType *NewIP =
1174 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001175 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001176 }
1177
John McCall90d1c2d2009-09-24 23:30:46 +00001178 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001179 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1180 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001181 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001182 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001183
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001184 return QualType(New, 0);
1185}
1186
1187/// getRValueReferenceType - Return the uniqued reference to the type for an
1188/// rvalue reference to the specified type.
1189QualType ASTContext::getRValueReferenceType(QualType T) {
1190 // Unique pointers, to guarantee there is only one pointer of a particular
1191 // structure.
1192 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001193 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001194
1195 void *InsertPos = 0;
1196 if (RValueReferenceType *RT =
1197 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1198 return QualType(RT, 0);
1199
John McCallfc93cf92009-10-22 22:37:11 +00001200 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1201
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001202 // If the referencee type isn't canonical, this won't be a canonical type
1203 // either, so fill in the canonical type field.
1204 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001205 if (InnerRef || !T.isCanonical()) {
1206 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1207 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001208
1209 // Get the new insert position for the node we care about.
1210 RValueReferenceType *NewIP =
1211 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1212 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1213 }
1214
John McCall90d1c2d2009-09-24 23:30:46 +00001215 RValueReferenceType *New
1216 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001217 Types.push_back(New);
1218 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001219 return QualType(New, 0);
1220}
1221
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001222/// getMemberPointerType - Return the uniqued reference to the type for a
1223/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001224QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001225 // Unique pointers, to guarantee there is only one pointer of a particular
1226 // structure.
1227 llvm::FoldingSetNodeID ID;
1228 MemberPointerType::Profile(ID, T, Cls);
1229
1230 void *InsertPos = 0;
1231 if (MemberPointerType *PT =
1232 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1233 return QualType(PT, 0);
1234
1235 // If the pointee or class type isn't canonical, this won't be a canonical
1236 // type either, so fill in the canonical type field.
1237 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001238 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001239 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1240
1241 // Get the new insert position for the node we care about.
1242 MemberPointerType *NewIP =
1243 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1244 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1245 }
John McCall90d1c2d2009-09-24 23:30:46 +00001246 MemberPointerType *New
1247 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001248 Types.push_back(New);
1249 MemberPointerTypes.InsertNode(New, InsertPos);
1250 return QualType(New, 0);
1251}
1252
Mike Stump11289f42009-09-09 15:08:12 +00001253/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001254/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001255QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001256 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001257 ArrayType::ArraySizeModifier ASM,
1258 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001259 assert((EltTy->isDependentType() ||
1260 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001261 "Constant array of VLAs is illegal!");
1262
Chris Lattnere2df3f92009-05-13 04:12:56 +00001263 // Convert the array size into a canonical width matching the pointer size for
1264 // the target.
1265 llvm::APInt ArySize(ArySizeIn);
1266 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001267
Chris Lattner23b7eb62007-06-15 23:05:46 +00001268 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001269 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001270
Chris Lattner36f8e652007-01-27 08:31:04 +00001271 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001272 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001273 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001274 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattner7ccecb92006-11-12 08:50:50 +00001276 // If the element type isn't canonical, this won't be a canonical type either,
1277 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001278 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001279 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001280 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001281 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001282 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001283 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001284 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001285 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
John McCall90d1c2d2009-09-24 23:30:46 +00001288 ConstantArrayType *New = new(*this,TypeAlignment)
1289 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001290 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001291 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001292 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001293}
1294
Steve Naroffcadebd02007-08-30 18:14:25 +00001295/// getVariableArrayType - Returns a non-unique reference to the type for a
1296/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001297QualType ASTContext::getVariableArrayType(QualType EltTy,
1298 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001299 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001300 unsigned EltTypeQuals,
1301 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001302 // Since we don't unique expressions, it isn't possible to unique VLA's
1303 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001304 QualType CanonType;
1305
1306 if (!EltTy.isCanonical()) {
1307 if (NumElts)
1308 NumElts->Retain();
1309 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1310 EltTypeQuals, Brackets);
1311 }
1312
John McCall90d1c2d2009-09-24 23:30:46 +00001313 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001314 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001315
1316 VariableArrayTypes.push_back(New);
1317 Types.push_back(New);
1318 return QualType(New, 0);
1319}
1320
Douglas Gregor4619e432008-12-05 23:32:09 +00001321/// getDependentSizedArrayType - Returns a non-unique reference to
1322/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001323/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001324QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1325 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001326 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001327 unsigned EltTypeQuals,
1328 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001329 assert((!NumElts || NumElts->isTypeDependent() ||
1330 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001331 "Size must be type- or value-dependent!");
1332
Douglas Gregorf3f95522009-07-31 00:23:35 +00001333 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001334 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001335 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001336
1337 if (NumElts) {
1338 // Dependently-sized array types that do not have a specified
1339 // number of elements will have their sizes deduced from an
1340 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001341 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1342 EltTypeQuals, NumElts);
1343
1344 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1345 }
1346
Douglas Gregorf3f95522009-07-31 00:23:35 +00001347 DependentSizedArrayType *New;
1348 if (Canon) {
1349 // We already have a canonical version of this array type; use it as
1350 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001351 New = new (*this, TypeAlignment)
1352 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1353 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001354 } else {
1355 QualType CanonEltTy = getCanonicalType(EltTy);
1356 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001357 New = new (*this, TypeAlignment)
1358 DependentSizedArrayType(*this, EltTy, QualType(),
1359 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001360
Douglas Gregorc42075a2010-02-04 18:10:26 +00001361 if (NumElts) {
1362 DependentSizedArrayType *CanonCheck
1363 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1364 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1365 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001366 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001367 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001368 } else {
1369 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1370 ASM, EltTypeQuals,
1371 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001372 New = new (*this, TypeAlignment)
1373 DependentSizedArrayType(*this, EltTy, Canon,
1374 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001375 }
1376 }
Mike Stump11289f42009-09-09 15:08:12 +00001377
Douglas Gregor4619e432008-12-05 23:32:09 +00001378 Types.push_back(New);
1379 return QualType(New, 0);
1380}
1381
Eli Friedmanbd258282008-02-15 18:16:39 +00001382QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1383 ArrayType::ArraySizeModifier ASM,
1384 unsigned EltTypeQuals) {
1385 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001386 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001387
1388 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001390 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1391 return QualType(ATP, 0);
1392
1393 // If the element type isn't canonical, this won't be a canonical type
1394 // either, so fill in the canonical type field.
1395 QualType Canonical;
1396
John McCallb692a092009-10-22 20:10:53 +00001397 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001398 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001399 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001400
1401 // Get the new insert position for the node we care about.
1402 IncompleteArrayType *NewIP =
1403 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001404 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001405 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001406
John McCall90d1c2d2009-09-24 23:30:46 +00001407 IncompleteArrayType *New = new (*this, TypeAlignment)
1408 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001409
1410 IncompleteArrayTypes.InsertNode(New, InsertPos);
1411 Types.push_back(New);
1412 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001413}
1414
Steve Naroff91fcddb2007-07-18 18:00:27 +00001415/// getVectorType - Return the unique reference to a vector type of
1416/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001417QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1418 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001419 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001420
Chris Lattner76a00cf2008-04-06 22:59:24 +00001421 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001422 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001423
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001424 // Check if we've already instantiated a vector of this type.
1425 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001426 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1427 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001428 void *InsertPos = 0;
1429 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1430 return QualType(VTP, 0);
1431
1432 // If the element type isn't canonical, this won't be a canonical type either,
1433 // so fill in the canonical type field.
1434 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001435 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1436 Canonical = getVectorType(getCanonicalType(vecType),
1437 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001438
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001439 // Get the new insert position for the node we care about.
1440 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001441 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001442 }
John McCall90d1c2d2009-09-24 23:30:46 +00001443 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001444 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001445 VectorTypes.InsertNode(New, InsertPos);
1446 Types.push_back(New);
1447 return QualType(New, 0);
1448}
1449
Nate Begemance4d7fc2008-04-18 23:10:10 +00001450/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001451/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001452QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001453 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Chris Lattner76a00cf2008-04-06 22:59:24 +00001455 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001456 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001457
Steve Naroff91fcddb2007-07-18 18:00:27 +00001458 // Check if we've already instantiated a vector of this type.
1459 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001460 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001461 void *InsertPos = 0;
1462 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1463 return QualType(VTP, 0);
1464
1465 // If the element type isn't canonical, this won't be a canonical type either,
1466 // so fill in the canonical type field.
1467 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001468 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001469 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Steve Naroff91fcddb2007-07-18 18:00:27 +00001471 // Get the new insert position for the node we care about.
1472 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001473 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001474 }
John McCall90d1c2d2009-09-24 23:30:46 +00001475 ExtVectorType *New = new (*this, TypeAlignment)
1476 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001477 VectorTypes.InsertNode(New, InsertPos);
1478 Types.push_back(New);
1479 return QualType(New, 0);
1480}
1481
Mike Stump11289f42009-09-09 15:08:12 +00001482QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001483 Expr *SizeExpr,
1484 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001485 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001486 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001487 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Douglas Gregor352169a2009-07-31 03:54:25 +00001489 void *InsertPos = 0;
1490 DependentSizedExtVectorType *Canon
1491 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1492 DependentSizedExtVectorType *New;
1493 if (Canon) {
1494 // We already have a canonical version of this array type; use it as
1495 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001496 New = new (*this, TypeAlignment)
1497 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1498 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001499 } else {
1500 QualType CanonVecTy = getCanonicalType(vecType);
1501 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001502 New = new (*this, TypeAlignment)
1503 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1504 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001505
1506 DependentSizedExtVectorType *CanonCheck
1507 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1508 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1509 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001510 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1511 } else {
1512 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1513 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001514 New = new (*this, TypeAlignment)
1515 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001516 }
1517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
Douglas Gregor758a8692009-06-17 21:51:59 +00001519 Types.push_back(New);
1520 return QualType(New, 0);
1521}
1522
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001523/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001524///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001525QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1526 const FunctionType::ExtInfo &Info) {
1527 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001528 // Unique functions, to guarantee there is only one function of a particular
1529 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001530 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001531 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Chris Lattner47955de2007-01-27 08:37:20 +00001533 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001534 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001535 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001536 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001538 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001539 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001540 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001541 Canonical =
1542 getFunctionNoProtoType(getCanonicalType(ResultTy),
1543 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattner47955de2007-01-27 08:37:20 +00001545 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001546 FunctionNoProtoType *NewIP =
1547 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001548 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
John McCall90d1c2d2009-09-24 23:30:46 +00001551 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001552 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001553 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001554 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001555 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001556}
1557
1558/// getFunctionType - Return a normal function type with a typed argument
1559/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001560QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001561 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001562 unsigned TypeQuals, bool hasExceptionSpec,
1563 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001564 const QualType *ExArray,
1565 const FunctionType::ExtInfo &Info) {
1566 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001567 // Unique functions, to guarantee there is only one function of a particular
1568 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001569 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001570 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001571 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001572 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001573
1574 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001575 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001576 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001577 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001578
1579 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001580 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001581 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001582 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001583 isCanonical = false;
1584
1585 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001586 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001587 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001588 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001589 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001590 CanonicalArgs.reserve(NumArgs);
1591 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001592 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001593
Chris Lattner76a00cf2008-04-06 22:59:24 +00001594 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001595 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001596 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001597 false, 0, 0,
1598 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001599
Chris Lattnerfd4de792007-01-27 01:15:32 +00001600 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001601 FunctionProtoType *NewIP =
1602 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001603 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001604 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001605
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001606 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001607 // for two variable size arrays (for parameter and exception types) at the
1608 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001609 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001610 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1611 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001612 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001613 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001614 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001615 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001616 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001617 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001618 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001619}
Chris Lattneref51c202006-11-10 07:17:23 +00001620
John McCalle78aac42010-03-10 03:28:59 +00001621#ifndef NDEBUG
1622static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1623 if (!isa<CXXRecordDecl>(D)) return false;
1624 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1625 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1626 return true;
1627 if (RD->getDescribedClassTemplate() &&
1628 !isa<ClassTemplateSpecializationDecl>(RD))
1629 return true;
1630 return false;
1631}
1632#endif
1633
1634/// getInjectedClassNameType - Return the unique reference to the
1635/// injected class name type for the specified templated declaration.
1636QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1637 QualType TST) {
1638 assert(NeedsInjectedClassNameType(Decl));
1639 if (Decl->TypeForDecl) {
1640 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1641 } else if (CXXRecordDecl *PrevDecl
1642 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1643 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1644 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1645 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1646 } else {
John McCall2408e322010-04-27 00:57:59 +00001647 Decl->TypeForDecl =
1648 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001649 Types.push_back(Decl->TypeForDecl);
1650 }
1651 return QualType(Decl->TypeForDecl, 0);
1652}
1653
Douglas Gregor83a586e2008-04-13 21:07:44 +00001654/// getTypeDeclType - Return the unique reference to the type for the
1655/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001656QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001657 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001658 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001659
John McCall81e38502010-02-16 03:57:14 +00001660 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001661 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001662
John McCall96f0b5f2010-03-10 06:48:02 +00001663 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1664 "Template type parameter types are always available.");
1665
John McCall81e38502010-02-16 03:57:14 +00001666 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001667 assert(!Record->getPreviousDeclaration() &&
1668 "struct/union has previous declaration");
1669 assert(!NeedsInjectedClassNameType(Record));
1670 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001671 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001672 assert(!Enum->getPreviousDeclaration() &&
1673 "enum has previous declaration");
1674 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001675 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001676 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1677 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001678 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001679 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001680
John McCall96f0b5f2010-03-10 06:48:02 +00001681 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001682 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001683}
1684
Chris Lattner32d920b2007-01-26 02:01:53 +00001685/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001686/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001687QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001688 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001689
Chris Lattner76a00cf2008-04-06 22:59:24 +00001690 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001691 Decl->TypeForDecl = new(*this, TypeAlignment)
1692 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001693 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001694 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001695}
1696
John McCallcebee162009-10-18 09:09:24 +00001697/// \brief Retrieve a substitution-result type.
1698QualType
1699ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1700 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001701 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001702 && "replacement types must always be canonical");
1703
1704 llvm::FoldingSetNodeID ID;
1705 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1706 void *InsertPos = 0;
1707 SubstTemplateTypeParmType *SubstParm
1708 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1709
1710 if (!SubstParm) {
1711 SubstParm = new (*this, TypeAlignment)
1712 SubstTemplateTypeParmType(Parm, Replacement);
1713 Types.push_back(SubstParm);
1714 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1715 }
1716
1717 return QualType(SubstParm, 0);
1718}
1719
Douglas Gregoreff93e02009-02-05 23:33:38 +00001720/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001721/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001722/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001723QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001724 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00001725 IdentifierInfo *Name) {
1726 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001727 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001728 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001729 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001730 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1731
1732 if (TypeParm)
1733 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001734
Anders Carlsson90036dc2009-06-16 00:30:48 +00001735 if (Name) {
1736 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00001737 TypeParm = new (*this, TypeAlignment)
1738 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001739
1740 TemplateTypeParmType *TypeCheck
1741 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1742 assert(!TypeCheck && "Template type parameter canonical type broken");
1743 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001744 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001745 TypeParm = new (*this, TypeAlignment)
1746 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001747
1748 Types.push_back(TypeParm);
1749 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1750
1751 return QualType(TypeParm, 0);
1752}
1753
John McCalle78aac42010-03-10 03:28:59 +00001754TypeSourceInfo *
1755ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1756 SourceLocation NameLoc,
1757 const TemplateArgumentListInfo &Args,
1758 QualType CanonType) {
1759 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1760
1761 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1762 TemplateSpecializationTypeLoc TL
1763 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1764 TL.setTemplateNameLoc(NameLoc);
1765 TL.setLAngleLoc(Args.getLAngleLoc());
1766 TL.setRAngleLoc(Args.getRAngleLoc());
1767 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1768 TL.setArgLocInfo(i, Args[i].getLocInfo());
1769 return DI;
1770}
1771
Mike Stump11289f42009-09-09 15:08:12 +00001772QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001773ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001774 const TemplateArgumentListInfo &Args,
John McCall2408e322010-04-27 00:57:59 +00001775 QualType Canon,
1776 bool IsCurrentInstantiation) {
John McCall6b51f282009-11-23 01:53:49 +00001777 unsigned NumArgs = Args.size();
1778
John McCall0ad16662009-10-29 08:12:44 +00001779 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1780 ArgVec.reserve(NumArgs);
1781 for (unsigned i = 0; i != NumArgs; ++i)
1782 ArgVec.push_back(Args[i].getArgument());
1783
John McCall2408e322010-04-27 00:57:59 +00001784 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1785 Canon, IsCurrentInstantiation);
John McCall0ad16662009-10-29 08:12:44 +00001786}
1787
1788QualType
1789ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001790 const TemplateArgument *Args,
1791 unsigned NumArgs,
John McCall2408e322010-04-27 00:57:59 +00001792 QualType Canon,
1793 bool IsCurrentInstantiation) {
Douglas Gregor15301382009-07-30 17:40:51 +00001794 if (!Canon.isNull())
1795 Canon = getCanonicalType(Canon);
1796 else {
John McCall2408e322010-04-27 00:57:59 +00001797 assert(!IsCurrentInstantiation &&
1798 "current-instantiation specializations should always "
1799 "have a canonical type");
1800
Douglas Gregor15301382009-07-30 17:40:51 +00001801 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001802 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1803 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1804 CanonArgs.reserve(NumArgs);
1805 for (unsigned I = 0; I != NumArgs; ++I)
1806 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1807
1808 // Determine whether this canonical template specialization type already
1809 // exists.
1810 llvm::FoldingSetNodeID ID;
John McCall2408e322010-04-27 00:57:59 +00001811 TemplateSpecializationType::Profile(ID, CanonTemplate, false,
Douglas Gregor00044172009-07-29 16:09:57 +00001812 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001813
1814 void *InsertPos = 0;
1815 TemplateSpecializationType *Spec
1816 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001817
Douglas Gregora8e02e72009-07-28 23:00:59 +00001818 if (!Spec) {
1819 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001820 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001821 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001822 TypeAlignment);
John McCall2408e322010-04-27 00:57:59 +00001823 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, false,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001824 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001825 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001826 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001827 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor15301382009-07-30 17:40:51 +00001830 if (Canon.isNull())
1831 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001832 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001833 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001834 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001835
Douglas Gregora8e02e72009-07-28 23:00:59 +00001836 // Allocate the (non-canonical) template specialization type, but don't
1837 // try to unique it: these types typically have location information that
1838 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001839 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001840 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001841 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001842 TemplateSpecializationType *Spec
John McCall2408e322010-04-27 00:57:59 +00001843 = new (Mem) TemplateSpecializationType(*this, Template,
1844 IsCurrentInstantiation,
1845 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001846 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregor8bf42052009-02-09 18:46:07 +00001848 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001849 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001850}
1851
Mike Stump11289f42009-09-09 15:08:12 +00001852QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001853ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1854 NestedNameSpecifier *NNS,
1855 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001856 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001857 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001858
1859 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001860 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001861 if (T)
1862 return QualType(T, 0);
1863
Douglas Gregorc42075a2010-02-04 18:10:26 +00001864 QualType Canon = NamedType;
1865 if (!Canon.isCanonical()) {
1866 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001867 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1868 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001869 (void)CheckT;
1870 }
1871
Abramo Bagnara6150c882010-05-11 21:36:43 +00001872 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001873 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001874 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001875 return QualType(T, 0);
1876}
1877
Douglas Gregor02085352010-03-31 20:19:30 +00001878QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1879 NestedNameSpecifier *NNS,
1880 const IdentifierInfo *Name,
1881 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001882 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1883
1884 if (Canon.isNull()) {
1885 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001886 ElaboratedTypeKeyword CanonKeyword = Keyword;
1887 if (Keyword == ETK_None)
1888 CanonKeyword = ETK_Typename;
1889
1890 if (CanonNNS != NNS || CanonKeyword != Keyword)
1891 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001892 }
1893
1894 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001895 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001896
1897 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001898 DependentNameType *T
1899 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00001900 if (T)
1901 return QualType(T, 0);
1902
Douglas Gregor02085352010-03-31 20:19:30 +00001903 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00001904 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001905 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001906 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00001907}
1908
Mike Stump11289f42009-09-09 15:08:12 +00001909QualType
Douglas Gregor02085352010-03-31 20:19:30 +00001910ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1911 NestedNameSpecifier *NNS,
1912 const TemplateSpecializationType *TemplateId,
1913 QualType Canon) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001914 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1915
Douglas Gregorc42075a2010-02-04 18:10:26 +00001916 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001917 DependentNameType::Profile(ID, Keyword, NNS, TemplateId);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001918
1919 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001920 DependentNameType *T
1921 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001922 if (T)
1923 return QualType(T, 0);
1924
Douglas Gregordce2b622009-04-01 00:28:59 +00001925 if (Canon.isNull()) {
1926 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1927 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
Douglas Gregor02085352010-03-31 20:19:30 +00001928 ElaboratedTypeKeyword CanonKeyword = Keyword;
1929 if (Keyword == ETK_None)
1930 CanonKeyword = ETK_Typename;
1931 if (CanonNNS != NNS || CanonKeyword != Keyword ||
1932 CanonType != QualType(TemplateId, 0)) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001933 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00001934 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00001935 assert(CanonTemplateId &&
1936 "Canonical type must also be a template specialization type");
Douglas Gregor02085352010-03-31 20:19:30 +00001937 Canon = getDependentNameType(CanonKeyword, CanonNNS, CanonTemplateId);
Douglas Gregordce2b622009-04-01 00:28:59 +00001938 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00001939
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001940 DependentNameType *CheckT
1941 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001942 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00001943 }
1944
Douglas Gregor02085352010-03-31 20:19:30 +00001945 T = new (*this) DependentNameType(Keyword, NNS, TemplateId, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00001946 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001947 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001948 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00001949}
1950
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001951/// CmpProtocolNames - Comparison predicate for sorting protocols
1952/// alphabetically.
1953static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1954 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00001955 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001956}
1957
John McCall8b07ec22010-05-15 11:32:37 +00001958static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00001959 unsigned NumProtocols) {
1960 if (NumProtocols == 0) return true;
1961
1962 for (unsigned i = 1; i != NumProtocols; ++i)
1963 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1964 return false;
1965 return true;
1966}
1967
1968static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001969 unsigned &NumProtocols) {
1970 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001972 // Sort protocols, keyed by name.
1973 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1974
1975 // Remove duplicates.
1976 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1977 NumProtocols = ProtocolsEnd-Protocols;
1978}
1979
John McCall8b07ec22010-05-15 11:32:37 +00001980QualType ASTContext::getObjCObjectType(QualType BaseType,
1981 ObjCProtocolDecl * const *Protocols,
1982 unsigned NumProtocols) {
1983 // If the base type is an interface and there aren't any protocols
1984 // to add, then the interface type will do just fine.
1985 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
1986 return BaseType;
1987
1988 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00001989 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00001990 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00001991 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00001992 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
1993 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00001994
John McCall8b07ec22010-05-15 11:32:37 +00001995 // Build the canonical type, which has the canonical base type and
1996 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00001997 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00001998 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
1999 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2000 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002001 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2002 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002003 unsigned UniqueCount = NumProtocols;
2004
John McCallfc93cf92009-10-22 22:37:11 +00002005 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002006 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2007 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002008 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002009 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2010 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002011 }
2012
2013 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002014 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2015 }
2016
2017 unsigned Size = sizeof(ObjCObjectTypeImpl);
2018 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2019 void *Mem = Allocate(Size, TypeAlignment);
2020 ObjCObjectTypeImpl *T =
2021 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2022
2023 Types.push_back(T);
2024 ObjCObjectTypes.InsertNode(T, InsertPos);
2025 return QualType(T, 0);
2026}
2027
2028/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2029/// the given object type.
2030QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2031 llvm::FoldingSetNodeID ID;
2032 ObjCObjectPointerType::Profile(ID, ObjectT);
2033
2034 void *InsertPos = 0;
2035 if (ObjCObjectPointerType *QT =
2036 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2037 return QualType(QT, 0);
2038
2039 // Find the canonical object type.
2040 QualType Canonical;
2041 if (!ObjectT.isCanonical()) {
2042 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2043
2044 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002045 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2046 }
2047
Douglas Gregorf85bee62010-02-08 22:59:26 +00002048 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002049 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2050 ObjCObjectPointerType *QType =
2051 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Steve Narofffb4330f2009-06-17 22:40:22 +00002053 Types.push_back(QType);
2054 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002055 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002056}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002057
Steve Naroffc277ad12009-07-18 15:33:26 +00002058/// getObjCInterfaceType - Return the unique reference to the type for the
2059/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002060QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2061 if (Decl->TypeForDecl)
2062 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002063
John McCall8b07ec22010-05-15 11:32:37 +00002064 // FIXME: redeclarations?
2065 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2066 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2067 Decl->TypeForDecl = T;
2068 Types.push_back(T);
2069 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002070}
2071
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002072/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2073/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002074/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002075/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002076/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002077QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002078 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002079 if (tofExpr->isTypeDependent()) {
2080 llvm::FoldingSetNodeID ID;
2081 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002082
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002083 void *InsertPos = 0;
2084 DependentTypeOfExprType *Canon
2085 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2086 if (Canon) {
2087 // We already have a "canonical" version of an identical, dependent
2088 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002089 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002090 QualType((TypeOfExprType*)Canon, 0));
2091 }
2092 else {
2093 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002094 Canon
2095 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002096 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2097 toe = Canon;
2098 }
2099 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002100 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002101 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002102 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002103 Types.push_back(toe);
2104 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002105}
2106
Steve Naroffa773cd52007-08-01 18:02:17 +00002107/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2108/// TypeOfType AST's. The only motivation to unique these nodes would be
2109/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002110/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002111/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002112QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002113 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002114 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002115 Types.push_back(tot);
2116 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002117}
2118
Anders Carlssonad6bd352009-06-24 21:24:56 +00002119/// getDecltypeForExpr - Given an expr, will return the decltype for that
2120/// expression, according to the rules in C++0x [dcl.type.simple]p4
2121static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002122 if (e->isTypeDependent())
2123 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002124
Anders Carlssonad6bd352009-06-24 21:24:56 +00002125 // If e is an id expression or a class member access, decltype(e) is defined
2126 // as the type of the entity named by e.
2127 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2128 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2129 return VD->getType();
2130 }
2131 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2132 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2133 return FD->getType();
2134 }
2135 // If e is a function call or an invocation of an overloaded operator,
2136 // (parentheses around e are ignored), decltype(e) is defined as the
2137 // return type of that function.
2138 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2139 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002140
Anders Carlssonad6bd352009-06-24 21:24:56 +00002141 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002142
2143 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002144 // defined as T&, otherwise decltype(e) is defined as T.
2145 if (e->isLvalue(Context) == Expr::LV_Valid)
2146 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002147
Anders Carlssonad6bd352009-06-24 21:24:56 +00002148 return T;
2149}
2150
Anders Carlsson81df7b82009-06-24 19:06:50 +00002151/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2152/// DecltypeType AST's. The only motivation to unique these nodes would be
2153/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002154/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002155/// on canonical type's (which are always unique).
2156QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002157 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002158 if (e->isTypeDependent()) {
2159 llvm::FoldingSetNodeID ID;
2160 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002161
Douglas Gregora21f6c32009-07-30 23:36:40 +00002162 void *InsertPos = 0;
2163 DependentDecltypeType *Canon
2164 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2165 if (Canon) {
2166 // We already have a "canonical" version of an equivalent, dependent
2167 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002168 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002169 QualType((DecltypeType*)Canon, 0));
2170 }
2171 else {
2172 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002173 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002174 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2175 dt = Canon;
2176 }
2177 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002178 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002179 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002180 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002181 Types.push_back(dt);
2182 return QualType(dt, 0);
2183}
2184
Chris Lattnerfb072462007-01-23 05:45:31 +00002185/// getTagDeclType - Return the unique reference to the type for the
2186/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002187QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002188 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002189 // FIXME: What is the design on getTagDeclType when it requires casting
2190 // away const? mutable?
2191 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002192}
2193
Mike Stump11289f42009-09-09 15:08:12 +00002194/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2195/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2196/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002197CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002198 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002199}
Chris Lattnerfb072462007-01-23 05:45:31 +00002200
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002201/// getSignedWCharType - Return the type of "signed wchar_t".
2202/// Used when in C++, as a GCC extension.
2203QualType ASTContext::getSignedWCharType() const {
2204 // FIXME: derive from "Target" ?
2205 return WCharTy;
2206}
2207
2208/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2209/// Used when in C++, as a GCC extension.
2210QualType ASTContext::getUnsignedWCharType() const {
2211 // FIXME: derive from "Target" ?
2212 return UnsignedIntTy;
2213}
2214
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002215/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2216/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2217QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002218 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002219}
2220
Chris Lattnera21ad802008-04-02 05:18:44 +00002221//===----------------------------------------------------------------------===//
2222// Type Operators
2223//===----------------------------------------------------------------------===//
2224
John McCallfc93cf92009-10-22 22:37:11 +00002225CanQualType ASTContext::getCanonicalParamType(QualType T) {
2226 // Push qualifiers into arrays, and then discard any remaining
2227 // qualifiers.
2228 T = getCanonicalType(T);
2229 const Type *Ty = T.getTypePtr();
2230
2231 QualType Result;
2232 if (isa<ArrayType>(Ty)) {
2233 Result = getArrayDecayedType(QualType(Ty,0));
2234 } else if (isa<FunctionType>(Ty)) {
2235 Result = getPointerType(QualType(Ty, 0));
2236 } else {
2237 Result = QualType(Ty, 0);
2238 }
2239
2240 return CanQualType::CreateUnsafe(Result);
2241}
2242
Chris Lattnered0d0792008-04-06 22:41:35 +00002243/// getCanonicalType - Return the canonical (structural) type corresponding to
2244/// the specified potentially non-canonical type. The non-canonical version
2245/// of a type may have many "decorated" versions of types. Decorators can
2246/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2247/// to be free of any of these, allowing two canonical types to be compared
2248/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002249CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002250 QualifierCollector Quals;
2251 const Type *Ptr = Quals.strip(T);
2252 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002253
John McCall8ccfcb52009-09-24 19:53:00 +00002254 // The canonical internal type will be the canonical type *except*
2255 // that we push type qualifiers down through array types.
2256
2257 // If there are no new qualifiers to push down, stop here.
2258 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002259 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002260
John McCall8ccfcb52009-09-24 19:53:00 +00002261 // If the type qualifiers are on an array type, get the canonical
2262 // type of the array with the qualifiers applied to the element
2263 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002264 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2265 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002266 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chris Lattner7adf0762008-08-04 07:31:14 +00002268 // Get the canonical version of the element with the extra qualifiers on it.
2269 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002270 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002271 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002272
Chris Lattner7adf0762008-08-04 07:31:14 +00002273 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002274 return CanQualType::CreateUnsafe(
2275 getConstantArrayType(NewEltTy, CAT->getSize(),
2276 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002277 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002278 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002279 return CanQualType::CreateUnsafe(
2280 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002281 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002282
Douglas Gregor4619e432008-12-05 23:32:09 +00002283 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002284 return CanQualType::CreateUnsafe(
2285 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002286 DSAT->getSizeExpr() ?
2287 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002288 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002289 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002290 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002291
Chris Lattner7adf0762008-08-04 07:31:14 +00002292 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002293 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002294 VAT->getSizeExpr() ?
2295 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002296 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002297 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002298 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002299}
2300
Chandler Carruth607f38e2009-12-29 07:16:59 +00002301QualType ASTContext::getUnqualifiedArrayType(QualType T,
2302 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002303 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002304 const ArrayType *AT = getAsArrayType(T);
2305 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002306 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002307 }
2308
Chandler Carruth607f38e2009-12-29 07:16:59 +00002309 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002310 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002311 if (Elt == UnqualElt)
2312 return T;
2313
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002314 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002315 return getConstantArrayType(UnqualElt, CAT->getSize(),
2316 CAT->getSizeModifier(), 0);
2317 }
2318
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002319 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002320 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2321 }
2322
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002323 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2324 return getVariableArrayType(UnqualElt,
2325 VAT->getSizeExpr() ?
2326 VAT->getSizeExpr()->Retain() : 0,
2327 VAT->getSizeModifier(),
2328 VAT->getIndexTypeCVRQualifiers(),
2329 VAT->getBracketsRange());
2330 }
2331
2332 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002333 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2334 DSAT->getSizeModifier(), 0,
2335 SourceRange());
2336}
2337
John McCall847e2a12009-11-24 18:42:40 +00002338DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2339 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2340 return TD->getDeclName();
2341
2342 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2343 if (DTN->isIdentifier()) {
2344 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2345 } else {
2346 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2347 }
2348 }
2349
John McCalld28ae272009-12-02 08:04:21 +00002350 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2351 assert(Storage);
2352 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002353}
2354
Douglas Gregor6bc50582009-05-07 06:41:52 +00002355TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2356 // If this template name refers to a template, the canonical
2357 // template name merely stores the template itself.
2358 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002359 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002360
John McCalld28ae272009-12-02 08:04:21 +00002361 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregor6bc50582009-05-07 06:41:52 +00002363 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2364 assert(DTN && "Non-dependent template names must refer to template decls.");
2365 return DTN->CanonicalTemplateName;
2366}
2367
Douglas Gregoradee3e32009-11-11 23:06:43 +00002368bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2369 X = getCanonicalTemplateName(X);
2370 Y = getCanonicalTemplateName(Y);
2371 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2372}
2373
Mike Stump11289f42009-09-09 15:08:12 +00002374TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002375ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2376 switch (Arg.getKind()) {
2377 case TemplateArgument::Null:
2378 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002379
Douglas Gregora8e02e72009-07-28 23:00:59 +00002380 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002381 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002382
Douglas Gregora8e02e72009-07-28 23:00:59 +00002383 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002384 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002385
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002386 case TemplateArgument::Template:
2387 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2388
Douglas Gregora8e02e72009-07-28 23:00:59 +00002389 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002390 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002391 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002392
Douglas Gregora8e02e72009-07-28 23:00:59 +00002393 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002394 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002395
Douglas Gregora8e02e72009-07-28 23:00:59 +00002396 case TemplateArgument::Pack: {
2397 // FIXME: Allocate in ASTContext
2398 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2399 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002400 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002401 AEnd = Arg.pack_end();
2402 A != AEnd; (void)++A, ++Idx)
2403 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002404
Douglas Gregora8e02e72009-07-28 23:00:59 +00002405 TemplateArgument Result;
2406 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2407 return Result;
2408 }
2409 }
2410
2411 // Silence GCC warning
2412 assert(false && "Unhandled template argument kind");
2413 return TemplateArgument();
2414}
2415
Douglas Gregor333489b2009-03-27 23:10:48 +00002416NestedNameSpecifier *
2417ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002418 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002419 return 0;
2420
2421 switch (NNS->getKind()) {
2422 case NestedNameSpecifier::Identifier:
2423 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002424 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002425 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2426 NNS->getAsIdentifier());
2427
2428 case NestedNameSpecifier::Namespace:
2429 // A namespace is canonical; build a nested-name-specifier with
2430 // this namespace and no prefix.
2431 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2432
2433 case NestedNameSpecifier::TypeSpec:
2434 case NestedNameSpecifier::TypeSpecWithTemplate: {
2435 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002436 return NestedNameSpecifier::Create(*this, 0,
2437 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002438 T.getTypePtr());
2439 }
2440
2441 case NestedNameSpecifier::Global:
2442 // The global specifier is canonical and unique.
2443 return NNS;
2444 }
2445
2446 // Required to silence a GCC warning
2447 return 0;
2448}
2449
Chris Lattner7adf0762008-08-04 07:31:14 +00002450
2451const ArrayType *ASTContext::getAsArrayType(QualType T) {
2452 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002453 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002454 // Handle the common positive case fast.
2455 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2456 return AT;
2457 }
Mike Stump11289f42009-09-09 15:08:12 +00002458
John McCall8ccfcb52009-09-24 19:53:00 +00002459 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002460 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002461 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002462 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002463
John McCall8ccfcb52009-09-24 19:53:00 +00002464 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002465 // implements C99 6.7.3p8: "If the specification of an array type includes
2466 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattner7adf0762008-08-04 07:31:14 +00002468 // If we get here, we either have type qualifiers on the type, or we have
2469 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002470 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002471
John McCall8ccfcb52009-09-24 19:53:00 +00002472 QualifierCollector Qs;
2473 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002474
Chris Lattner7adf0762008-08-04 07:31:14 +00002475 // If we have a simple case, just return now.
2476 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002477 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002478 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002479
Chris Lattner7adf0762008-08-04 07:31:14 +00002480 // Otherwise, we have an array and we have qualifiers on it. Push the
2481 // qualifiers into the array element type and return a new array type.
2482 // Get the canonical version of the element with the extra qualifiers on it.
2483 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002484 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002485
Chris Lattner7adf0762008-08-04 07:31:14 +00002486 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2487 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2488 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002489 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002490 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2491 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2492 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002493 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002494
Mike Stump11289f42009-09-09 15:08:12 +00002495 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002496 = dyn_cast<DependentSizedArrayType>(ATy))
2497 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002498 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002499 DSAT->getSizeExpr() ?
2500 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002501 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002502 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002503 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chris Lattner7adf0762008-08-04 07:31:14 +00002505 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002506 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002507 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002508 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002509 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002510 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002511 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002512}
2513
2514
Chris Lattnera21ad802008-04-02 05:18:44 +00002515/// getArrayDecayedType - Return the properly qualified result of decaying the
2516/// specified array type to a pointer. This operation is non-trivial when
2517/// handling typedefs etc. The canonical type of "T" must be an array type,
2518/// this returns a pointer to a properly qualified element of the array.
2519///
2520/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2521QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002522 // Get the element type with 'getAsArrayType' so that we don't lose any
2523 // typedefs in the element type of the array. This also handles propagation
2524 // of type qualifiers from the array type into the element type if present
2525 // (C99 6.7.3p8).
2526 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2527 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002528
Chris Lattner7adf0762008-08-04 07:31:14 +00002529 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002530
2531 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002532 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002533}
2534
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002535QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002536 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002537 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2538 QT = AT->getElementType();
2539 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002540}
2541
Anders Carlsson4bf82142009-09-25 01:23:32 +00002542QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2543 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002544
Anders Carlsson4bf82142009-09-25 01:23:32 +00002545 if (const ArrayType *AT = getAsArrayType(ElemTy))
2546 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002547
Anders Carlssone0808df2008-12-21 03:44:36 +00002548 return ElemTy;
2549}
2550
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002551/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002552uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002553ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2554 uint64_t ElementCount = 1;
2555 do {
2556 ElementCount *= CA->getSize().getZExtValue();
2557 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2558 } while (CA);
2559 return ElementCount;
2560}
2561
Steve Naroff0af91202007-04-27 21:51:21 +00002562/// getFloatingRank - Return a relative rank for floating point types.
2563/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002564static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002565 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002566 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002567
John McCall9dd450b2009-09-21 23:43:11 +00002568 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2569 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002570 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002571 case BuiltinType::Float: return FloatRank;
2572 case BuiltinType::Double: return DoubleRank;
2573 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002574 }
2575}
2576
Mike Stump11289f42009-09-09 15:08:12 +00002577/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2578/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002579/// 'typeDomain' is a real floating point or complex type.
2580/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002581QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2582 QualType Domain) const {
2583 FloatingRank EltRank = getFloatingRank(Size);
2584 if (Domain->isComplexType()) {
2585 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002586 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002587 case FloatRank: return FloatComplexTy;
2588 case DoubleRank: return DoubleComplexTy;
2589 case LongDoubleRank: return LongDoubleComplexTy;
2590 }
Steve Naroff0af91202007-04-27 21:51:21 +00002591 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002592
2593 assert(Domain->isRealFloatingType() && "Unknown domain!");
2594 switch (EltRank) {
2595 default: assert(0 && "getFloatingRank(): illegal value for rank");
2596 case FloatRank: return FloatTy;
2597 case DoubleRank: return DoubleTy;
2598 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002599 }
Steve Naroffe4718892007-04-27 18:30:00 +00002600}
2601
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002602/// getFloatingTypeOrder - Compare the rank of the two specified floating
2603/// point types, ignoring the domain of the type (i.e. 'double' ==
2604/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002605/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002606int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2607 FloatingRank LHSR = getFloatingRank(LHS);
2608 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002609
Chris Lattnerb90739d2008-04-06 23:38:49 +00002610 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002611 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002612 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002613 return 1;
2614 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002615}
2616
Chris Lattner76a00cf2008-04-06 22:59:24 +00002617/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2618/// routine will assert if passed a built-in type that isn't an integer or enum,
2619/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002620unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002621 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002622 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002623 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002624
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002625 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2626 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2627
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002628 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2629 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2630
2631 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2632 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2633
Chris Lattner76a00cf2008-04-06 22:59:24 +00002634 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002635 default: assert(0 && "getIntegerRank(): not a built-in integer");
2636 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002637 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002638 case BuiltinType::Char_S:
2639 case BuiltinType::Char_U:
2640 case BuiltinType::SChar:
2641 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002642 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002643 case BuiltinType::Short:
2644 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002645 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002646 case BuiltinType::Int:
2647 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002648 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002649 case BuiltinType::Long:
2650 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002651 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002652 case BuiltinType::LongLong:
2653 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002654 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002655 case BuiltinType::Int128:
2656 case BuiltinType::UInt128:
2657 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002658 }
2659}
2660
Eli Friedman629ffb92009-08-20 04:21:42 +00002661/// \brief Whether this is a promotable bitfield reference according
2662/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2663///
2664/// \returns the type this bit-field will promote to, or NULL if no
2665/// promotion occurs.
2666QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002667 if (E->isTypeDependent() || E->isValueDependent())
2668 return QualType();
2669
Eli Friedman629ffb92009-08-20 04:21:42 +00002670 FieldDecl *Field = E->getBitField();
2671 if (!Field)
2672 return QualType();
2673
2674 QualType FT = Field->getType();
2675
2676 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2677 uint64_t BitWidth = BitWidthAP.getZExtValue();
2678 uint64_t IntSize = getTypeSize(IntTy);
2679 // GCC extension compatibility: if the bit-field size is less than or equal
2680 // to the size of int, it gets promoted no matter what its type is.
2681 // For instance, unsigned long bf : 4 gets promoted to signed int.
2682 if (BitWidth < IntSize)
2683 return IntTy;
2684
2685 if (BitWidth == IntSize)
2686 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2687
2688 // Types bigger than int are not subject to promotions, and therefore act
2689 // like the base type.
2690 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2691 // is ridiculous.
2692 return QualType();
2693}
2694
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002695/// getPromotedIntegerType - Returns the type that Promotable will
2696/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2697/// integer type.
2698QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2699 assert(!Promotable.isNull());
2700 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002701 if (const EnumType *ET = Promotable->getAs<EnumType>())
2702 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002703 if (Promotable->isSignedIntegerType())
2704 return IntTy;
2705 uint64_t PromotableSize = getTypeSize(Promotable);
2706 uint64_t IntSize = getTypeSize(IntTy);
2707 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2708 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2709}
2710
Mike Stump11289f42009-09-09 15:08:12 +00002711/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002712/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002713/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002714int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002715 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2716 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002717 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattner76a00cf2008-04-06 22:59:24 +00002719 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2720 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002721
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002722 unsigned LHSRank = getIntegerRank(LHSC);
2723 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002724
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002725 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2726 if (LHSRank == RHSRank) return 0;
2727 return LHSRank > RHSRank ? 1 : -1;
2728 }
Mike Stump11289f42009-09-09 15:08:12 +00002729
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002730 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2731 if (LHSUnsigned) {
2732 // If the unsigned [LHS] type is larger, return it.
2733 if (LHSRank >= RHSRank)
2734 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002735
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002736 // If the signed type can represent all values of the unsigned type, it
2737 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002738 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002739 return -1;
2740 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002741
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002742 // If the unsigned [RHS] type is larger, return it.
2743 if (RHSRank >= LHSRank)
2744 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002745
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002746 // If the signed type can represent all values of the unsigned type, it
2747 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002748 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002749 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002750}
Anders Carlsson98f07902007-08-17 05:31:46 +00002751
Anders Carlsson6d417272009-11-14 21:45:58 +00002752static RecordDecl *
2753CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2754 SourceLocation L, IdentifierInfo *Id) {
2755 if (Ctx.getLangOptions().CPlusPlus)
2756 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2757 else
2758 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2759}
2760
Mike Stump11289f42009-09-09 15:08:12 +00002761// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002762QualType ASTContext::getCFConstantStringType() {
2763 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002764 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002765 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002766 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002767 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002768
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002769 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002770
Anders Carlsson98f07902007-08-17 05:31:46 +00002771 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002772 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002773 // int flags;
2774 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002775 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002776 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002777 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002778 FieldTypes[3] = LongTy;
2779
Anders Carlsson98f07902007-08-17 05:31:46 +00002780 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002781 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002782 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002783 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002784 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002785 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002786 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002787 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002788 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002789 }
2790
Douglas Gregord5058122010-02-11 01:19:42 +00002791 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002792 }
Mike Stump11289f42009-09-09 15:08:12 +00002793
Anders Carlsson98f07902007-08-17 05:31:46 +00002794 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002795}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002796
Douglas Gregor512b0772009-04-23 22:29:11 +00002797void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002798 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002799 assert(Rec && "Invalid CFConstantStringType");
2800 CFConstantStringTypeDecl = Rec->getDecl();
2801}
2802
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002803// getNSConstantStringType - Return the type used for constant NSStrings.
2804QualType ASTContext::getNSConstantStringType() {
2805 if (!NSConstantStringTypeDecl) {
2806 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002807 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002808 &Idents.get("__builtin_NSString"));
2809 NSConstantStringTypeDecl->startDefinition();
2810
2811 QualType FieldTypes[3];
2812
2813 // const int *isa;
2814 FieldTypes[0] = getPointerType(IntTy.withConst());
2815 // const char *str;
2816 FieldTypes[1] = getPointerType(CharTy.withConst());
2817 // unsigned int length;
2818 FieldTypes[2] = UnsignedIntTy;
2819
2820 // Create fields
2821 for (unsigned i = 0; i < 3; ++i) {
2822 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2823 SourceLocation(), 0,
2824 FieldTypes[i], /*TInfo=*/0,
2825 /*BitWidth=*/0,
2826 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002827 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002828 NSConstantStringTypeDecl->addDecl(Field);
2829 }
2830
2831 NSConstantStringTypeDecl->completeDefinition();
2832 }
2833
2834 return getTagDeclType(NSConstantStringTypeDecl);
2835}
2836
2837void ASTContext::setNSConstantStringType(QualType T) {
2838 const RecordType *Rec = T->getAs<RecordType>();
2839 assert(Rec && "Invalid NSConstantStringType");
2840 NSConstantStringTypeDecl = Rec->getDecl();
2841}
2842
Mike Stump11289f42009-09-09 15:08:12 +00002843QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002844 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00002845 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002846 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002847 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00002848 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002849
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002850 QualType FieldTypes[] = {
2851 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00002852 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002853 getPointerType(UnsignedLongTy),
2854 getConstantArrayType(UnsignedLongTy,
2855 llvm::APInt(32, 5), ArrayType::Normal, 0)
2856 };
Mike Stump11289f42009-09-09 15:08:12 +00002857
Douglas Gregor91f84212008-12-11 16:49:14 +00002858 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002859 FieldDecl *Field = FieldDecl::Create(*this,
2860 ObjCFastEnumerationStateTypeDecl,
2861 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002862 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002863 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002864 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002865 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002866 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002867 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00002868 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00002869 if (CXXRecordDecl *CXXRD =
2870 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00002871 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00002872
Douglas Gregord5058122010-02-11 01:19:42 +00002873 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002874 }
Mike Stump11289f42009-09-09 15:08:12 +00002875
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002876 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2877}
2878
Mike Stumpd0153282009-10-20 02:12:22 +00002879QualType ASTContext::getBlockDescriptorType() {
2880 if (BlockDescriptorType)
2881 return getTagDeclType(BlockDescriptorType);
2882
2883 RecordDecl *T;
2884 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002885 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002886 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00002887 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002888
2889 QualType FieldTypes[] = {
2890 UnsignedLongTy,
2891 UnsignedLongTy,
2892 };
2893
2894 const char *FieldNames[] = {
2895 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002896 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00002897 };
2898
2899 for (size_t i = 0; i < 2; ++i) {
2900 FieldDecl *Field = FieldDecl::Create(*this,
2901 T,
2902 SourceLocation(),
2903 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002904 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00002905 /*BitWidth=*/0,
2906 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002907 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00002908 T->addDecl(Field);
2909 }
2910
Douglas Gregord5058122010-02-11 01:19:42 +00002911 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002912
2913 BlockDescriptorType = T;
2914
2915 return getTagDeclType(BlockDescriptorType);
2916}
2917
2918void ASTContext::setBlockDescriptorType(QualType T) {
2919 const RecordType *Rec = T->getAs<RecordType>();
2920 assert(Rec && "Invalid BlockDescriptorType");
2921 BlockDescriptorType = Rec->getDecl();
2922}
2923
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002924QualType ASTContext::getBlockDescriptorExtendedType() {
2925 if (BlockDescriptorExtendedType)
2926 return getTagDeclType(BlockDescriptorExtendedType);
2927
2928 RecordDecl *T;
2929 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002930 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002931 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00002932 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002933
2934 QualType FieldTypes[] = {
2935 UnsignedLongTy,
2936 UnsignedLongTy,
2937 getPointerType(VoidPtrTy),
2938 getPointerType(VoidPtrTy)
2939 };
2940
2941 const char *FieldNames[] = {
2942 "reserved",
2943 "Size",
2944 "CopyFuncPtr",
2945 "DestroyFuncPtr"
2946 };
2947
2948 for (size_t i = 0; i < 4; ++i) {
2949 FieldDecl *Field = FieldDecl::Create(*this,
2950 T,
2951 SourceLocation(),
2952 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002953 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002954 /*BitWidth=*/0,
2955 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002956 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002957 T->addDecl(Field);
2958 }
2959
Douglas Gregord5058122010-02-11 01:19:42 +00002960 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002961
2962 BlockDescriptorExtendedType = T;
2963
2964 return getTagDeclType(BlockDescriptorExtendedType);
2965}
2966
2967void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2968 const RecordType *Rec = T->getAs<RecordType>();
2969 assert(Rec && "Invalid BlockDescriptorType");
2970 BlockDescriptorExtendedType = Rec->getDecl();
2971}
2972
Mike Stump94967902009-10-21 18:16:27 +00002973bool ASTContext::BlockRequiresCopying(QualType Ty) {
2974 if (Ty->isBlockPointerType())
2975 return true;
2976 if (isObjCNSObjectType(Ty))
2977 return true;
2978 if (Ty->isObjCObjectPointerType())
2979 return true;
2980 return false;
2981}
2982
2983QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2984 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00002985 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00002986 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00002987 // unsigned int __flags;
2988 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00002989 // void *__copy_helper; // as needed
2990 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00002991 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00002992 // } *
2993
Mike Stump94967902009-10-21 18:16:27 +00002994 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2995
2996 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00002997 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00002998 llvm::SmallString<36> Name;
2999 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3000 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003001 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003002 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003003 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003004 T->startDefinition();
3005 QualType Int32Ty = IntTy;
3006 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3007 QualType FieldTypes[] = {
3008 getPointerType(VoidPtrTy),
3009 getPointerType(getTagDeclType(T)),
3010 Int32Ty,
3011 Int32Ty,
3012 getPointerType(VoidPtrTy),
3013 getPointerType(VoidPtrTy),
3014 Ty
3015 };
3016
3017 const char *FieldNames[] = {
3018 "__isa",
3019 "__forwarding",
3020 "__flags",
3021 "__size",
3022 "__copy_helper",
3023 "__destroy_helper",
3024 DeclName,
3025 };
3026
3027 for (size_t i = 0; i < 7; ++i) {
3028 if (!HasCopyAndDispose && i >=4 && i <= 5)
3029 continue;
3030 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3031 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003032 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003033 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003034 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003035 T->addDecl(Field);
3036 }
3037
Douglas Gregord5058122010-02-11 01:19:42 +00003038 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003039
3040 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003041}
3042
3043
3044QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003045 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003046 llvm::SmallVectorImpl<const Expr *> &Layout) {
3047
Mike Stumpd0153282009-10-20 02:12:22 +00003048 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003049 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003050 llvm::SmallString<36> Name;
3051 llvm::raw_svector_ostream(Name) << "__block_literal_"
3052 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003053 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003054 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003055 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003056 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003057 QualType FieldTypes[] = {
3058 getPointerType(VoidPtrTy),
3059 IntTy,
3060 IntTy,
3061 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003062 (BlockHasCopyDispose ?
3063 getPointerType(getBlockDescriptorExtendedType()) :
3064 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003065 };
3066
3067 const char *FieldNames[] = {
3068 "__isa",
3069 "__flags",
3070 "__reserved",
3071 "__FuncPtr",
3072 "__descriptor"
3073 };
3074
3075 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003076 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003077 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003078 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003079 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003080 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003081 T->addDecl(Field);
3082 }
3083
John McCall87fe5d52010-05-20 01:18:31 +00003084 for (unsigned i = 0; i < Layout.size(); ++i) {
3085 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003086
John McCall87fe5d52010-05-20 01:18:31 +00003087 QualType FieldType = E->getType();
3088 IdentifierInfo *FieldName = 0;
3089 if (isa<CXXThisExpr>(E)) {
3090 FieldName = &Idents.get("this");
3091 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3092 const ValueDecl *D = BDRE->getDecl();
3093 FieldName = D->getIdentifier();
3094 if (BDRE->isByRef())
3095 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3096 } else {
3097 // Padding.
3098 assert(isa<ConstantArrayType>(FieldType) &&
3099 isa<DeclRefExpr>(E) &&
3100 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3101 "doesn't match characteristics of padding decl");
3102 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003103
3104 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003105 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003106 /*BitWidth=*/0, /*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 Stump7fe9cc12009-10-21 03:49:08 +00003112
3113 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003114}
3115
Douglas Gregor512b0772009-04-23 22:29:11 +00003116void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003117 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003118 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3119 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3120}
3121
Anders Carlsson18acd442007-10-29 06:33:42 +00003122// This returns true if a type has been typedefed to BOOL:
3123// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003124static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003125 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003126 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3127 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003128
Anders Carlssond8499822007-10-29 05:01:08 +00003129 return false;
3130}
3131
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003132/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003133/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003134CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003135 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003136
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003137 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003138 if (sz.isPositive() && type->isIntegralType())
3139 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003140 // Treat arrays as pointers, since that's how they're passed in.
3141 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003142 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003143 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003144}
3145
3146static inline
3147std::string charUnitsToString(const CharUnits &CU) {
3148 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003149}
3150
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003151/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003152/// declaration.
3153void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3154 std::string& S) {
3155 const BlockDecl *Decl = Expr->getBlockDecl();
3156 QualType BlockTy =
3157 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3158 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003159 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003160 // Compute size of all parameters.
3161 // Start with computing size of a pointer in number of bytes.
3162 // FIXME: There might(should) be a better way of doing this computation!
3163 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003164 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3165 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003166 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003167 E = Decl->param_end(); PI != E; ++PI) {
3168 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003169 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003170 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003171 ParmOffset += sz;
3172 }
3173 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003174 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003175 // Block pointer and offset.
3176 S += "@?0";
3177 ParmOffset = PtrSize;
3178
3179 // Argument types.
3180 ParmOffset = PtrSize;
3181 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3182 Decl->param_end(); PI != E; ++PI) {
3183 ParmVarDecl *PVDecl = *PI;
3184 QualType PType = PVDecl->getOriginalType();
3185 if (const ArrayType *AT =
3186 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3187 // Use array's original type only if it has known number of
3188 // elements.
3189 if (!isa<ConstantArrayType>(AT))
3190 PType = PVDecl->getType();
3191 } else if (PType->isFunctionType())
3192 PType = PVDecl->getType();
3193 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003194 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003195 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003196 }
3197}
3198
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003199/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003200/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003201void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003202 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003203 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003204 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003205 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003206 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003207 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003208 // Compute size of all parameters.
3209 // Start with computing size of a pointer in number of bytes.
3210 // FIXME: There might(should) be a better way of doing this computation!
3211 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003212 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003213 // The first two arguments (self and _cmd) are pointers; account for
3214 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003215 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003216 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003217 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003218 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003219 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003220 assert (sz.isPositive() &&
3221 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003222 ParmOffset += sz;
3223 }
Ken Dyck40775002010-01-11 17:06:35 +00003224 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003225 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003226 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003227
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003228 // Argument types.
3229 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003230 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003231 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003232 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003233 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003234 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003235 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3236 // Use array's original type only if it has known number of
3237 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003238 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003239 PType = PVDecl->getType();
3240 } else if (PType->isFunctionType())
3241 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003242 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003243 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003244 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003245 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003246 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003247 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003248 }
3249}
3250
Daniel Dunbar4932b362008-08-28 04:38:10 +00003251/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003252/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003253/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3254/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003255/// Property attributes are stored as a comma-delimited C string. The simple
3256/// attributes readonly and bycopy are encoded as single characters. The
3257/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3258/// encoded as single characters, followed by an identifier. Property types
3259/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003260/// these attributes are defined by the following enumeration:
3261/// @code
3262/// enum PropertyAttributes {
3263/// kPropertyReadOnly = 'R', // property is read-only.
3264/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3265/// kPropertyByref = '&', // property is a reference to the value last assigned
3266/// kPropertyDynamic = 'D', // property is dynamic
3267/// kPropertyGetter = 'G', // followed by getter selector name
3268/// kPropertySetter = 'S', // followed by setter selector name
3269/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3270/// kPropertyType = 't' // followed by old-style type encoding.
3271/// kPropertyWeak = 'W' // 'weak' property
3272/// kPropertyStrong = 'P' // property GC'able
3273/// kPropertyNonAtomic = 'N' // property non-atomic
3274/// };
3275/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003276void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003277 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003278 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003279 // Collect information from the property implementation decl(s).
3280 bool Dynamic = false;
3281 ObjCPropertyImplDecl *SynthesizePID = 0;
3282
3283 // FIXME: Duplicated code due to poor abstraction.
3284 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003285 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003286 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3287 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003288 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003289 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003290 ObjCPropertyImplDecl *PID = *i;
3291 if (PID->getPropertyDecl() == PD) {
3292 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3293 Dynamic = true;
3294 } else {
3295 SynthesizePID = PID;
3296 }
3297 }
3298 }
3299 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003300 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003301 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003302 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003303 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003304 ObjCPropertyImplDecl *PID = *i;
3305 if (PID->getPropertyDecl() == PD) {
3306 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3307 Dynamic = true;
3308 } else {
3309 SynthesizePID = PID;
3310 }
3311 }
Mike Stump11289f42009-09-09 15:08:12 +00003312 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003313 }
3314 }
3315
3316 // FIXME: This is not very efficient.
3317 S = "T";
3318
3319 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003320 // GCC has some special rules regarding encoding of properties which
3321 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003322 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003323 true /* outermost type */,
3324 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003325
3326 if (PD->isReadOnly()) {
3327 S += ",R";
3328 } else {
3329 switch (PD->getSetterKind()) {
3330 case ObjCPropertyDecl::Assign: break;
3331 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003332 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003333 }
3334 }
3335
3336 // It really isn't clear at all what this means, since properties
3337 // are "dynamic by default".
3338 if (Dynamic)
3339 S += ",D";
3340
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003341 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3342 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003343
Daniel Dunbar4932b362008-08-28 04:38:10 +00003344 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3345 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003346 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003347 }
3348
3349 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3350 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003351 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003352 }
3353
3354 if (SynthesizePID) {
3355 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3356 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003357 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003358 }
3359
3360 // FIXME: OBJCGC: weak & strong
3361}
3362
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003363/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003364/// Another legacy compatibility encoding: 32-bit longs are encoded as
3365/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003366/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3367///
3368void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003369 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003370 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003371 if (BT->getKind() == BuiltinType::ULong &&
3372 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003373 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003374 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003375 if (BT->getKind() == BuiltinType::Long &&
3376 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003377 PointeeTy = IntTy;
3378 }
3379 }
3380}
3381
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003382void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003383 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003384 // We follow the behavior of gcc, expanding structures which are
3385 // directly pointed to, and expanding embedded structures. Note that
3386 // these rules are sufficient to prevent recursive encoding of the
3387 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003388 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003389 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003390}
3391
David Chisnallb190a2c2010-06-04 01:10:52 +00003392static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3393 switch (T->getAs<BuiltinType>()->getKind()) {
3394 default: assert(0 && "Unhandled builtin type kind");
3395 case BuiltinType::Void: return 'v';
3396 case BuiltinType::Bool: return 'B';
3397 case BuiltinType::Char_U:
3398 case BuiltinType::UChar: return 'C';
3399 case BuiltinType::UShort: return 'S';
3400 case BuiltinType::UInt: return 'I';
3401 case BuiltinType::ULong:
3402 return
3403 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3404 case BuiltinType::UInt128: return 'T';
3405 case BuiltinType::ULongLong: return 'Q';
3406 case BuiltinType::Char_S:
3407 case BuiltinType::SChar: return 'c';
3408 case BuiltinType::Short: return 's';
3409 case BuiltinType::Int: return 'i';
3410 case BuiltinType::Long:
3411 return
3412 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3413 case BuiltinType::LongLong: return 'q';
3414 case BuiltinType::Int128: return 't';
3415 case BuiltinType::Float: return 'f';
3416 case BuiltinType::Double: return 'd';
3417 case BuiltinType::LongDouble: return 'd';
3418 }
3419}
3420
Mike Stump11289f42009-09-09 15:08:12 +00003421static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003422 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003423 const Expr *E = FD->getBitWidth();
3424 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3425 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003426 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003427 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3428 // The GNU runtime requires more information; bitfields are encoded as b,
3429 // then the offset (in bits) of the first element, then the type of the
3430 // bitfield, then the size in bits. For example, in this structure:
3431 //
3432 // struct
3433 // {
3434 // int integer;
3435 // int flags:2;
3436 // };
3437 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3438 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3439 // information is not especially sensible, but we're stuck with it for
3440 // compatibility with GCC, although providing it breaks anything that
3441 // actually uses runtime introspection and wants to work on both runtimes...
3442 if (!Ctx->getLangOptions().NeXTRuntime) {
3443 const RecordDecl *RD = FD->getParent();
3444 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3445 // FIXME: This same linear search is also used in ExprConstant - it might
3446 // be better if the FieldDecl stored its offset. We'd be increasing the
3447 // size of the object slightly, but saving some time every time it is used.
3448 unsigned i = 0;
3449 for (RecordDecl::field_iterator Field = RD->field_begin(),
3450 FieldEnd = RD->field_end();
3451 Field != FieldEnd; (void)++Field, ++i) {
3452 if (*Field == FD)
3453 break;
3454 }
3455 S += llvm::utostr(RL.getFieldOffset(i));
3456 S += ObjCEncodingForPrimitiveKind(Context, T);
3457 }
3458 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003459 S += llvm::utostr(N);
3460}
3461
Daniel Dunbar07d07852009-10-18 21:17:35 +00003462// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003463void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3464 bool ExpandPointedToStructures,
3465 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003466 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003467 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003468 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003469 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003470 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003471 return EncodeBitField(this, S, T, FD);
3472 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003473 return;
3474 }
Mike Stump11289f42009-09-09 15:08:12 +00003475
John McCall9dd450b2009-09-21 23:43:11 +00003476 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003477 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003478 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003479 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003480 return;
3481 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003482
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003483 // encoding for pointer or r3eference types.
3484 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003485 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003486 if (PT->isObjCSelType()) {
3487 S += ':';
3488 return;
3489 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003490 PointeeTy = PT->getPointeeType();
3491 }
3492 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3493 PointeeTy = RT->getPointeeType();
3494 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003495 bool isReadOnly = false;
3496 // For historical/compatibility reasons, the read-only qualifier of the
3497 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3498 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003499 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003500 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003501 if (OutermostType && T.isConstQualified()) {
3502 isReadOnly = true;
3503 S += 'r';
3504 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003505 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003506 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003507 while (P->getAs<PointerType>())
3508 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003509 if (P.isConstQualified()) {
3510 isReadOnly = true;
3511 S += 'r';
3512 }
3513 }
3514 if (isReadOnly) {
3515 // Another legacy compatibility encoding. Some ObjC qualifier and type
3516 // combinations need to be rearranged.
3517 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003518 if (llvm::StringRef(S).endswith("nr"))
3519 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003520 }
Mike Stump11289f42009-09-09 15:08:12 +00003521
Anders Carlssond8499822007-10-29 05:01:08 +00003522 if (PointeeTy->isCharType()) {
3523 // char pointer types should be encoded as '*' unless it is a
3524 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003525 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003526 S += '*';
3527 return;
3528 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003529 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003530 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3531 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3532 S += '#';
3533 return;
3534 }
3535 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3536 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3537 S += '@';
3538 return;
3539 }
3540 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003541 }
Anders Carlssond8499822007-10-29 05:01:08 +00003542 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003543 getLegacyIntegralTypeEncoding(PointeeTy);
3544
Mike Stump11289f42009-09-09 15:08:12 +00003545 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003546 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003547 return;
3548 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003549
Chris Lattnere7cabb92009-07-13 00:10:46 +00003550 if (const ArrayType *AT =
3551 // Ignore type qualifiers etc.
3552 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003553 if (isa<IncompleteArrayType>(AT)) {
3554 // Incomplete arrays are encoded as a pointer to the array element.
3555 S += '^';
3556
Mike Stump11289f42009-09-09 15:08:12 +00003557 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003558 false, ExpandStructures, FD);
3559 } else {
3560 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003561
Anders Carlssond05f44b2009-02-22 01:38:57 +00003562 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3563 S += llvm::utostr(CAT->getSize().getZExtValue());
3564 else {
3565 //Variable length arrays are encoded as a regular array with 0 elements.
3566 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3567 S += '0';
3568 }
Mike Stump11289f42009-09-09 15:08:12 +00003569
3570 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003571 false, ExpandStructures, FD);
3572 S += ']';
3573 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003574 return;
3575 }
Mike Stump11289f42009-09-09 15:08:12 +00003576
John McCall9dd450b2009-09-21 23:43:11 +00003577 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003578 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003579 return;
3580 }
Mike Stump11289f42009-09-09 15:08:12 +00003581
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003582 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003583 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003584 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003585 // Anonymous structures print as '?'
3586 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3587 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003588 if (ClassTemplateSpecializationDecl *Spec
3589 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3590 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3591 std::string TemplateArgsStr
3592 = TemplateSpecializationType::PrintTemplateArgumentList(
3593 TemplateArgs.getFlatArgumentList(),
3594 TemplateArgs.flat_size(),
3595 (*this).PrintingPolicy);
3596
3597 S += TemplateArgsStr;
3598 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003599 } else {
3600 S += '?';
3601 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003602 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003603 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003604 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3605 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003606 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003607 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003608 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003609 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003610 S += '"';
3611 }
Mike Stump11289f42009-09-09 15:08:12 +00003612
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003613 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003614 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003615 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003616 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003617 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003618 QualType qt = Field->getType();
3619 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003620 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003621 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003622 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003623 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003624 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003625 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003626 return;
3627 }
Mike Stump11289f42009-09-09 15:08:12 +00003628
Chris Lattnere7cabb92009-07-13 00:10:46 +00003629 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003630 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003631 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003632 else
3633 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003634 return;
3635 }
Mike Stump11289f42009-09-09 15:08:12 +00003636
Chris Lattnere7cabb92009-07-13 00:10:46 +00003637 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003638 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003639 return;
3640 }
Mike Stump11289f42009-09-09 15:08:12 +00003641
John McCall8b07ec22010-05-15 11:32:37 +00003642 // Ignore protocol qualifiers when mangling at this level.
3643 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3644 T = OT->getBaseType();
3645
John McCall8ccfcb52009-09-24 19:53:00 +00003646 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003647 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003648 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003649 S += '{';
3650 const IdentifierInfo *II = OI->getIdentifier();
3651 S += II->getName();
3652 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003653 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003654 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003655 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003656 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003657 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003658 RecFields[i]);
3659 else
Mike Stump11289f42009-09-09 15:08:12 +00003660 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003661 FD);
3662 }
3663 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003664 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003665 }
Mike Stump11289f42009-09-09 15:08:12 +00003666
John McCall9dd450b2009-09-21 23:43:11 +00003667 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003668 if (OPT->isObjCIdType()) {
3669 S += '@';
3670 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Steve Narofff0c86112009-10-28 22:03:49 +00003673 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3674 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3675 // Since this is a binary compatibility issue, need to consult with runtime
3676 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003677 S += '#';
3678 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
Chris Lattnere7cabb92009-07-13 00:10:46 +00003681 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003682 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003683 ExpandPointedToStructures,
3684 ExpandStructures, FD);
3685 if (FD || EncodingProperty) {
3686 // Note that we do extended encoding of protocol qualifer list
3687 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003688 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003689 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3690 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003691 S += '<';
3692 S += (*I)->getNameAsString();
3693 S += '>';
3694 }
3695 S += '"';
3696 }
3697 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003698 }
Mike Stump11289f42009-09-09 15:08:12 +00003699
Chris Lattnere7cabb92009-07-13 00:10:46 +00003700 QualType PointeeTy = OPT->getPointeeType();
3701 if (!EncodingProperty &&
3702 isa<TypedefType>(PointeeTy.getTypePtr())) {
3703 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003704 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003705 // {...};
3706 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003707 getObjCEncodingForTypeImpl(PointeeTy, S,
3708 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003709 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003710 return;
3711 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003712
3713 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003714 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003715 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003716 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003717 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3718 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003719 S += '<';
3720 S += (*I)->getNameAsString();
3721 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003722 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003723 S += '"';
3724 }
3725 return;
3726 }
Mike Stump11289f42009-09-09 15:08:12 +00003727
John McCalla9e6e8d2010-05-17 23:56:34 +00003728 // gcc just blithely ignores member pointers.
3729 // TODO: maybe there should be a mangling for these
3730 if (T->getAs<MemberPointerType>())
3731 return;
3732
Chris Lattnere7cabb92009-07-13 00:10:46 +00003733 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003734}
3735
Mike Stump11289f42009-09-09 15:08:12 +00003736void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003737 std::string& S) const {
3738 if (QT & Decl::OBJC_TQ_In)
3739 S += 'n';
3740 if (QT & Decl::OBJC_TQ_Inout)
3741 S += 'N';
3742 if (QT & Decl::OBJC_TQ_Out)
3743 S += 'o';
3744 if (QT & Decl::OBJC_TQ_Bycopy)
3745 S += 'O';
3746 if (QT & Decl::OBJC_TQ_Byref)
3747 S += 'R';
3748 if (QT & Decl::OBJC_TQ_Oneway)
3749 S += 'V';
3750}
3751
Chris Lattnere7cabb92009-07-13 00:10:46 +00003752void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003753 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003754
Anders Carlsson87c149b2007-10-11 01:00:40 +00003755 BuiltinVaListType = T;
3756}
3757
Chris Lattnere7cabb92009-07-13 00:10:46 +00003758void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003759 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003760}
3761
Chris Lattnere7cabb92009-07-13 00:10:46 +00003762void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003763 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003764}
3765
Chris Lattnere7cabb92009-07-13 00:10:46 +00003766void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003767 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003768}
3769
Chris Lattnere7cabb92009-07-13 00:10:46 +00003770void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003771 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003772}
3773
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003774void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003775 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003776 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003777
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003778 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003779}
3780
John McCalld28ae272009-12-02 08:04:21 +00003781/// \brief Retrieve the template name that corresponds to a non-empty
3782/// lookup.
John McCallad371252010-01-20 00:46:10 +00003783TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3784 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003785 unsigned size = End - Begin;
3786 assert(size > 1 && "set is not overloaded!");
3787
3788 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3789 size * sizeof(FunctionTemplateDecl*));
3790 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3791
3792 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003793 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003794 NamedDecl *D = *I;
3795 assert(isa<FunctionTemplateDecl>(D) ||
3796 (isa<UsingShadowDecl>(D) &&
3797 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3798 *Storage++ = D;
3799 }
3800
3801 return TemplateName(OT);
3802}
3803
Douglas Gregordc572a32009-03-30 22:58:21 +00003804/// \brief Retrieve the template name that represents a qualified
3805/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003806TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003807 bool TemplateKeyword,
3808 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003809 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003810 llvm::FoldingSetNodeID ID;
3811 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3812
3813 void *InsertPos = 0;
3814 QualifiedTemplateName *QTN =
3815 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3816 if (!QTN) {
3817 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3818 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3819 }
3820
3821 return TemplateName(QTN);
3822}
3823
3824/// \brief Retrieve the template name that represents a dependent
3825/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003826TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003827 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003828 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003829 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003830
3831 llvm::FoldingSetNodeID ID;
3832 DependentTemplateName::Profile(ID, NNS, Name);
3833
3834 void *InsertPos = 0;
3835 DependentTemplateName *QTN =
3836 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3837
3838 if (QTN)
3839 return TemplateName(QTN);
3840
3841 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3842 if (CanonNNS == NNS) {
3843 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3844 } else {
3845 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3846 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003847 DependentTemplateName *CheckQTN =
3848 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3849 assert(!CheckQTN && "Dependent type name canonicalization broken");
3850 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00003851 }
3852
3853 DependentTemplateNames.InsertNode(QTN, InsertPos);
3854 return TemplateName(QTN);
3855}
3856
Douglas Gregor71395fa2009-11-04 00:56:37 +00003857/// \brief Retrieve the template name that represents a dependent
3858/// template name such as \c MetaFun::template operator+.
3859TemplateName
3860ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3861 OverloadedOperatorKind Operator) {
3862 assert((!NNS || NNS->isDependent()) &&
3863 "Nested name specifier must be dependent");
3864
3865 llvm::FoldingSetNodeID ID;
3866 DependentTemplateName::Profile(ID, NNS, Operator);
3867
3868 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003869 DependentTemplateName *QTN
3870 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00003871
3872 if (QTN)
3873 return TemplateName(QTN);
3874
3875 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3876 if (CanonNNS == NNS) {
3877 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3878 } else {
3879 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3880 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003881
3882 DependentTemplateName *CheckQTN
3883 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3884 assert(!CheckQTN && "Dependent template name canonicalization broken");
3885 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00003886 }
3887
3888 DependentTemplateNames.InsertNode(QTN, InsertPos);
3889 return TemplateName(QTN);
3890}
3891
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003892/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00003893/// TargetInfo, produce the corresponding type. The unsigned @p Type
3894/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00003895CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003896 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00003897 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003898 case TargetInfo::SignedShort: return ShortTy;
3899 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3900 case TargetInfo::SignedInt: return IntTy;
3901 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3902 case TargetInfo::SignedLong: return LongTy;
3903 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3904 case TargetInfo::SignedLongLong: return LongLongTy;
3905 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3906 }
3907
3908 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00003909 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003910}
Ted Kremenek77c51b22008-07-24 23:58:27 +00003911
3912//===----------------------------------------------------------------------===//
3913// Type Predicates.
3914//===----------------------------------------------------------------------===//
3915
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003916/// isObjCNSObjectType - Return true if this is an NSObject object using
3917/// NSObject attribute on a c-style pointer type.
3918/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00003919/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003920///
3921bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3922 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3923 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003924 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003925 return true;
3926 }
Mike Stump11289f42009-09-09 15:08:12 +00003927 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003928}
3929
Fariborz Jahanian96207692009-02-18 21:49:28 +00003930/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3931/// garbage collection attribute.
3932///
John McCall8ccfcb52009-09-24 19:53:00 +00003933Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3934 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003935 if (getLangOptions().ObjC1 &&
3936 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00003937 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00003938 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00003939 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003940 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00003941 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00003942 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003943 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003944 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003945 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003946 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00003947 // Non-pointers have none gc'able attribute regardless of the attribute
3948 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00003949 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003950 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003951 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00003952 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003953}
3954
Chris Lattner49af6a42008-04-07 06:51:04 +00003955//===----------------------------------------------------------------------===//
3956// Type Compatibility Testing
3957//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00003958
Mike Stump11289f42009-09-09 15:08:12 +00003959/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00003960/// compatible.
3961static bool areCompatVectorTypes(const VectorType *LHS,
3962 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00003963 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00003964 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00003965 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00003966}
3967
Steve Naroff8e6aee52009-07-23 01:01:38 +00003968//===----------------------------------------------------------------------===//
3969// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3970//===----------------------------------------------------------------------===//
3971
3972/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3973/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00003974bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3975 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00003976 if (lProto == rProto)
3977 return true;
3978 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3979 E = rProto->protocol_end(); PI != E; ++PI)
3980 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3981 return true;
3982 return false;
3983}
3984
Steve Naroff8e6aee52009-07-23 01:01:38 +00003985/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3986/// return true if lhs's protocols conform to rhs's protocol; false
3987/// otherwise.
3988bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3989 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3990 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3991 return false;
3992}
3993
3994/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3995/// ObjCQualifiedIDType.
3996bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3997 bool compare) {
3998 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00003999 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004000 lhs->isObjCIdType() || lhs->isObjCClassType())
4001 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004002 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004003 rhs->isObjCIdType() || rhs->isObjCClassType())
4004 return true;
4005
4006 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004007 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004008
Steve Naroff8e6aee52009-07-23 01:01:38 +00004009 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004010
Steve Naroff8e6aee52009-07-23 01:01:38 +00004011 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004012 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004013 // make sure we check the class hierarchy.
4014 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4015 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4016 E = lhsQID->qual_end(); I != E; ++I) {
4017 // when comparing an id<P> on lhs with a static type on rhs,
4018 // see if static class implements all of id's protocols, directly or
4019 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004020 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004021 return false;
4022 }
4023 }
4024 // If there are no qualifiers and no interface, we have an 'id'.
4025 return true;
4026 }
Mike Stump11289f42009-09-09 15:08:12 +00004027 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004028 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4029 E = lhsQID->qual_end(); I != E; ++I) {
4030 ObjCProtocolDecl *lhsProto = *I;
4031 bool match = false;
4032
4033 // when comparing an id<P> on lhs with a static type on rhs,
4034 // see if static class implements all of id's protocols, directly or
4035 // through its super class and categories.
4036 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4037 E = rhsOPT->qual_end(); J != E; ++J) {
4038 ObjCProtocolDecl *rhsProto = *J;
4039 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4040 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4041 match = true;
4042 break;
4043 }
4044 }
Mike Stump11289f42009-09-09 15:08:12 +00004045 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004046 // make sure we check the class hierarchy.
4047 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4048 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4049 E = lhsQID->qual_end(); I != E; ++I) {
4050 // when comparing an id<P> on lhs with a static type on rhs,
4051 // see if static class implements all of id's protocols, directly or
4052 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004053 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004054 match = true;
4055 break;
4056 }
4057 }
4058 }
4059 if (!match)
4060 return false;
4061 }
Mike Stump11289f42009-09-09 15:08:12 +00004062
Steve Naroff8e6aee52009-07-23 01:01:38 +00004063 return true;
4064 }
Mike Stump11289f42009-09-09 15:08:12 +00004065
Steve Naroff8e6aee52009-07-23 01:01:38 +00004066 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4067 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4068
Mike Stump11289f42009-09-09 15:08:12 +00004069 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004070 lhs->getAsObjCInterfacePointerType()) {
4071 if (lhsOPT->qual_empty()) {
4072 bool match = false;
4073 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4074 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4075 E = rhsQID->qual_end(); I != E; ++I) {
4076 // when comparing an id<P> on lhs with a static type on rhs,
4077 // see if static class implements all of id's protocols, directly or
4078 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004079 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004080 match = true;
4081 break;
4082 }
4083 }
4084 if (!match)
4085 return false;
4086 }
4087 return true;
4088 }
Mike Stump11289f42009-09-09 15:08:12 +00004089 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004090 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4091 E = lhsOPT->qual_end(); I != E; ++I) {
4092 ObjCProtocolDecl *lhsProto = *I;
4093 bool match = false;
4094
4095 // when comparing an id<P> on lhs with a static type on rhs,
4096 // see if static class implements all of id's protocols, directly or
4097 // through its super class and categories.
4098 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4099 E = rhsQID->qual_end(); J != E; ++J) {
4100 ObjCProtocolDecl *rhsProto = *J;
4101 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4102 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4103 match = true;
4104 break;
4105 }
4106 }
4107 if (!match)
4108 return false;
4109 }
4110 return true;
4111 }
4112 return false;
4113}
4114
Eli Friedman47f77112008-08-22 00:56:42 +00004115/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004116/// compatible for assignment from RHS to LHS. This handles validation of any
4117/// protocol qualifiers on the LHS or RHS.
4118///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004119bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4120 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004121 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4122 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4123
Steve Naroff1329fa02009-07-15 18:40:39 +00004124 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004125 if (LHS->isObjCUnqualifiedIdOrClass() ||
4126 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004127 return true;
4128
John McCall8b07ec22010-05-15 11:32:37 +00004129 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004130 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4131 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004132 false);
4133
John McCall8b07ec22010-05-15 11:32:37 +00004134 // If we have 2 user-defined types, fall into that path.
4135 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004136 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004137
Steve Naroff8e6aee52009-07-23 01:01:38 +00004138 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004139}
4140
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004141/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4142/// for providing type-safty for objective-c pointers used to pass/return
4143/// arguments in block literals. When passed as arguments, passing 'A*' where
4144/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4145/// not OK. For the return type, the opposite is not OK.
4146bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4147 const ObjCObjectPointerType *LHSOPT,
4148 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004149 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004150 return true;
4151
4152 if (LHSOPT->isObjCBuiltinType()) {
4153 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4154 }
4155
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004156 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004157 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4158 QualType(RHSOPT,0),
4159 false);
4160
4161 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4162 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4163 if (LHS && RHS) { // We have 2 user-defined types.
4164 if (LHS != RHS) {
4165 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4166 return false;
4167 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4168 return true;
4169 }
4170 else
4171 return true;
4172 }
4173 return false;
4174}
4175
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004176/// getIntersectionOfProtocols - This routine finds the intersection of set
4177/// of protocols inherited from two distinct objective-c pointer objects.
4178/// It is used to build composite qualifier list of the composite type of
4179/// the conditional expression involving two objective-c pointer objects.
4180static
4181void getIntersectionOfProtocols(ASTContext &Context,
4182 const ObjCObjectPointerType *LHSOPT,
4183 const ObjCObjectPointerType *RHSOPT,
4184 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4185
John McCall8b07ec22010-05-15 11:32:37 +00004186 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4187 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4188 assert(LHS->getInterface() && "LHS must have an interface base");
4189 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004190
4191 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4192 unsigned LHSNumProtocols = LHS->getNumProtocols();
4193 if (LHSNumProtocols > 0)
4194 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4195 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004196 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004197 Context.CollectInheritedProtocols(LHS->getInterface(),
4198 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004199 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4200 LHSInheritedProtocols.end());
4201 }
4202
4203 unsigned RHSNumProtocols = RHS->getNumProtocols();
4204 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004205 ObjCProtocolDecl **RHSProtocols =
4206 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004207 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4208 if (InheritedProtocolSet.count(RHSProtocols[i]))
4209 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4210 }
4211 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004212 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004213 Context.CollectInheritedProtocols(RHS->getInterface(),
4214 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004215 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4216 RHSInheritedProtocols.begin(),
4217 E = RHSInheritedProtocols.end(); I != E; ++I)
4218 if (InheritedProtocolSet.count((*I)))
4219 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004220 }
4221}
4222
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004223/// areCommonBaseCompatible - Returns common base class of the two classes if
4224/// one found. Note that this is O'2 algorithm. But it will be called as the
4225/// last type comparison in a ?-exp of ObjC pointer types before a
4226/// warning is issued. So, its invokation is extremely rare.
4227QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004228 const ObjCObjectPointerType *Lptr,
4229 const ObjCObjectPointerType *Rptr) {
4230 const ObjCObjectType *LHS = Lptr->getObjectType();
4231 const ObjCObjectType *RHS = Rptr->getObjectType();
4232 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4233 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4234 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004235 return QualType();
4236
John McCall8b07ec22010-05-15 11:32:37 +00004237 while ((LDecl = LDecl->getSuperClass())) {
4238 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004239 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004240 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4241 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4242
4243 QualType Result = QualType(LHS, 0);
4244 if (!Protocols.empty())
4245 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4246 Result = getObjCObjectPointerType(Result);
4247 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004248 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004249 }
4250
4251 return QualType();
4252}
4253
John McCall8b07ec22010-05-15 11:32:37 +00004254bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4255 const ObjCObjectType *RHS) {
4256 assert(LHS->getInterface() && "LHS is not an interface type");
4257 assert(RHS->getInterface() && "RHS is not an interface type");
4258
Chris Lattner49af6a42008-04-07 06:51:04 +00004259 // Verify that the base decls are compatible: the RHS must be a subclass of
4260 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004261 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004262 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004263
Chris Lattner49af6a42008-04-07 06:51:04 +00004264 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4265 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004266 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004267 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004268
Chris Lattner49af6a42008-04-07 06:51:04 +00004269 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4270 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004271 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004272 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004273
John McCall8b07ec22010-05-15 11:32:37 +00004274 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4275 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004276 LHSPI != LHSPE; LHSPI++) {
4277 bool RHSImplementsProtocol = false;
4278
4279 // If the RHS doesn't implement the protocol on the left, the types
4280 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004281 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4282 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004283 RHSPI != RHSPE; RHSPI++) {
4284 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004285 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004286 break;
4287 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004288 }
4289 // FIXME: For better diagnostics, consider passing back the protocol name.
4290 if (!RHSImplementsProtocol)
4291 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004292 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004293 // The RHS implements all protocols listed on the LHS.
4294 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004295}
4296
Steve Naroffb7605152009-02-12 17:52:19 +00004297bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4298 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004299 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4300 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004301
Steve Naroff7cae42b2009-07-10 23:34:53 +00004302 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004303 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004304
4305 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4306 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004307}
4308
Mike Stump11289f42009-09-09 15:08:12 +00004309/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004310/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004311/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004312/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004313bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004314 if (getLangOptions().CPlusPlus)
4315 return hasSameType(LHS, RHS);
4316
Eli Friedman47f77112008-08-22 00:56:42 +00004317 return !mergeTypes(LHS, RHS).isNull();
4318}
4319
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004320bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4321 return !mergeTypes(LHS, RHS, true).isNull();
4322}
4323
4324QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4325 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004326 const FunctionType *lbase = lhs->getAs<FunctionType>();
4327 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004328 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4329 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004330 bool allLTypes = true;
4331 bool allRTypes = true;
4332
4333 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004334 QualType retType;
4335 if (OfBlockPointer)
4336 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4337 else
4338 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004339 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004340 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004341 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004342 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004343 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004344 // FIXME: double check this
4345 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4346 // rbase->getRegParmAttr() != 0 &&
4347 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004348 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4349 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004350 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4351 lbaseInfo.getRegParm();
4352 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4353 if (NoReturn != lbaseInfo.getNoReturn() ||
4354 RegParm != lbaseInfo.getRegParm())
4355 allLTypes = false;
4356 if (NoReturn != rbaseInfo.getNoReturn() ||
4357 RegParm != rbaseInfo.getRegParm())
4358 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004359 CallingConv lcc = lbaseInfo.getCC();
4360 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004361 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004362 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004363 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004364
Eli Friedman47f77112008-08-22 00:56:42 +00004365 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004366 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4367 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004368 unsigned lproto_nargs = lproto->getNumArgs();
4369 unsigned rproto_nargs = rproto->getNumArgs();
4370
4371 // Compatible functions must have the same number of arguments
4372 if (lproto_nargs != rproto_nargs)
4373 return QualType();
4374
4375 // Variadic and non-variadic functions aren't compatible
4376 if (lproto->isVariadic() != rproto->isVariadic())
4377 return QualType();
4378
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004379 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4380 return QualType();
4381
Eli Friedman47f77112008-08-22 00:56:42 +00004382 // Check argument compatibility
4383 llvm::SmallVector<QualType, 10> types;
4384 for (unsigned i = 0; i < lproto_nargs; i++) {
4385 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4386 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004387 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004388 if (argtype.isNull()) return QualType();
4389 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004390 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4391 allLTypes = false;
4392 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4393 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004394 }
4395 if (allLTypes) return lhs;
4396 if (allRTypes) return rhs;
4397 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004398 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004399 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004400 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004401 }
4402
4403 if (lproto) allRTypes = false;
4404 if (rproto) allLTypes = false;
4405
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004406 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004407 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004408 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004409 if (proto->isVariadic()) return QualType();
4410 // Check that the types are compatible with the types that
4411 // would result from default argument promotions (C99 6.7.5.3p15).
4412 // The only types actually affected are promotable integer
4413 // types and floats, which would be passed as a different
4414 // type depending on whether the prototype is visible.
4415 unsigned proto_nargs = proto->getNumArgs();
4416 for (unsigned i = 0; i < proto_nargs; ++i) {
4417 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004418
4419 // Look at the promotion type of enum types, since that is the type used
4420 // to pass enum values.
4421 if (const EnumType *Enum = argTy->getAs<EnumType>())
4422 argTy = Enum->getDecl()->getPromotionType();
4423
Eli Friedman47f77112008-08-22 00:56:42 +00004424 if (argTy->isPromotableIntegerType() ||
4425 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4426 return QualType();
4427 }
4428
4429 if (allLTypes) return lhs;
4430 if (allRTypes) return rhs;
4431 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004432 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004433 proto->getTypeQuals(),
4434 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004435 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004436 }
4437
4438 if (allLTypes) return lhs;
4439 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004440 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004441 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004442}
4443
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004444QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4445 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004446 // C++ [expr]: If an expression initially has the type "reference to T", the
4447 // type is adjusted to "T" prior to any further analysis, the expression
4448 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004449 // expression is an lvalue unless the reference is an rvalue reference and
4450 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004451 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4452 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4453
Eli Friedman47f77112008-08-22 00:56:42 +00004454 QualType LHSCan = getCanonicalType(LHS),
4455 RHSCan = getCanonicalType(RHS);
4456
4457 // If two types are identical, they are compatible.
4458 if (LHSCan == RHSCan)
4459 return LHS;
4460
John McCall8ccfcb52009-09-24 19:53:00 +00004461 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004462 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4463 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004464 if (LQuals != RQuals) {
4465 // If any of these qualifiers are different, we have a type
4466 // mismatch.
4467 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4468 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4469 return QualType();
4470
4471 // Exactly one GC qualifier difference is allowed: __strong is
4472 // okay if the other type has no GC qualifier but is an Objective
4473 // C object pointer (i.e. implicitly strong by default). We fix
4474 // this by pretending that the unqualified type was actually
4475 // qualified __strong.
4476 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4477 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4478 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4479
4480 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4481 return QualType();
4482
4483 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4484 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4485 }
4486 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4487 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4488 }
Eli Friedman47f77112008-08-22 00:56:42 +00004489 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004490 }
4491
4492 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004493
Eli Friedmandcca6332009-06-01 01:22:52 +00004494 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4495 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004496
Chris Lattnerfd652912008-01-14 05:45:46 +00004497 // We want to consider the two function types to be the same for these
4498 // comparisons, just force one to the other.
4499 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4500 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004501
4502 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004503 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4504 LHSClass = Type::ConstantArray;
4505 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4506 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004507
John McCall8b07ec22010-05-15 11:32:37 +00004508 // ObjCInterfaces are just specialized ObjCObjects.
4509 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4510 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4511
Nate Begemance4d7fc2008-04-18 23:10:10 +00004512 // Canonicalize ExtVector -> Vector.
4513 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4514 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004515
Chris Lattner95554662008-04-07 05:43:21 +00004516 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004517 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004518 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004519 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004520 // Compatibility is based on the underlying type, not the promotion
4521 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004522 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004523 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4524 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004525 }
John McCall9dd450b2009-09-21 23:43:11 +00004526 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004527 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4528 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004529 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004530
Eli Friedman47f77112008-08-22 00:56:42 +00004531 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004532 }
Eli Friedman47f77112008-08-22 00:56:42 +00004533
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004534 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004535 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004536#define TYPE(Class, Base)
4537#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004538#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004539#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4540#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4541#include "clang/AST/TypeNodes.def"
4542 assert(false && "Non-canonical and dependent types shouldn't get here");
4543 return QualType();
4544
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004545 case Type::LValueReference:
4546 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004547 case Type::MemberPointer:
4548 assert(false && "C++ should never be in mergeTypes");
4549 return QualType();
4550
John McCall8b07ec22010-05-15 11:32:37 +00004551 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004552 case Type::IncompleteArray:
4553 case Type::VariableArray:
4554 case Type::FunctionProto:
4555 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004556 assert(false && "Types are eliminated above");
4557 return QualType();
4558
Chris Lattnerfd652912008-01-14 05:45:46 +00004559 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004560 {
4561 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004562 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4563 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004564 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4565 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004566 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004567 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004568 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004569 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004570 return getPointerType(ResultType);
4571 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004572 case Type::BlockPointer:
4573 {
4574 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004575 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4576 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004577 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004578 if (ResultType.isNull()) return QualType();
4579 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4580 return LHS;
4581 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4582 return RHS;
4583 return getBlockPointerType(ResultType);
4584 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004585 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004586 {
4587 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4588 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4589 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4590 return QualType();
4591
4592 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4593 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4594 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4595 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004596 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4597 return LHS;
4598 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4599 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004600 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4601 ArrayType::ArraySizeModifier(), 0);
4602 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4603 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004604 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4605 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004606 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4607 return LHS;
4608 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4609 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004610 if (LVAT) {
4611 // FIXME: This isn't correct! But tricky to implement because
4612 // the array's size has to be the size of LHS, but the type
4613 // has to be different.
4614 return LHS;
4615 }
4616 if (RVAT) {
4617 // FIXME: This isn't correct! But tricky to implement because
4618 // the array's size has to be the size of RHS, but the type
4619 // has to be different.
4620 return RHS;
4621 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004622 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4623 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004624 return getIncompleteArrayType(ResultType,
4625 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004626 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004627 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004628 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004629 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004630 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004631 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004632 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004633 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004634 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004635 case Type::Complex:
4636 // Distinct complex types are incompatible.
4637 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004638 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004639 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004640 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4641 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004642 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004643 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004644 case Type::ObjCObject: {
4645 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004646 // FIXME: This should be type compatibility, e.g. whether
4647 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004648 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4649 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4650 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004651 return LHS;
4652
Eli Friedman47f77112008-08-22 00:56:42 +00004653 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004654 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004655 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004656 if (OfBlockPointer) {
4657 if (canAssignObjCInterfacesInBlockPointer(
4658 LHS->getAs<ObjCObjectPointerType>(),
4659 RHS->getAs<ObjCObjectPointerType>()))
4660 return LHS;
4661 return QualType();
4662 }
John McCall9dd450b2009-09-21 23:43:11 +00004663 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4664 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004665 return LHS;
4666
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004667 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004668 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004669 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004670
4671 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004672}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004673
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004674/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4675/// 'RHS' attributes and returns the merged version; including for function
4676/// return types.
4677QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4678 QualType LHSCan = getCanonicalType(LHS),
4679 RHSCan = getCanonicalType(RHS);
4680 // If two types are identical, they are compatible.
4681 if (LHSCan == RHSCan)
4682 return LHS;
4683 if (RHSCan->isFunctionType()) {
4684 if (!LHSCan->isFunctionType())
4685 return QualType();
4686 QualType OldReturnType =
4687 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4688 QualType NewReturnType =
4689 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4690 QualType ResReturnType =
4691 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4692 if (ResReturnType.isNull())
4693 return QualType();
4694 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4695 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4696 // In either case, use OldReturnType to build the new function type.
4697 const FunctionType *F = LHS->getAs<FunctionType>();
4698 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4699 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4700 QualType ResultType
4701 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4702 FPT->getNumArgs(), FPT->isVariadic(),
4703 FPT->getTypeQuals(),
4704 FPT->hasExceptionSpec(),
4705 FPT->hasAnyExceptionSpec(),
4706 FPT->getNumExceptions(),
4707 FPT->exception_begin(),
4708 Info);
4709 return ResultType;
4710 }
4711 }
4712 return QualType();
4713 }
4714
4715 // If the qualifiers are different, the types can still be merged.
4716 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4717 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4718 if (LQuals != RQuals) {
4719 // If any of these qualifiers are different, we have a type mismatch.
4720 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4721 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4722 return QualType();
4723
4724 // Exactly one GC qualifier difference is allowed: __strong is
4725 // okay if the other type has no GC qualifier but is an Objective
4726 // C object pointer (i.e. implicitly strong by default). We fix
4727 // this by pretending that the unqualified type was actually
4728 // qualified __strong.
4729 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4730 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4731 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4732
4733 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4734 return QualType();
4735
4736 if (GC_L == Qualifiers::Strong)
4737 return LHS;
4738 if (GC_R == Qualifiers::Strong)
4739 return RHS;
4740 return QualType();
4741 }
4742
4743 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4744 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4745 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4746 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4747 if (ResQT == LHSBaseQT)
4748 return LHS;
4749 if (ResQT == RHSBaseQT)
4750 return RHS;
4751 }
4752 return QualType();
4753}
4754
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004755//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004756// Integer Predicates
4757//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004758
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004759unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004760 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004761 return 1;
John McCall56774992009-12-09 09:09:27 +00004762 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004763 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004764 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004765 return (unsigned)getTypeSize(T);
4766}
4767
4768QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4769 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004770
4771 // Turn <4 x signed int> -> <4 x unsigned int>
4772 if (const VectorType *VTy = T->getAs<VectorType>())
4773 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004774 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004775
4776 // For enums, we return the unsigned version of the base type.
4777 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004778 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004779
4780 const BuiltinType *BTy = T->getAs<BuiltinType>();
4781 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004782 switch (BTy->getKind()) {
4783 case BuiltinType::Char_S:
4784 case BuiltinType::SChar:
4785 return UnsignedCharTy;
4786 case BuiltinType::Short:
4787 return UnsignedShortTy;
4788 case BuiltinType::Int:
4789 return UnsignedIntTy;
4790 case BuiltinType::Long:
4791 return UnsignedLongTy;
4792 case BuiltinType::LongLong:
4793 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004794 case BuiltinType::Int128:
4795 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004796 default:
4797 assert(0 && "Unexpected signed integer type");
4798 return QualType();
4799 }
4800}
4801
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004802ExternalASTSource::~ExternalASTSource() { }
4803
4804void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004805
4806
4807//===----------------------------------------------------------------------===//
4808// Builtin Type Computation
4809//===----------------------------------------------------------------------===//
4810
4811/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4812/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004813static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004814 ASTContext::GetBuiltinTypeError &Error,
4815 bool AllowTypeModifiers = true) {
4816 // Modifiers.
4817 int HowLong = 0;
4818 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004819
Chris Lattnerecd79c62009-06-14 00:45:47 +00004820 // Read the modifiers first.
4821 bool Done = false;
4822 while (!Done) {
4823 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004824 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004825 case 'S':
4826 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4827 assert(!Signed && "Can't use 'S' modifier multiple times!");
4828 Signed = true;
4829 break;
4830 case 'U':
4831 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4832 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4833 Unsigned = true;
4834 break;
4835 case 'L':
4836 assert(HowLong <= 2 && "Can't have LLLL modifier");
4837 ++HowLong;
4838 break;
4839 }
4840 }
4841
4842 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004843
Chris Lattnerecd79c62009-06-14 00:45:47 +00004844 // Read the base type.
4845 switch (*Str++) {
4846 default: assert(0 && "Unknown builtin type letter!");
4847 case 'v':
4848 assert(HowLong == 0 && !Signed && !Unsigned &&
4849 "Bad modifiers used with 'v'!");
4850 Type = Context.VoidTy;
4851 break;
4852 case 'f':
4853 assert(HowLong == 0 && !Signed && !Unsigned &&
4854 "Bad modifiers used with 'f'!");
4855 Type = Context.FloatTy;
4856 break;
4857 case 'd':
4858 assert(HowLong < 2 && !Signed && !Unsigned &&
4859 "Bad modifiers used with 'd'!");
4860 if (HowLong)
4861 Type = Context.LongDoubleTy;
4862 else
4863 Type = Context.DoubleTy;
4864 break;
4865 case 's':
4866 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4867 if (Unsigned)
4868 Type = Context.UnsignedShortTy;
4869 else
4870 Type = Context.ShortTy;
4871 break;
4872 case 'i':
4873 if (HowLong == 3)
4874 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4875 else if (HowLong == 2)
4876 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4877 else if (HowLong == 1)
4878 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4879 else
4880 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4881 break;
4882 case 'c':
4883 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4884 if (Signed)
4885 Type = Context.SignedCharTy;
4886 else if (Unsigned)
4887 Type = Context.UnsignedCharTy;
4888 else
4889 Type = Context.CharTy;
4890 break;
4891 case 'b': // boolean
4892 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4893 Type = Context.BoolTy;
4894 break;
4895 case 'z': // size_t.
4896 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4897 Type = Context.getSizeType();
4898 break;
4899 case 'F':
4900 Type = Context.getCFConstantStringType();
4901 break;
4902 case 'a':
4903 Type = Context.getBuiltinVaListType();
4904 assert(!Type.isNull() && "builtin va list type not initialized!");
4905 break;
4906 case 'A':
4907 // This is a "reference" to a va_list; however, what exactly
4908 // this means depends on how va_list is defined. There are two
4909 // different kinds of va_list: ones passed by value, and ones
4910 // passed by reference. An example of a by-value va_list is
4911 // x86, where va_list is a char*. An example of by-ref va_list
4912 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4913 // we want this argument to be a char*&; for x86-64, we want
4914 // it to be a __va_list_tag*.
4915 Type = Context.getBuiltinVaListType();
4916 assert(!Type.isNull() && "builtin va list type not initialized!");
4917 if (Type->isArrayType()) {
4918 Type = Context.getArrayDecayedType(Type);
4919 } else {
4920 Type = Context.getLValueReferenceType(Type);
4921 }
4922 break;
4923 case 'V': {
4924 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004925 unsigned NumElements = strtoul(Str, &End, 10);
4926 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004927
Chris Lattnerecd79c62009-06-14 00:45:47 +00004928 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004929
Chris Lattnerecd79c62009-06-14 00:45:47 +00004930 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004931 // FIXME: Don't know what to do about AltiVec.
4932 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004933 break;
4934 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004935 case 'X': {
4936 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4937 Type = Context.getComplexType(ElementType);
4938 break;
4939 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004940 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004941 Type = Context.getFILEType();
4942 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004943 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004944 return QualType();
4945 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004946 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004947 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004948 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004949 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004950 else
4951 Type = Context.getjmp_bufType();
4952
Mike Stump2adb4da2009-07-28 23:47:15 +00004953 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004954 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004955 return QualType();
4956 }
4957 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
Chris Lattnerecd79c62009-06-14 00:45:47 +00004960 if (!AllowTypeModifiers)
4961 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004962
Chris Lattnerecd79c62009-06-14 00:45:47 +00004963 Done = false;
4964 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004965 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004966 default: Done = true; --Str; break;
4967 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004968 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004969 {
4970 // Both pointers and references can have their pointee types
4971 // qualified with an address space.
4972 char *End;
4973 unsigned AddrSpace = strtoul(Str, &End, 10);
4974 if (End != Str && AddrSpace != 0) {
4975 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4976 Str = End;
4977 }
4978 }
4979 if (c == '*')
4980 Type = Context.getPointerType(Type);
4981 else
4982 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004983 break;
4984 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4985 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00004986 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00004987 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00004988 case 'D':
4989 Type = Context.getVolatileType(Type);
4990 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004991 }
4992 }
Mike Stump11289f42009-09-09 15:08:12 +00004993
Chris Lattnerecd79c62009-06-14 00:45:47 +00004994 return Type;
4995}
4996
4997/// GetBuiltinType - Return the type for the specified builtin.
4998QualType ASTContext::GetBuiltinType(unsigned id,
4999 GetBuiltinTypeError &Error) {
5000 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005001
Chris Lattnerecd79c62009-06-14 00:45:47 +00005002 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005003
Chris Lattnerecd79c62009-06-14 00:45:47 +00005004 Error = GE_None;
5005 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5006 if (Error != GE_None)
5007 return QualType();
5008 while (TypeStr[0] && TypeStr[0] != '.') {
5009 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5010 if (Error != GE_None)
5011 return QualType();
5012
5013 // Do array -> pointer decay. The builtin should use the decayed type.
5014 if (Ty->isArrayType())
5015 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005016
Chris Lattnerecd79c62009-06-14 00:45:47 +00005017 ArgTypes.push_back(Ty);
5018 }
5019
5020 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5021 "'.' should only occur at end of builtin type list!");
5022
5023 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5024 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5025 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005026
5027 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005028 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005029 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005030 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005031}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005032
5033QualType
5034ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5035 // Perform the usual unary conversions. We do this early so that
5036 // integral promotions to "int" can allow us to exit early, in the
5037 // lhs == rhs check. Also, for conversion purposes, we ignore any
5038 // qualifiers. For example, "const float" and "float" are
5039 // equivalent.
5040 if (lhs->isPromotableIntegerType())
5041 lhs = getPromotedIntegerType(lhs);
5042 else
5043 lhs = lhs.getUnqualifiedType();
5044 if (rhs->isPromotableIntegerType())
5045 rhs = getPromotedIntegerType(rhs);
5046 else
5047 rhs = rhs.getUnqualifiedType();
5048
5049 // If both types are identical, no conversion is needed.
5050 if (lhs == rhs)
5051 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005052
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005053 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5054 // The caller can deal with this (e.g. pointer + int).
5055 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5056 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005057
5058 // At this point, we have two different arithmetic types.
5059
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005060 // Handle complex types first (C99 6.3.1.8p1).
5061 if (lhs->isComplexType() || rhs->isComplexType()) {
5062 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005063 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005064 // convert the rhs to the lhs complex type.
5065 return lhs;
5066 }
Mike Stump11289f42009-09-09 15:08:12 +00005067 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005068 // convert the lhs to the rhs complex type.
5069 return rhs;
5070 }
5071 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005072 // When both operands are complex, the shorter operand is converted to the
5073 // type of the longer, and that is the type of the result. This corresponds
5074 // to what is done when combining two real floating-point operands.
5075 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005076 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005077 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005078 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005079 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005080 // "double _Complex" is promoted to "long double _Complex".
5081 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005082
5083 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005084 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005085 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005086 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005087 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005088 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5089 // domains match. This is a requirement for our implementation, C99
5090 // does not require this promotion.
5091 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5092 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5093 return rhs;
5094 } else { // handle "_Complex double, double".
5095 return lhs;
5096 }
5097 }
5098 return lhs; // The domain/size match exactly.
5099 }
5100 // Now handle "real" floating types (i.e. float, double, long double).
5101 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5102 // if we have an integer operand, the result is the real floating type.
5103 if (rhs->isIntegerType()) {
5104 // convert rhs to the lhs floating point type.
5105 return lhs;
5106 }
5107 if (rhs->isComplexIntegerType()) {
5108 // convert rhs to the complex floating point type.
5109 return getComplexType(lhs);
5110 }
5111 if (lhs->isIntegerType()) {
5112 // convert lhs to the rhs floating point type.
5113 return rhs;
5114 }
Mike Stump11289f42009-09-09 15:08:12 +00005115 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005116 // convert lhs to the complex floating point type.
5117 return getComplexType(rhs);
5118 }
5119 // We have two real floating types, float/complex combos were handled above.
5120 // Convert the smaller operand to the bigger result.
5121 int result = getFloatingTypeOrder(lhs, rhs);
5122 if (result > 0) // convert the rhs
5123 return lhs;
5124 assert(result < 0 && "illegal float comparison");
5125 return rhs; // convert the lhs
5126 }
5127 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5128 // Handle GCC complex int extension.
5129 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5130 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5131
5132 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005133 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005134 rhsComplexInt->getElementType()) >= 0)
5135 return lhs; // convert the rhs
5136 return rhs;
5137 } else if (lhsComplexInt && rhs->isIntegerType()) {
5138 // convert the rhs to the lhs complex type.
5139 return lhs;
5140 } else if (rhsComplexInt && lhs->isIntegerType()) {
5141 // convert the lhs to the rhs complex type.
5142 return rhs;
5143 }
5144 }
5145 // Finally, we have two differing integer types.
5146 // The rules for this case are in C99 6.3.1.8
5147 int compare = getIntegerTypeOrder(lhs, rhs);
5148 bool lhsSigned = lhs->isSignedIntegerType(),
5149 rhsSigned = rhs->isSignedIntegerType();
5150 QualType destType;
5151 if (lhsSigned == rhsSigned) {
5152 // Same signedness; use the higher-ranked type
5153 destType = compare >= 0 ? lhs : rhs;
5154 } else if (compare != (lhsSigned ? 1 : -1)) {
5155 // The unsigned type has greater than or equal rank to the
5156 // signed type, so use the unsigned type
5157 destType = lhsSigned ? rhs : lhs;
5158 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5159 // The two types are different widths; if we are here, that
5160 // means the signed type is larger than the unsigned type, so
5161 // use the signed type.
5162 destType = lhsSigned ? lhs : rhs;
5163 } else {
5164 // The signed type is higher-ranked than the unsigned type,
5165 // but isn't actually any bigger (like unsigned int and long
5166 // on most 32-bit systems). Use the unsigned type corresponding
5167 // to the signed type.
5168 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5169 }
5170 return destType;
5171}