blob: 5cd52396a80b643dc31f55fd05b27f0d42a75e68 [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"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
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),
Mike Stumpa4de80b2009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump11289f42009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump11289f42009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall9f57c292009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000056}
57
Chris Lattnerd5973eb2006-11-12 00:53:46 +000058ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
62
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000063 if (FreeMemory) {
64 // Deallocate all the types.
65 while (!Types.empty()) {
66 Types.back()->Destroy(*this);
67 Types.pop_back();
68 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000069
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000070 for (llvm::FoldingSet<ExtQuals>::iterator
71 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
72 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000073 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000074 }
75 }
76
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000077 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
78 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
79 // Increment in loop to prevent using deallocated memory.
80 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
81 delete R;
82 }
83
84 for (llvm::DenseMap<const ObjCContainerDecl*,
85 const ASTRecordLayout*>::iterator
86 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
87 // Increment in loop to prevent using deallocated memory.
88 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
89 delete R;
Nuno Lopese013c7f2008-12-17 22:30:25 +000090 }
91
Douglas Gregorf21eb492009-03-26 23:50:42 +000092 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +000093 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
94 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +000095 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000096 NNS != NNSEnd; ) {
97 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +000098 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000099 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000100
101 if (GlobalNestedNameSpecifier)
102 GlobalNestedNameSpecifier->Destroy(*this);
103
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000104 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000105}
106
Mike Stump11289f42009-09-09 15:08:12 +0000107void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000108ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
109 ExternalSource.reset(Source.take());
110}
111
Chris Lattner4eb445d2007-01-26 01:27:23 +0000112void ASTContext::PrintStats() const {
113 fprintf(stderr, "*** AST Context Stats:\n");
114 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000115
Douglas Gregora30d0462009-05-26 14:40:08 +0000116 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000117#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000118#define ABSTRACT_TYPE(Name, Parent)
119#include "clang/AST/TypeNodes.def"
120 0 // Extra
121 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000122
Chris Lattner4eb445d2007-01-26 01:27:23 +0000123 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
124 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000125 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000126 }
127
Douglas Gregora30d0462009-05-26 14:40:08 +0000128 unsigned Idx = 0;
129 unsigned TotalBytes = 0;
130#define TYPE(Name, Parent) \
131 if (counts[Idx]) \
132 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
133 TotalBytes += counts[Idx] * sizeof(Name##Type); \
134 ++Idx;
135#define ABSTRACT_TYPE(Name, Parent)
136#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000137
Douglas Gregora30d0462009-05-26 14:40:08 +0000138 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000139
140 if (ExternalSource.get()) {
141 fprintf(stderr, "\n");
142 ExternalSource->PrintStats();
143 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000144}
145
146
John McCall48f2d582009-10-23 23:03:21 +0000147void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000148 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000149 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000150 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000151}
152
Chris Lattner970e54e2006-11-12 00:37:36 +0000153void ASTContext::InitBuiltinTypes() {
154 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner970e54e2006-11-12 00:37:36 +0000156 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000157 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000158
Chris Lattner970e54e2006-11-12 00:37:36 +0000159 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000160 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000161 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000162 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000163 InitBuiltinType(CharTy, BuiltinType::Char_S);
164 else
165 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000166 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000167 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
168 InitBuiltinType(ShortTy, BuiltinType::Short);
169 InitBuiltinType(IntTy, BuiltinType::Int);
170 InitBuiltinType(LongTy, BuiltinType::Long);
171 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattner970e54e2006-11-12 00:37:36 +0000173 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000174 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
175 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
176 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
177 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
178 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattner970e54e2006-11-12 00:37:36 +0000180 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000181 InitBuiltinType(FloatTy, BuiltinType::Float);
182 InitBuiltinType(DoubleTy, BuiltinType::Double);
183 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000184
Chris Lattnerf122cef2009-04-30 02:43:43 +0000185 // GNU extension, 128-bit integers.
186 InitBuiltinType(Int128Ty, BuiltinType::Int128);
187 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
188
Chris Lattner007cb022009-02-26 23:43:47 +0000189 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
190 InitBuiltinType(WCharTy, BuiltinType::WChar);
191 else // C99
192 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000193
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000194 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
195 InitBuiltinType(Char16Ty, BuiltinType::Char16);
196 else // C99
197 Char16Ty = getFromTargetType(Target.getChar16Type());
198
199 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
200 InitBuiltinType(Char32Ty, BuiltinType::Char32);
201 else // C99
202 Char32Ty = getFromTargetType(Target.getChar32Type());
203
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000205 InitBuiltinType(OverloadTy, BuiltinType::Overload);
206
207 // Placeholder type for type-dependent expressions whose type is
208 // completely unknown. No code should ever check a type against
209 // DependentTy and users should never see it; however, it is here to
210 // help diagnose failures to properly check for type-dependent
211 // expressions.
212 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213
Mike Stump11289f42009-09-09 15:08:12 +0000214 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000215 // not yet been deduced.
216 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000217
Chris Lattner970e54e2006-11-12 00:37:36 +0000218 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000219 FloatComplexTy = getComplexType(FloatTy);
220 DoubleComplexTy = getComplexType(DoubleTy);
221 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222
Steve Naroff66e9f332007-10-15 14:41:52 +0000223 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000224
Steve Naroff1329fa02009-07-15 18:40:39 +0000225 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
226 ObjCIdTypedefType = QualType();
227 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000228 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000229
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000230 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000231 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
232 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000233 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000234
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000235 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000236
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000237 // void * type
238 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000239
240 // nullptr type (C++0x 2.14.7)
241 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000242}
243
Douglas Gregor86d142a2009-10-08 07:24:58 +0000244MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000245ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000246 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000247 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000248 = InstantiatedFromStaticDataMember.find(Var);
249 if (Pos == InstantiatedFromStaticDataMember.end())
250 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000251
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000252 return Pos->second;
253}
254
Mike Stump11289f42009-09-09 15:08:12 +0000255void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000256ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
257 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000258 assert(Inst->isStaticDataMember() && "Not a static data member");
259 assert(Tmpl->isStaticDataMember() && "Not a static data member");
260 assert(!InstantiatedFromStaticDataMember[Inst] &&
261 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000262 InstantiatedFromStaticDataMember[Inst]
263 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000264}
265
John McCalle61f2ba2009-11-18 02:36:19 +0000266NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000267ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000268 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000269 = InstantiatedFromUsingDecl.find(UUD);
270 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000271 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000272
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000273 return Pos->second;
274}
275
276void
John McCallb96ec562009-12-04 22:46:56 +0000277ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
278 assert((isa<UsingDecl>(Pattern) ||
279 isa<UnresolvedUsingValueDecl>(Pattern) ||
280 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
281 "pattern decl is not a using decl");
282 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
283 InstantiatedFromUsingDecl[Inst] = Pattern;
284}
285
286UsingShadowDecl *
287ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
288 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
289 = InstantiatedFromUsingShadowDecl.find(Inst);
290 if (Pos == InstantiatedFromUsingShadowDecl.end())
291 return 0;
292
293 return Pos->second;
294}
295
296void
297ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
298 UsingShadowDecl *Pattern) {
299 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
300 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000301}
302
Anders Carlsson5da84842009-09-01 04:26:58 +0000303FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
304 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
305 = InstantiatedFromUnnamedFieldDecl.find(Field);
306 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
307 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000308
Anders Carlsson5da84842009-09-01 04:26:58 +0000309 return Pos->second;
310}
311
312void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
313 FieldDecl *Tmpl) {
314 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
315 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
316 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
317 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000318
Anders Carlsson5da84842009-09-01 04:26:58 +0000319 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
320}
321
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000322namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000323 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000324 : std::binary_function<SourceRange, SourceRange, bool> {
325 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000326
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000327 public:
328 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000329
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000330 bool operator()(SourceRange X, SourceRange Y) {
331 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
332 }
333 };
334}
335
336/// \brief Determine whether the given comment is a Doxygen-style comment.
337///
338/// \param Start the start of the comment text.
339///
340/// \param End the end of the comment text.
341///
342/// \param Member whether we want to check whether this is a member comment
343/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
344/// we only return true when we find a non-member comment.
Mike Stump11289f42009-09-09 15:08:12 +0000345static bool
346isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000347 bool Member = false) {
Mike Stump11289f42009-09-09 15:08:12 +0000348 const char *BufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000349 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
350 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
351 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000352
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000353 if (End - Start < 4)
354 return false;
355
356 assert(Start[0] == '/' && "Not a comment?");
357 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
358 return false;
359 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
360 return false;
361
362 return (Start[3] == '<') == Member;
363}
364
365/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump11289f42009-09-09 15:08:12 +0000366/// it has one.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000367const char *ASTContext::getCommentForDecl(const Decl *D) {
368 if (!D)
369 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000371 // Check whether we have cached a comment string for this declaration
372 // already.
Mike Stump11289f42009-09-09 15:08:12 +0000373 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000374 = DeclComments.find(D);
375 if (Pos != DeclComments.end())
376 return Pos->second.c_str();
377
Mike Stump11289f42009-09-09 15:08:12 +0000378 // If we have an external AST source and have not yet loaded comments from
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000379 // that source, do so now.
380 if (ExternalSource && !LoadedExternalComments) {
381 std::vector<SourceRange> LoadedComments;
382 ExternalSource->ReadComments(LoadedComments);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000384 if (!LoadedComments.empty())
385 Comments.insert(Comments.begin(), LoadedComments.begin(),
386 LoadedComments.end());
Mike Stump11289f42009-09-09 15:08:12 +0000387
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000388 LoadedExternalComments = true;
389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
391 // If there are no comments anywhere, we won't find anything.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000392 if (Comments.empty())
393 return 0;
394
395 // If the declaration doesn't map directly to a location in a file, we
396 // can't find the comment.
397 SourceLocation DeclStartLoc = D->getLocStart();
398 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
399 return 0;
400
401 // Find the comment that occurs just before this declaration.
402 std::vector<SourceRange>::iterator LastComment
Mike Stump11289f42009-09-09 15:08:12 +0000403 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000404 SourceRange(DeclStartLoc),
405 BeforeInTranslationUnit(&SourceMgr));
Mike Stump11289f42009-09-09 15:08:12 +0000406
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000407 // Decompose the location for the start of the declaration and find the
408 // beginning of the file buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000409 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000410 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000411 const char *FileBufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000412 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump11289f42009-09-09 15:08:12 +0000413
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000414 // First check whether we have a comment for a member.
415 if (LastComment != Comments.end() &&
416 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
417 isDoxygenComment(SourceMgr, *LastComment, true)) {
418 std::pair<FileID, unsigned> LastCommentEndDecomp
419 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
420 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
421 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump11289f42009-09-09 15:08:12 +0000422 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000423 LastCommentEndDecomp.second)) {
424 // The Doxygen member comment comes after the declaration starts and
425 // is on the same line and in the same file as the declaration. This
426 // is the comment we want.
427 std::string &Result = DeclComments[D];
Mike Stump11289f42009-09-09 15:08:12 +0000428 Result.append(FileBufferStart +
429 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000430 FileBufferStart + LastCommentEndDecomp.second + 1);
431 return Result.c_str();
432 }
433 }
Mike Stump11289f42009-09-09 15:08:12 +0000434
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000435 if (LastComment == Comments.begin())
436 return 0;
437 --LastComment;
438
439 // Decompose the end of the comment.
440 std::pair<FileID, unsigned> LastCommentEndDecomp
441 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000443 // If the comment and the declaration aren't in the same file, then they
444 // aren't related.
445 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
446 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000447
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000448 // Check that we actually have a Doxygen comment.
449 if (!isDoxygenComment(SourceMgr, *LastComment))
450 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000451
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000452 // Compute the starting line for the declaration and for the end of the
453 // comment (this is expensive).
Mike Stump11289f42009-09-09 15:08:12 +0000454 unsigned DeclStartLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000455 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
456 unsigned CommentEndLine
Mike Stump11289f42009-09-09 15:08:12 +0000457 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000458 LastCommentEndDecomp.second);
Mike Stump11289f42009-09-09 15:08:12 +0000459
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000460 // If the comment does not end on the line prior to the declaration, then
461 // the comment is not associated with the declaration at all.
462 if (CommentEndLine + 1 != DeclStartLine)
463 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000464
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000465 // We have a comment, but there may be more comments on the previous lines.
466 // Keep looking so long as the comments are still Doxygen comments and are
467 // still adjacent.
Mike Stump11289f42009-09-09 15:08:12 +0000468 unsigned ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000469 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
470 std::vector<SourceRange>::iterator FirstComment = LastComment;
471 while (FirstComment != Comments.begin()) {
472 // Look at the previous comment
473 --FirstComment;
474 std::pair<FileID, unsigned> Decomp
475 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000476
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000477 // If this previous comment is in a different file, we're done.
478 if (Decomp.first != DeclStartDecomp.first) {
479 ++FirstComment;
480 break;
481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000483 // If this comment is not a Doxygen comment, we're done.
484 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
485 ++FirstComment;
486 break;
487 }
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000489 // If the line number is not what we expected, we're done.
490 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
491 if (Line != ExpectedLine) {
492 ++FirstComment;
493 break;
494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000496 // Set the next expected line number.
Mike Stump11289f42009-09-09 15:08:12 +0000497 ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000498 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000501 // The iterator range [FirstComment, LastComment] contains all of the
502 // BCPL comments that, together, are associated with this declaration.
503 // Form a single comment block string for this declaration that concatenates
504 // all of these comments.
505 std::string &Result = DeclComments[D];
506 while (FirstComment != LastComment) {
507 std::pair<FileID, unsigned> DecompStart
508 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
509 std::pair<FileID, unsigned> DecompEnd
510 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
511 Result.append(FileBufferStart + DecompStart.second,
512 FileBufferStart + DecompEnd.second + 1);
513 ++FirstComment;
514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000516 // Append the last comment line.
Mike Stump11289f42009-09-09 15:08:12 +0000517 Result.append(FileBufferStart +
518 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000519 FileBufferStart + LastCommentEndDecomp.second + 1);
520 return Result.c_str();
521}
522
Chris Lattner53cfe802007-07-18 17:52:12 +0000523//===----------------------------------------------------------------------===//
524// Type Sizing and Analysis
525//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000526
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000527/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
528/// scalar floating point type.
529const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000530 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000531 assert(BT && "Not a floating point type!");
532 switch (BT->getKind()) {
533 default: assert(0 && "Not a floating point type!");
534 case BuiltinType::Float: return Target.getFloatFormat();
535 case BuiltinType::Double: return Target.getDoubleFormat();
536 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
537 }
538}
539
Ken Dyck160146e2010-01-27 17:10:57 +0000540/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000541/// specified decl. Note that bitfields do not have a valid alignment, so
542/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000543/// If @p RefAsPointee, references are treated like their underlying type
544/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000545CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000546 unsigned Align = Target.getCharWidth();
547
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000548 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000549 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000550
Chris Lattner68061312009-01-24 21:53:27 +0000551 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
552 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000553 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000554 if (RefAsPointee)
555 T = RT->getPointeeType();
556 else
557 T = getPointerType(RT->getPointeeType());
558 }
559 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000560 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000561 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
562 T = cast<ArrayType>(T)->getElementType();
563
564 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
565 }
Charles Davis3fc51072010-02-23 04:52:00 +0000566 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
567 // In the case of a field in a packed struct, we want the minimum
568 // of the alignment of the field and the alignment of the struct.
569 Align = std::min(Align,
570 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
571 }
Chris Lattner68061312009-01-24 21:53:27 +0000572 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000573
Ken Dyck160146e2010-01-27 17:10:57 +0000574 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000575}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000576
Chris Lattner983a8bb2007-07-13 22:13:22 +0000577/// getTypeSize - Return the size of the specified type, in bits. This method
578/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000579///
580/// FIXME: Pointers into different addr spaces could have different sizes and
581/// alignment requirements: getPointerInfo should take an AddrSpace, this
582/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000583std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000584ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000585 uint64_t Width=0;
586 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000587 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000588#define TYPE(Class, Base)
589#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000590#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000591#define DEPENDENT_TYPE(Class, Base) case Type::Class:
592#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000593 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000594 break;
595
Chris Lattner355332d2007-07-13 22:27:08 +0000596 case Type::FunctionNoProto:
597 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000598 // GCC extension: alignof(function) = 32 bits
599 Width = 0;
600 Align = 32;
601 break;
602
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000603 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000604 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000605 Width = 0;
606 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
607 break;
608
Steve Naroff5c131802007-08-30 01:06:46 +0000609 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000610 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000611
Chris Lattner37e05872008-03-05 18:54:05 +0000612 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000613 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000614 Align = EltInfo.second;
615 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000616 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000617 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000618 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000619 const VectorType *VT = cast<VectorType>(T);
620 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
621 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000622 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000623 // If the alignment is not a power of 2, round up to the next power of 2.
624 // This happens for non-power-of-2 length vectors.
Chris Lattner63d2b362009-10-22 05:17:15 +0000625 if (VT->getNumElements() & (VT->getNumElements()-1)) {
626 Align = llvm::NextPowerOf2(Align);
627 Width = llvm::RoundUpToAlignment(Width, Align);
628 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000629 break;
630 }
Chris Lattner647fb222007-07-18 18:26:58 +0000631
Chris Lattner7570e9c2008-03-08 08:52:55 +0000632 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000633 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000634 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000635 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000636 // GCC extension: alignof(void) = 8 bits.
637 Width = 0;
638 Align = 8;
639 break;
640
Chris Lattner6a4f7452007-12-19 19:23:28 +0000641 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000642 Width = Target.getBoolWidth();
643 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000644 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000645 case BuiltinType::Char_S:
646 case BuiltinType::Char_U:
647 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000649 Width = Target.getCharWidth();
650 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000651 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000652 case BuiltinType::WChar:
653 Width = Target.getWCharWidth();
654 Align = Target.getWCharAlign();
655 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000656 case BuiltinType::Char16:
657 Width = Target.getChar16Width();
658 Align = Target.getChar16Align();
659 break;
660 case BuiltinType::Char32:
661 Width = Target.getChar32Width();
662 Align = Target.getChar32Align();
663 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000664 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000665 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000666 Width = Target.getShortWidth();
667 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000668 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000669 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000671 Width = Target.getIntWidth();
672 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000673 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000674 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000675 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000676 Width = Target.getLongWidth();
677 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000678 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000679 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000680 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000681 Width = Target.getLongLongWidth();
682 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000683 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000684 case BuiltinType::Int128:
685 case BuiltinType::UInt128:
686 Width = 128;
687 Align = 128; // int128_t is 128-bit aligned on all targets.
688 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000689 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000690 Width = Target.getFloatWidth();
691 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000692 break;
693 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000694 Width = Target.getDoubleWidth();
695 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000696 break;
697 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000698 Width = Target.getLongDoubleWidth();
699 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000700 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000701 case BuiltinType::NullPtr:
702 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
703 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000704 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000705 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000706 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000707 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000708 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000709 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000710 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000711 case Type::BlockPointer: {
712 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
713 Width = Target.getPointerWidth(AS);
714 Align = Target.getPointerAlign(AS);
715 break;
716 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000717 case Type::LValueReference:
718 case Type::RValueReference: {
719 // alignof and sizeof should never enter this code path here, so we go
720 // the pointer route.
721 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
722 Width = Target.getPointerWidth(AS);
723 Align = Target.getPointerAlign(AS);
724 break;
725 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000726 case Type::Pointer: {
727 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000728 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000729 Align = Target.getPointerAlign(AS);
730 break;
731 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000732 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000733 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000734 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000735 getTypeInfo(getPointerDiffType());
736 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000737 if (Pointee->isFunctionType())
738 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000739 Align = PtrDiffInfo.second;
740 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000741 }
Chris Lattner647fb222007-07-18 18:26:58 +0000742 case Type::Complex: {
743 // Complex types have the same alignment as their elements, but twice the
744 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000745 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000746 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000747 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000748 Align = EltInfo.second;
749 break;
750 }
Devang Pateldbb72632008-06-04 21:54:36 +0000751 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000752 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000753 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
754 Width = Layout.getSize();
755 Align = Layout.getAlignment();
756 break;
757 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000758 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000759 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000760 const TagType *TT = cast<TagType>(T);
761
762 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000763 Width = 1;
764 Align = 1;
765 break;
766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000768 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000769 return getTypeInfo(ET->getDecl()->getIntegerType());
770
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000771 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000772 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
773 Width = Layout.getSize();
774 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000775 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000776 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000777
Chris Lattner63d2b362009-10-22 05:17:15 +0000778 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000779 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
780 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000781
Chris Lattner63d2b362009-10-22 05:17:15 +0000782 case Type::Elaborated:
783 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
784 .getTypePtr());
John McCallfcc33b02009-09-05 00:15:47 +0000785
Douglas Gregoref462e62009-04-30 17:32:17 +0000786 case Type::Typedef: {
787 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000788 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000789 Align = std::max(Aligned->getMaxAlignment(),
790 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000791 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
792 } else
793 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000794 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000795 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000796
797 case Type::TypeOfExpr:
798 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
799 .getTypePtr());
800
801 case Type::TypeOf:
802 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
803
Anders Carlsson81df7b82009-06-24 19:06:50 +0000804 case Type::Decltype:
805 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
806 .getTypePtr());
807
Douglas Gregoref462e62009-04-30 17:32:17 +0000808 case Type::QualifiedName:
809 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000810
Douglas Gregoref462e62009-04-30 17:32:17 +0000811 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000812 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000813 "Cannot request the size of a dependent type");
814 // FIXME: this is likely to be wrong once we support template
815 // aliases, since a template alias could refer to a typedef that
816 // has an __aligned__ attribute on it.
817 return getTypeInfo(getCanonicalType(T));
818 }
Mike Stump11289f42009-09-09 15:08:12 +0000819
Chris Lattner53cfe802007-07-18 17:52:12 +0000820 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000821 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000822}
823
Ken Dyck8c89d592009-12-22 14:23:30 +0000824/// getTypeSizeInChars - Return the size of the specified type, in characters.
825/// This method does not work on incomplete types.
826CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000827 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000828}
829CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000830 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000831}
832
Ken Dycka6046ab2010-01-26 17:25:18 +0000833/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000834/// characters. This method does not work on incomplete types.
835CharUnits ASTContext::getTypeAlignInChars(QualType T) {
836 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
837}
838CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
839 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
840}
841
Chris Lattnera3402cd2009-01-27 18:08:34 +0000842/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
843/// type for the current target in bits. This can be different than the ABI
844/// alignment in cases where it is beneficial for performance to overalign
845/// a data type.
846unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
847 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000848
849 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000850 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000851 T = CT->getElementType().getTypePtr();
852 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
853 T->isSpecificBuiltinType(BuiltinType::LongLong))
854 return std::max(ABIAlign, (unsigned)getTypeSize(T));
855
Chris Lattnera3402cd2009-01-27 18:08:34 +0000856 return ABIAlign;
857}
858
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000859static void CollectLocalObjCIvars(ASTContext *Ctx,
860 const ObjCInterfaceDecl *OI,
861 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000862 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
863 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000864 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000865 if (!IVDecl->isInvalidDecl())
866 Fields.push_back(cast<FieldDecl>(IVDecl));
867 }
868}
869
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000870void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
871 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
872 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
873 CollectObjCIvars(SuperClass, Fields);
874 CollectLocalObjCIvars(this, OI, Fields);
875}
876
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000877/// ShallowCollectObjCIvars -
878/// Collect all ivars, including those synthesized, in the current class.
879///
880void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000881 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000882 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
883 E = OI->ivar_end(); I != E; ++I) {
884 Ivars.push_back(*I);
885 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000886
887 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000888}
889
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000890void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
891 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000892 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
893 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000894 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
895 Ivars.push_back(Ivar);
Mike Stump11289f42009-09-09 15:08:12 +0000896
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000897 // Also look into nested protocols.
898 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
899 E = PD->protocol_end(); P != E; ++P)
900 CollectProtocolSynthesizedIvars(*P, Ivars);
901}
902
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000903/// CollectNonClassIvars -
904/// This routine collects all other ivars which are not declared in the class.
905/// This includes synthesized ivars and those in class's implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000906///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000907void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000908 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000909 // Find ivars declared in class extension.
910 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
911 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
912 E = CDecl->ivar_end(); I != E; ++I) {
913 Ivars.push_back(*I);
914 }
915 }
916
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000917 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
918 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000919 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
920 Ivars.push_back(Ivar);
921 }
922 // Also look into interface's protocol list for properties declared
923 // in the protocol and whose ivars are synthesized.
924 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
925 PE = OI->protocol_end(); P != PE; ++P) {
926 ObjCProtocolDecl *PD = (*P);
927 CollectProtocolSynthesizedIvars(PD, Ivars);
928 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000929
930 // Also add any ivar defined in this class's implementation
931 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
932 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
933 E = ImplDecl->ivar_end(); I != E; ++I)
934 Ivars.push_back(*I);
935 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000936}
937
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000938/// CollectInheritedProtocols - Collect all protocols in current class and
939/// those inherited by it.
940void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000941 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000942 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
943 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
944 PE = OI->protocol_end(); P != PE; ++P) {
945 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000946 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000948 PE = Proto->protocol_end(); P != PE; ++P) {
949 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000950 CollectInheritedProtocols(*P, Protocols);
951 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000952 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000953
954 // Categories of this Interface.
955 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
956 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
957 CollectInheritedProtocols(CDeclChain, Protocols);
958 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
959 while (SD) {
960 CollectInheritedProtocols(SD, Protocols);
961 SD = SD->getSuperClass();
962 }
963 return;
964 }
965 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
966 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
967 PE = OC->protocol_end(); P != PE; ++P) {
968 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000969 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
971 PE = Proto->protocol_end(); P != PE; ++P)
972 CollectInheritedProtocols(*P, Protocols);
973 }
974 return;
975 }
976 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
977 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
978 PE = OP->protocol_end(); P != PE; ++P) {
979 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000980 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000981 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
982 PE = Proto->protocol_end(); P != PE; ++P)
983 CollectInheritedProtocols(*P, Protocols);
984 }
985 return;
986 }
987}
988
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000989unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
990 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000991 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
992 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000993 if ((*I)->getPropertyIvarDecl())
994 ++count;
995
996 // Also look into nested protocols.
997 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
998 E = PD->protocol_end(); P != E; ++P)
999 count += CountProtocolSynthesizedIvars(*P);
1000 return count;
1001}
1002
Mike Stump11289f42009-09-09 15:08:12 +00001003unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001004 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001005 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1006 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001007 if ((*I)->getPropertyIvarDecl())
1008 ++count;
1009 }
1010 // Also look into interface's protocol list for properties declared
1011 // in the protocol and whose ivars are synthesized.
1012 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1013 PE = OI->protocol_end(); P != PE; ++P) {
1014 ObjCProtocolDecl *PD = (*P);
1015 count += CountProtocolSynthesizedIvars(PD);
1016 }
1017 return count;
1018}
1019
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001020/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1021ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1022 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1023 I = ObjCImpls.find(D);
1024 if (I != ObjCImpls.end())
1025 return cast<ObjCImplementationDecl>(I->second);
1026 return 0;
1027}
1028/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1029ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1030 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1031 I = ObjCImpls.find(D);
1032 if (I != ObjCImpls.end())
1033 return cast<ObjCCategoryImplDecl>(I->second);
1034 return 0;
1035}
1036
1037/// \brief Set the implementation of ObjCInterfaceDecl.
1038void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1039 ObjCImplementationDecl *ImplD) {
1040 assert(IFaceD && ImplD && "Passed null params");
1041 ObjCImpls[IFaceD] = ImplD;
1042}
1043/// \brief Set the implementation of ObjCCategoryDecl.
1044void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1045 ObjCCategoryImplDecl *ImplD) {
1046 assert(CatD && ImplD && "Passed null params");
1047 ObjCImpls[CatD] = ImplD;
1048}
1049
John McCallbcd03502009-12-07 02:54:59 +00001050/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001051///
John McCallbcd03502009-12-07 02:54:59 +00001052/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001053/// the TypeLoc wrappers.
1054///
1055/// \param T the type that will be the basis for type source info. This type
1056/// should refer to how the declarator was written in source code, not to
1057/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001058TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001059 unsigned DataSize) {
1060 if (!DataSize)
1061 DataSize = TypeLoc::getFullDataSizeForType(T);
1062 else
1063 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001064 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001065
John McCallbcd03502009-12-07 02:54:59 +00001066 TypeSourceInfo *TInfo =
1067 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1068 new (TInfo) TypeSourceInfo(T);
1069 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001070}
1071
John McCallbcd03502009-12-07 02:54:59 +00001072TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001073 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001074 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001075 DI->getTypeLoc().initialize(L);
1076 return DI;
1077}
1078
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001079/// getInterfaceLayoutImpl - Get or compute information about the
1080/// layout of the given interface.
1081///
1082/// \param Impl - If given, also include the layout of the interface's
1083/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +00001084const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001085ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1086 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +00001087 assert(!D->isForwardDecl() && "Invalid interface decl!");
1088
Devang Pateldbb72632008-06-04 21:54:36 +00001089 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +00001090 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001091 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1092 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1093 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +00001094
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001095 // Add in synthesized ivar count if laying out an implementation.
1096 if (Impl) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001097 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001098 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001099 // entry. Note we can't cache this because we simply free all
1100 // entries later; however we shouldn't look up implementations
1101 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001102 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001103 return getObjCLayout(D, 0);
1104 }
1105
Mike Stump11289f42009-09-09 15:08:12 +00001106 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001107 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1108 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001109
Devang Pateldbb72632008-06-04 21:54:36 +00001110 return *NewEntry;
1111}
1112
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001113const ASTRecordLayout &
1114ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1115 return getObjCLayout(D, 0);
1116}
1117
1118const ASTRecordLayout &
1119ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1120 return getObjCLayout(D->getClassInterface(), D);
1121}
1122
Devang Patele11664a2007-11-01 19:11:01 +00001123/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +00001124/// specified record (struct/union/class), which indicates its size and field
1125/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +00001126const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001127 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +00001128 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +00001129
Chris Lattner53cfe802007-07-18 17:52:12 +00001130 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +00001131 // Note that we can't save a reference to the entry because this function
1132 // is recursive.
1133 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +00001134 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +00001135
Mike Stump11289f42009-09-09 15:08:12 +00001136 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001137 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +00001138 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001139
Chris Lattner647fb222007-07-18 18:26:58 +00001140 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +00001141}
1142
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001143const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001144 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001145 assert(RD && "Cannot get key function for forward declarations!");
1146
1147 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1148 if (!Entry)
1149 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1150 else
1151 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1152 "Key function changed!");
1153
1154 return Entry;
1155}
1156
Chris Lattner983a8bb2007-07-13 22:13:22 +00001157//===----------------------------------------------------------------------===//
1158// Type creation/memoization methods
1159//===----------------------------------------------------------------------===//
1160
John McCall8ccfcb52009-09-24 19:53:00 +00001161QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1162 unsigned Fast = Quals.getFastQualifiers();
1163 Quals.removeFastQualifiers();
1164
1165 // Check if we've already instantiated this type.
1166 llvm::FoldingSetNodeID ID;
1167 ExtQuals::Profile(ID, TypeNode, Quals);
1168 void *InsertPos = 0;
1169 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1170 assert(EQ->getQualifiers() == Quals);
1171 QualType T = QualType(EQ, Fast);
1172 return T;
1173 }
1174
John McCall90d1c2d2009-09-24 23:30:46 +00001175 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001176 ExtQualNodes.InsertNode(New, InsertPos);
1177 QualType T = QualType(New, Fast);
1178 return T;
1179}
1180
1181QualType ASTContext::getVolatileType(QualType T) {
1182 QualType CanT = getCanonicalType(T);
1183 if (CanT.isVolatileQualified()) return T;
1184
1185 QualifierCollector Quals;
1186 const Type *TypeNode = Quals.strip(T);
1187 Quals.addVolatile();
1188
1189 return getExtQualType(TypeNode, Quals);
1190}
1191
Fariborz Jahanianece85822009-02-17 18:27:45 +00001192QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001193 QualType CanT = getCanonicalType(T);
1194 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001195 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001196
John McCall8ccfcb52009-09-24 19:53:00 +00001197 // If we are composing extended qualifiers together, merge together
1198 // into one ExtQuals node.
1199 QualifierCollector Quals;
1200 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001201
John McCall8ccfcb52009-09-24 19:53:00 +00001202 // If this type already has an address space specified, it cannot get
1203 // another one.
1204 assert(!Quals.hasAddressSpace() &&
1205 "Type cannot be in multiple addr spaces!");
1206 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001207
John McCall8ccfcb52009-09-24 19:53:00 +00001208 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001209}
1210
Chris Lattnerd60183d2009-02-18 22:53:11 +00001211QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001212 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001213 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001214 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001215 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001216
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001217 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001218 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001219 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001220 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1221 return getPointerType(ResultType);
1222 }
1223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
John McCall8ccfcb52009-09-24 19:53:00 +00001225 // If we are composing extended qualifiers together, merge together
1226 // into one ExtQuals node.
1227 QualifierCollector Quals;
1228 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001229
John McCall8ccfcb52009-09-24 19:53:00 +00001230 // If this type already has an ObjCGC specified, it cannot get
1231 // another one.
1232 assert(!Quals.hasObjCGCAttr() &&
1233 "Type cannot have multiple ObjCGCs!");
1234 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCall8ccfcb52009-09-24 19:53:00 +00001236 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001237}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001238
Douglas Gregor8c940862010-01-18 17:14:39 +00001239static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1240 bool AddNoReturn,
1241 CallingConv CallConv) {
John McCall8ccfcb52009-09-24 19:53:00 +00001242 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001243 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1244 QualType Pointee = Pointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001245 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1246 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001247 if (ResultType == Pointee)
1248 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001249
1250 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001251 } else if (const BlockPointerType *BlockPointer
1252 = T->getAs<BlockPointerType>()) {
1253 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001254 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1255 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001256 if (ResultType == Pointee)
1257 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001258
1259 ResultType = Context.getBlockPointerType(ResultType);
1260 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1261 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001262 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001263
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001264 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001265 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1266 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001267 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001268 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001269 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001270 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1271 FPT->getNumArgs(), FPT->isVariadic(),
1272 FPT->getTypeQuals(),
1273 FPT->hasExceptionSpec(),
1274 FPT->hasAnyExceptionSpec(),
1275 FPT->getNumExceptions(),
1276 FPT->exception_begin(),
1277 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001278 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001279 } else
1280 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001281
1282 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1283}
1284
1285QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1286 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1287}
1288
1289QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1290 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump8c5d7992009-07-25 21:26:53 +00001291}
1292
Chris Lattnerc6395932007-06-22 20:56:16 +00001293/// getComplexType - Return the uniqued reference to the type for a complex
1294/// number with the specified element type.
1295QualType ASTContext::getComplexType(QualType T) {
1296 // Unique pointers, to guarantee there is only one pointer of a particular
1297 // structure.
1298 llvm::FoldingSetNodeID ID;
1299 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattnerc6395932007-06-22 20:56:16 +00001301 void *InsertPos = 0;
1302 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1303 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattnerc6395932007-06-22 20:56:16 +00001305 // If the pointee type isn't canonical, this won't be a canonical type either,
1306 // so fill in the canonical type field.
1307 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001308 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001309 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattnerc6395932007-06-22 20:56:16 +00001311 // Get the new insert position for the node we care about.
1312 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001313 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001314 }
John McCall90d1c2d2009-09-24 23:30:46 +00001315 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001316 Types.push_back(New);
1317 ComplexTypes.InsertNode(New, InsertPos);
1318 return QualType(New, 0);
1319}
1320
Chris Lattner970e54e2006-11-12 00:37:36 +00001321/// getPointerType - Return the uniqued reference to the type for a pointer to
1322/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001323QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001324 // Unique pointers, to guarantee there is only one pointer of a particular
1325 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001326 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001327 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattner67521df2007-01-27 01:29:36 +00001329 void *InsertPos = 0;
1330 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001331 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattner7ccecb92006-11-12 08:50:50 +00001333 // If the pointee type isn't canonical, this won't be a canonical type either,
1334 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001335 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001336 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001337 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattner67521df2007-01-27 01:29:36 +00001339 // Get the new insert position for the node we care about.
1340 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001341 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001342 }
John McCall90d1c2d2009-09-24 23:30:46 +00001343 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001344 Types.push_back(New);
1345 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001346 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001347}
1348
Mike Stump11289f42009-09-09 15:08:12 +00001349/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001350/// a pointer to the specified block.
1351QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001352 assert(T->isFunctionType() && "block of function types only");
1353 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001354 // structure.
1355 llvm::FoldingSetNodeID ID;
1356 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Steve Naroffec33ed92008-08-27 16:04:49 +00001358 void *InsertPos = 0;
1359 if (BlockPointerType *PT =
1360 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1361 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001362
1363 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001364 // type either so fill in the canonical type field.
1365 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001366 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001367 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001368
Steve Naroffec33ed92008-08-27 16:04:49 +00001369 // Get the new insert position for the node we care about.
1370 BlockPointerType *NewIP =
1371 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001372 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001373 }
John McCall90d1c2d2009-09-24 23:30:46 +00001374 BlockPointerType *New
1375 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001376 Types.push_back(New);
1377 BlockPointerTypes.InsertNode(New, InsertPos);
1378 return QualType(New, 0);
1379}
1380
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001381/// getLValueReferenceType - Return the uniqued reference to the type for an
1382/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001383QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001384 // Unique pointers, to guarantee there is only one pointer of a particular
1385 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001386 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001387 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001388
1389 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001390 if (LValueReferenceType *RT =
1391 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001392 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001393
John McCallfc93cf92009-10-22 22:37:11 +00001394 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1395
Bill Wendling3708c182007-05-27 10:15:43 +00001396 // If the referencee type isn't canonical, this won't be a canonical type
1397 // either, so fill in the canonical type field.
1398 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001399 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1400 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1401 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001402
Bill Wendling3708c182007-05-27 10:15:43 +00001403 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001404 LValueReferenceType *NewIP =
1405 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001406 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001407 }
1408
John McCall90d1c2d2009-09-24 23:30:46 +00001409 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001410 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1411 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001412 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001413 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001414
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001415 return QualType(New, 0);
1416}
1417
1418/// getRValueReferenceType - Return the uniqued reference to the type for an
1419/// rvalue reference to the specified type.
1420QualType ASTContext::getRValueReferenceType(QualType T) {
1421 // Unique pointers, to guarantee there is only one pointer of a particular
1422 // structure.
1423 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001424 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001425
1426 void *InsertPos = 0;
1427 if (RValueReferenceType *RT =
1428 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1429 return QualType(RT, 0);
1430
John McCallfc93cf92009-10-22 22:37:11 +00001431 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1432
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001433 // If the referencee type isn't canonical, this won't be a canonical type
1434 // either, so fill in the canonical type field.
1435 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001436 if (InnerRef || !T.isCanonical()) {
1437 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1438 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001439
1440 // Get the new insert position for the node we care about.
1441 RValueReferenceType *NewIP =
1442 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1443 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1444 }
1445
John McCall90d1c2d2009-09-24 23:30:46 +00001446 RValueReferenceType *New
1447 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001448 Types.push_back(New);
1449 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001450 return QualType(New, 0);
1451}
1452
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001453/// getMemberPointerType - Return the uniqued reference to the type for a
1454/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001455QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001456 // Unique pointers, to guarantee there is only one pointer of a particular
1457 // structure.
1458 llvm::FoldingSetNodeID ID;
1459 MemberPointerType::Profile(ID, T, Cls);
1460
1461 void *InsertPos = 0;
1462 if (MemberPointerType *PT =
1463 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1464 return QualType(PT, 0);
1465
1466 // If the pointee or class type isn't canonical, this won't be a canonical
1467 // type either, so fill in the canonical type field.
1468 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001469 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001470 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1471
1472 // Get the new insert position for the node we care about.
1473 MemberPointerType *NewIP =
1474 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1475 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1476 }
John McCall90d1c2d2009-09-24 23:30:46 +00001477 MemberPointerType *New
1478 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001479 Types.push_back(New);
1480 MemberPointerTypes.InsertNode(New, InsertPos);
1481 return QualType(New, 0);
1482}
1483
Mike Stump11289f42009-09-09 15:08:12 +00001484/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001485/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001486QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001487 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001488 ArrayType::ArraySizeModifier ASM,
1489 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001490 assert((EltTy->isDependentType() ||
1491 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001492 "Constant array of VLAs is illegal!");
1493
Chris Lattnere2df3f92009-05-13 04:12:56 +00001494 // Convert the array size into a canonical width matching the pointer size for
1495 // the target.
1496 llvm::APInt ArySize(ArySizeIn);
1497 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001498
Chris Lattner23b7eb62007-06-15 23:05:46 +00001499 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001500 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Chris Lattner36f8e652007-01-27 08:31:04 +00001502 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001503 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001504 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001505 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Chris Lattner7ccecb92006-11-12 08:50:50 +00001507 // If the element type isn't canonical, this won't be a canonical type either,
1508 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001509 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001510 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001511 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001512 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001513 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001514 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001515 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001516 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCall90d1c2d2009-09-24 23:30:46 +00001519 ConstantArrayType *New = new(*this,TypeAlignment)
1520 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001521 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001522 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001523 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001524}
1525
Steve Naroffcadebd02007-08-30 18:14:25 +00001526/// getVariableArrayType - Returns a non-unique reference to the type for a
1527/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001528QualType ASTContext::getVariableArrayType(QualType EltTy,
1529 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001530 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001531 unsigned EltTypeQuals,
1532 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001533 // Since we don't unique expressions, it isn't possible to unique VLA's
1534 // that have an expression provided for their size.
1535
John McCall90d1c2d2009-09-24 23:30:46 +00001536 VariableArrayType *New = new(*this, TypeAlignment)
1537 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001538
1539 VariableArrayTypes.push_back(New);
1540 Types.push_back(New);
1541 return QualType(New, 0);
1542}
1543
Douglas Gregor4619e432008-12-05 23:32:09 +00001544/// getDependentSizedArrayType - Returns a non-unique reference to
1545/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001546/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001547QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1548 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001549 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001550 unsigned EltTypeQuals,
1551 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001552 assert((!NumElts || NumElts->isTypeDependent() ||
1553 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001554 "Size must be type- or value-dependent!");
1555
Douglas Gregorf3f95522009-07-31 00:23:35 +00001556 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001557 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001558 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001559
1560 if (NumElts) {
1561 // Dependently-sized array types that do not have a specified
1562 // number of elements will have their sizes deduced from an
1563 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001564 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1565 EltTypeQuals, NumElts);
1566
1567 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1568 }
1569
Douglas Gregorf3f95522009-07-31 00:23:35 +00001570 DependentSizedArrayType *New;
1571 if (Canon) {
1572 // We already have a canonical version of this array type; use it as
1573 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001574 New = new (*this, TypeAlignment)
1575 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1576 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001577 } else {
1578 QualType CanonEltTy = getCanonicalType(EltTy);
1579 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001580 New = new (*this, TypeAlignment)
1581 DependentSizedArrayType(*this, EltTy, QualType(),
1582 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001583
Douglas Gregorc42075a2010-02-04 18:10:26 +00001584 if (NumElts) {
1585 DependentSizedArrayType *CanonCheck
1586 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1587 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1588 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001589 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001590 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001591 } else {
1592 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1593 ASM, EltTypeQuals,
1594 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001595 New = new (*this, TypeAlignment)
1596 DependentSizedArrayType(*this, EltTy, Canon,
1597 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001598 }
1599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600
Douglas Gregor4619e432008-12-05 23:32:09 +00001601 Types.push_back(New);
1602 return QualType(New, 0);
1603}
1604
Eli Friedmanbd258282008-02-15 18:16:39 +00001605QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1606 ArrayType::ArraySizeModifier ASM,
1607 unsigned EltTypeQuals) {
1608 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001609 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001610
1611 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001612 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001613 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1614 return QualType(ATP, 0);
1615
1616 // If the element type isn't canonical, this won't be a canonical type
1617 // either, so fill in the canonical type field.
1618 QualType Canonical;
1619
John McCallb692a092009-10-22 20:10:53 +00001620 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001621 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001622 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001623
1624 // Get the new insert position for the node we care about.
1625 IncompleteArrayType *NewIP =
1626 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001627 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001628 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001629
John McCall90d1c2d2009-09-24 23:30:46 +00001630 IncompleteArrayType *New = new (*this, TypeAlignment)
1631 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001632
1633 IncompleteArrayTypes.InsertNode(New, InsertPos);
1634 Types.push_back(New);
1635 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001636}
1637
Steve Naroff91fcddb2007-07-18 18:00:27 +00001638/// getVectorType - Return the unique reference to a vector type of
1639/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001640QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1641 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001642 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001643
Chris Lattner76a00cf2008-04-06 22:59:24 +00001644 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001645 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001646
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001647 // Check if we've already instantiated a vector of this type.
1648 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001649 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1650 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001651 void *InsertPos = 0;
1652 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1653 return QualType(VTP, 0);
1654
1655 // If the element type isn't canonical, this won't be a canonical type either,
1656 // so fill in the canonical type field.
1657 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001658 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1659 Canonical = getVectorType(getCanonicalType(vecType),
1660 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001661
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001662 // Get the new insert position for the node we care about.
1663 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001664 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001665 }
John McCall90d1c2d2009-09-24 23:30:46 +00001666 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001667 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001668 VectorTypes.InsertNode(New, InsertPos);
1669 Types.push_back(New);
1670 return QualType(New, 0);
1671}
1672
Nate Begemance4d7fc2008-04-18 23:10:10 +00001673/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001674/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001675QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001676 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattner76a00cf2008-04-06 22:59:24 +00001678 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001679 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001680
Steve Naroff91fcddb2007-07-18 18:00:27 +00001681 // Check if we've already instantiated a vector of this type.
1682 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001683 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001684 void *InsertPos = 0;
1685 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1686 return QualType(VTP, 0);
1687
1688 // If the element type isn't canonical, this won't be a canonical type either,
1689 // so fill in the canonical type field.
1690 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001691 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001692 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001693
Steve Naroff91fcddb2007-07-18 18:00:27 +00001694 // Get the new insert position for the node we care about.
1695 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001696 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001697 }
John McCall90d1c2d2009-09-24 23:30:46 +00001698 ExtVectorType *New = new (*this, TypeAlignment)
1699 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001700 VectorTypes.InsertNode(New, InsertPos);
1701 Types.push_back(New);
1702 return QualType(New, 0);
1703}
1704
Mike Stump11289f42009-09-09 15:08:12 +00001705QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001706 Expr *SizeExpr,
1707 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001708 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001709 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001710 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001711
Douglas Gregor352169a2009-07-31 03:54:25 +00001712 void *InsertPos = 0;
1713 DependentSizedExtVectorType *Canon
1714 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1715 DependentSizedExtVectorType *New;
1716 if (Canon) {
1717 // We already have a canonical version of this array type; use it as
1718 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001719 New = new (*this, TypeAlignment)
1720 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1721 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001722 } else {
1723 QualType CanonVecTy = getCanonicalType(vecType);
1724 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001725 New = new (*this, TypeAlignment)
1726 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1727 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001728
1729 DependentSizedExtVectorType *CanonCheck
1730 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1731 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1732 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001733 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1734 } else {
1735 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1736 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001737 New = new (*this, TypeAlignment)
1738 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001739 }
1740 }
Mike Stump11289f42009-09-09 15:08:12 +00001741
Douglas Gregor758a8692009-06-17 21:51:59 +00001742 Types.push_back(New);
1743 return QualType(New, 0);
1744}
1745
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001746/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001747///
Douglas Gregor8c940862010-01-18 17:14:39 +00001748QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1749 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001750 // Unique functions, to guarantee there is only one function of a particular
1751 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001752 llvm::FoldingSetNodeID ID;
John McCallcddbad02010-02-04 05:44:44 +00001753 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump11289f42009-09-09 15:08:12 +00001754
Chris Lattner47955de2007-01-27 08:37:20 +00001755 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001756 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001757 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001758 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001759
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001760 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001761 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001762 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001763 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001764 getCanonicalCallConv(CallConv));
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattner47955de2007-01-27 08:37:20 +00001766 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001767 FunctionNoProtoType *NewIP =
1768 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001769 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
John McCall90d1c2d2009-09-24 23:30:46 +00001772 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallcddbad02010-02-04 05:44:44 +00001773 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Chris Lattner47955de2007-01-27 08:37:20 +00001774 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001775 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001776 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001777}
1778
1779/// getFunctionType - Return a normal function type with a typed argument
1780/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001781QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001782 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001783 unsigned TypeQuals, bool hasExceptionSpec,
1784 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregor8c940862010-01-18 17:14:39 +00001785 const QualType *ExArray, bool NoReturn,
1786 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001787 // Unique functions, to guarantee there is only one function of a particular
1788 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001789 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001790 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001791 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallcddbad02010-02-04 05:44:44 +00001792 NumExs, ExArray, NoReturn, CallConv);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001793
1794 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001795 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001796 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001797 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001798
1799 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001800 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001801 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001802 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001803 isCanonical = false;
1804
1805 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001806 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001807 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001808 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001809 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001810 CanonicalArgs.reserve(NumArgs);
1811 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001812 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001813
Chris Lattner76a00cf2008-04-06 22:59:24 +00001814 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001815 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001816 isVariadic, TypeQuals, false,
Douglas Gregor8c940862010-01-18 17:14:39 +00001817 false, 0, 0, NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001818 getCanonicalCallConv(CallConv));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001819
Chris Lattnerfd4de792007-01-27 01:15:32 +00001820 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001821 FunctionProtoType *NewIP =
1822 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001823 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001824 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001825
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001826 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001827 // for two variable size arrays (for parameter and exception types) at the
1828 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001829 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001830 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1831 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001832 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001833 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001834 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregor8c940862010-01-18 17:14:39 +00001835 ExArray, NumExs, Canonical, NoReturn, CallConv);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001836 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001837 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001838 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001839}
Chris Lattneref51c202006-11-10 07:17:23 +00001840
Douglas Gregor83a586e2008-04-13 21:07:44 +00001841/// getTypeDeclType - Return the unique reference to the type for the
1842/// specified type declaration.
John McCall81e38502010-02-16 03:57:14 +00001843QualType ASTContext::getTypeDeclType(const TypeDecl *Decl,
1844 const TypeDecl* PrevDecl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001845 assert(Decl && "Passed null for Decl param");
Douglas Gregor83a586e2008-04-13 21:07:44 +00001846 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001847
John McCall81e38502010-02-16 03:57:14 +00001848 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001849 return getTypedefType(Typedef);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001850 else if (isa<TemplateTypeParmDecl>(Decl)) {
1851 assert(false && "Template type parameter types are always available.");
John McCall81e38502010-02-16 03:57:14 +00001852 } else if (const ObjCInterfaceDecl *ObjCInterface
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001853 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001854 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001855
John McCall81e38502010-02-16 03:57:14 +00001856 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek721e2392009-01-19 21:31:22 +00001857 if (PrevDecl)
1858 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff096bab72009-01-27 22:08:43 +00001859 else
John McCall90d1c2d2009-09-24 23:30:46 +00001860 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001861 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek721e2392009-01-19 21:31:22 +00001862 if (PrevDecl)
1863 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff096bab72009-01-27 22:08:43 +00001864 else
John McCall90d1c2d2009-09-24 23:30:46 +00001865 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001866 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001867 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1868 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001869 } else
Douglas Gregor83a586e2008-04-13 21:07:44 +00001870 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001871
Ted Kremenek21475702008-09-05 17:16:31 +00001872 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001873 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001874}
1875
Chris Lattner32d920b2007-01-26 02:01:53 +00001876/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001877/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001878QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001879 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001880
Chris Lattner76a00cf2008-04-06 22:59:24 +00001881 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001882 Decl->TypeForDecl = new(*this, TypeAlignment)
1883 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001884 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001885 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001886}
1887
John McCallcebee162009-10-18 09:09:24 +00001888/// \brief Retrieve a substitution-result type.
1889QualType
1890ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1891 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001892 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001893 && "replacement types must always be canonical");
1894
1895 llvm::FoldingSetNodeID ID;
1896 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1897 void *InsertPos = 0;
1898 SubstTemplateTypeParmType *SubstParm
1899 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1900
1901 if (!SubstParm) {
1902 SubstParm = new (*this, TypeAlignment)
1903 SubstTemplateTypeParmType(Parm, Replacement);
1904 Types.push_back(SubstParm);
1905 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1906 }
1907
1908 return QualType(SubstParm, 0);
1909}
1910
Douglas Gregoreff93e02009-02-05 23:33:38 +00001911/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001912/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001913/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001914QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001915 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00001916 IdentifierInfo *Name) {
1917 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001918 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001919 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001920 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001921 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1922
1923 if (TypeParm)
1924 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001925
Anders Carlsson90036dc2009-06-16 00:30:48 +00001926 if (Name) {
1927 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00001928 TypeParm = new (*this, TypeAlignment)
1929 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001930
1931 TemplateTypeParmType *TypeCheck
1932 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1933 assert(!TypeCheck && "Template type parameter canonical type broken");
1934 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001935 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001936 TypeParm = new (*this, TypeAlignment)
1937 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001938
1939 Types.push_back(TypeParm);
1940 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1941
1942 return QualType(TypeParm, 0);
1943}
1944
Mike Stump11289f42009-09-09 15:08:12 +00001945QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001946ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001947 const TemplateArgumentListInfo &Args,
John McCall0ad16662009-10-29 08:12:44 +00001948 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001949 unsigned NumArgs = Args.size();
1950
John McCall0ad16662009-10-29 08:12:44 +00001951 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1952 ArgVec.reserve(NumArgs);
1953 for (unsigned i = 0; i != NumArgs; ++i)
1954 ArgVec.push_back(Args[i].getArgument());
1955
1956 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1957}
1958
1959QualType
1960ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001961 const TemplateArgument *Args,
1962 unsigned NumArgs,
1963 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001964 if (!Canon.isNull())
1965 Canon = getCanonicalType(Canon);
1966 else {
1967 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001968 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1969 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1970 CanonArgs.reserve(NumArgs);
1971 for (unsigned I = 0; I != NumArgs; ++I)
1972 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1973
1974 // Determine whether this canonical template specialization type already
1975 // exists.
1976 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001977 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00001978 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001979
1980 void *InsertPos = 0;
1981 TemplateSpecializationType *Spec
1982 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregora8e02e72009-07-28 23:00:59 +00001984 if (!Spec) {
1985 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001986 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001987 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001988 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001989 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001990 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001991 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001992 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001993 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001994 }
Mike Stump11289f42009-09-09 15:08:12 +00001995
Douglas Gregor15301382009-07-30 17:40:51 +00001996 if (Canon.isNull())
1997 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001998 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001999 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00002000 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002001
Douglas Gregora8e02e72009-07-28 23:00:59 +00002002 // Allocate the (non-canonical) template specialization type, but don't
2003 // try to unique it: these types typically have location information that
2004 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002005 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002006 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002007 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002008 TemplateSpecializationType *Spec
2009 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002010 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002011
Douglas Gregor8bf42052009-02-09 18:46:07 +00002012 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002013 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002014}
2015
Mike Stump11289f42009-09-09 15:08:12 +00002016QualType
Douglas Gregorf21eb492009-03-26 23:50:42 +00002017ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor52537682009-03-19 00:18:19 +00002018 QualType NamedType) {
2019 llvm::FoldingSetNodeID ID;
Douglas Gregorf21eb492009-03-26 23:50:42 +00002020 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002021
2022 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002023 QualifiedNameType *T
Douglas Gregor52537682009-03-19 00:18:19 +00002024 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2025 if (T)
2026 return QualType(T, 0);
2027
Douglas Gregorc42075a2010-02-04 18:10:26 +00002028 QualType Canon = NamedType;
2029 if (!Canon.isCanonical()) {
2030 Canon = getCanonicalType(NamedType);
2031 QualifiedNameType *CheckT
2032 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2033 assert(!CheckT && "Qualified name canonical type broken");
2034 (void)CheckT;
2035 }
2036
2037 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002038 Types.push_back(T);
2039 QualifiedNameTypes.InsertNode(T, InsertPos);
2040 return QualType(T, 0);
2041}
2042
Mike Stump11289f42009-09-09 15:08:12 +00002043QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor333489b2009-03-27 23:10:48 +00002044 const IdentifierInfo *Name,
2045 QualType Canon) {
2046 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2047
2048 if (Canon.isNull()) {
2049 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2050 if (CanonNNS != NNS)
2051 Canon = getTypenameType(CanonNNS, Name);
2052 }
2053
2054 llvm::FoldingSetNodeID ID;
2055 TypenameType::Profile(ID, NNS, Name);
2056
2057 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002058 TypenameType *T
Douglas Gregor333489b2009-03-27 23:10:48 +00002059 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2060 if (T)
2061 return QualType(T, 0);
2062
2063 T = new (*this) TypenameType(NNS, Name, Canon);
2064 Types.push_back(T);
2065 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002066 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002067}
2068
Mike Stump11289f42009-09-09 15:08:12 +00002069QualType
2070ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregordce2b622009-04-01 00:28:59 +00002071 const TemplateSpecializationType *TemplateId,
2072 QualType Canon) {
2073 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2074
Douglas Gregorc42075a2010-02-04 18:10:26 +00002075 llvm::FoldingSetNodeID ID;
2076 TypenameType::Profile(ID, NNS, TemplateId);
2077
2078 void *InsertPos = 0;
2079 TypenameType *T
2080 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2081 if (T)
2082 return QualType(T, 0);
2083
Douglas Gregordce2b622009-04-01 00:28:59 +00002084 if (Canon.isNull()) {
2085 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2086 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2087 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2088 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00002089 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00002090 assert(CanonTemplateId &&
2091 "Canonical type must also be a template specialization type");
2092 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2093 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00002094
2095 TypenameType *CheckT
2096 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2097 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00002098 }
2099
Douglas Gregordce2b622009-04-01 00:28:59 +00002100 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2101 Types.push_back(T);
2102 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002103 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002104}
2105
John McCallfcc33b02009-09-05 00:15:47 +00002106QualType
2107ASTContext::getElaboratedType(QualType UnderlyingType,
2108 ElaboratedType::TagKind Tag) {
2109 llvm::FoldingSetNodeID ID;
2110 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00002111
John McCallfcc33b02009-09-05 00:15:47 +00002112 void *InsertPos = 0;
2113 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2114 if (T)
2115 return QualType(T, 0);
2116
Douglas Gregorc42075a2010-02-04 18:10:26 +00002117 QualType Canon = UnderlyingType;
2118 if (!Canon.isCanonical()) {
2119 Canon = getCanonicalType(Canon);
2120 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2121 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2122 }
John McCallfcc33b02009-09-05 00:15:47 +00002123
2124 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2125 Types.push_back(T);
2126 ElaboratedTypes.InsertNode(T, InsertPos);
2127 return QualType(T, 0);
2128}
2129
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002130/// CmpProtocolNames - Comparison predicate for sorting protocols
2131/// alphabetically.
2132static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2133 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002134 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002135}
2136
John McCallfc93cf92009-10-22 22:37:11 +00002137static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2138 unsigned NumProtocols) {
2139 if (NumProtocols == 0) return true;
2140
2141 for (unsigned i = 1; i != NumProtocols; ++i)
2142 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2143 return false;
2144 return true;
2145}
2146
2147static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002148 unsigned &NumProtocols) {
2149 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002151 // Sort protocols, keyed by name.
2152 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2153
2154 // Remove duplicates.
2155 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2156 NumProtocols = ProtocolsEnd-Protocols;
2157}
2158
Steve Narofffb4330f2009-06-17 22:40:22 +00002159/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2160/// the given interface decl and the conforming protocol list.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002161QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump11289f42009-09-09 15:08:12 +00002162 ObjCProtocolDecl **Protocols,
Steve Narofffb4330f2009-06-17 22:40:22 +00002163 unsigned NumProtocols) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002164 llvm::FoldingSetNodeID ID;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002165 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002166
2167 void *InsertPos = 0;
2168 if (ObjCObjectPointerType *QT =
2169 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2170 return QualType(QT, 0);
2171
John McCallfc93cf92009-10-22 22:37:11 +00002172 // Sort the protocol list alphabetically to canonicalize it.
2173 QualType Canonical;
2174 if (!InterfaceT.isCanonical() ||
2175 !areSortedAndUniqued(Protocols, NumProtocols)) {
2176 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2177 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2178 unsigned UniqueCount = NumProtocols;
2179
2180 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2181 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2182
2183 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2184 &Sorted[0], UniqueCount);
2185 } else {
2186 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2187 Protocols, NumProtocols);
2188 }
2189
2190 // Regenerate InsertPos.
2191 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2192 }
2193
Douglas Gregorf85bee62010-02-08 22:59:26 +00002194 // No match.
2195 unsigned Size = sizeof(ObjCObjectPointerType)
2196 + NumProtocols * sizeof(ObjCProtocolDecl *);
2197 void *Mem = Allocate(Size, TypeAlignment);
2198 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2199 InterfaceT,
2200 Protocols,
2201 NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Steve Narofffb4330f2009-06-17 22:40:22 +00002203 Types.push_back(QType);
2204 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2205 return QualType(QType, 0);
2206}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002207
Steve Naroffc277ad12009-07-18 15:33:26 +00002208/// getObjCInterfaceType - Return the unique reference to the type for the
2209/// specified ObjC interface decl. The list of protocols is optional.
2210QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002211 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002212 llvm::FoldingSetNodeID ID;
Steve Naroffc277ad12009-07-18 15:33:26 +00002213 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002214
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002215 void *InsertPos = 0;
Steve Naroffc277ad12009-07-18 15:33:26 +00002216 if (ObjCInterfaceType *QT =
2217 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002218 return QualType(QT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002219
John McCallfc93cf92009-10-22 22:37:11 +00002220 // Sort the protocol list alphabetically to canonicalize it.
2221 QualType Canonical;
2222 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2223 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2224 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2225
2226 unsigned UniqueCount = NumProtocols;
2227 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2228
2229 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2230
2231 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 }
2233
Douglas Gregorf85bee62010-02-08 22:59:26 +00002234 unsigned Size = sizeof(ObjCInterfaceType)
2235 + NumProtocols * sizeof(ObjCProtocolDecl *);
2236 void *Mem = Allocate(Size, TypeAlignment);
2237 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2238 const_cast<ObjCInterfaceDecl*>(Decl),
2239 Protocols,
2240 NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002241
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002242 Types.push_back(QType);
Steve Naroffc277ad12009-07-18 15:33:26 +00002243 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002244 return QualType(QType, 0);
2245}
2246
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002247/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2248/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002249/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002250/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002251/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002252QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002253 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002254 if (tofExpr->isTypeDependent()) {
2255 llvm::FoldingSetNodeID ID;
2256 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002257
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002258 void *InsertPos = 0;
2259 DependentTypeOfExprType *Canon
2260 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2261 if (Canon) {
2262 // We already have a "canonical" version of an identical, dependent
2263 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002264 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002265 QualType((TypeOfExprType*)Canon, 0));
2266 }
2267 else {
2268 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002269 Canon
2270 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002271 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2272 toe = Canon;
2273 }
2274 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002275 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002276 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002277 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002278 Types.push_back(toe);
2279 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002280}
2281
Steve Naroffa773cd52007-08-01 18:02:17 +00002282/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2283/// TypeOfType AST's. The only motivation to unique these nodes would be
2284/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002285/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002286/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002287QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002288 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002289 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002290 Types.push_back(tot);
2291 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002292}
2293
Anders Carlssonad6bd352009-06-24 21:24:56 +00002294/// getDecltypeForExpr - Given an expr, will return the decltype for that
2295/// expression, according to the rules in C++0x [dcl.type.simple]p4
2296static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002297 if (e->isTypeDependent())
2298 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002299
Anders Carlssonad6bd352009-06-24 21:24:56 +00002300 // If e is an id expression or a class member access, decltype(e) is defined
2301 // as the type of the entity named by e.
2302 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2303 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2304 return VD->getType();
2305 }
2306 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2307 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2308 return FD->getType();
2309 }
2310 // If e is a function call or an invocation of an overloaded operator,
2311 // (parentheses around e are ignored), decltype(e) is defined as the
2312 // return type of that function.
2313 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2314 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002315
Anders Carlssonad6bd352009-06-24 21:24:56 +00002316 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002317
2318 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002319 // defined as T&, otherwise decltype(e) is defined as T.
2320 if (e->isLvalue(Context) == Expr::LV_Valid)
2321 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002322
Anders Carlssonad6bd352009-06-24 21:24:56 +00002323 return T;
2324}
2325
Anders Carlsson81df7b82009-06-24 19:06:50 +00002326/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2327/// DecltypeType AST's. The only motivation to unique these nodes would be
2328/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002329/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002330/// on canonical type's (which are always unique).
2331QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002332 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002333 if (e->isTypeDependent()) {
2334 llvm::FoldingSetNodeID ID;
2335 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregora21f6c32009-07-30 23:36:40 +00002337 void *InsertPos = 0;
2338 DependentDecltypeType *Canon
2339 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2340 if (Canon) {
2341 // We already have a "canonical" version of an equivalent, dependent
2342 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002343 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002344 QualType((DecltypeType*)Canon, 0));
2345 }
2346 else {
2347 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002348 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002349 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2350 dt = Canon;
2351 }
2352 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002353 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002354 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002355 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002356 Types.push_back(dt);
2357 return QualType(dt, 0);
2358}
2359
Chris Lattnerfb072462007-01-23 05:45:31 +00002360/// getTagDeclType - Return the unique reference to the type for the
2361/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002362QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002363 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002364 // FIXME: What is the design on getTagDeclType when it requires casting
2365 // away const? mutable?
2366 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002367}
2368
Mike Stump11289f42009-09-09 15:08:12 +00002369/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2370/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2371/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002372CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002373 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002374}
Chris Lattnerfb072462007-01-23 05:45:31 +00002375
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002376/// getSignedWCharType - Return the type of "signed wchar_t".
2377/// Used when in C++, as a GCC extension.
2378QualType ASTContext::getSignedWCharType() const {
2379 // FIXME: derive from "Target" ?
2380 return WCharTy;
2381}
2382
2383/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2384/// Used when in C++, as a GCC extension.
2385QualType ASTContext::getUnsignedWCharType() const {
2386 // FIXME: derive from "Target" ?
2387 return UnsignedIntTy;
2388}
2389
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002390/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2391/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2392QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002393 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002394}
2395
Chris Lattnera21ad802008-04-02 05:18:44 +00002396//===----------------------------------------------------------------------===//
2397// Type Operators
2398//===----------------------------------------------------------------------===//
2399
John McCallfc93cf92009-10-22 22:37:11 +00002400CanQualType ASTContext::getCanonicalParamType(QualType T) {
2401 // Push qualifiers into arrays, and then discard any remaining
2402 // qualifiers.
2403 T = getCanonicalType(T);
2404 const Type *Ty = T.getTypePtr();
2405
2406 QualType Result;
2407 if (isa<ArrayType>(Ty)) {
2408 Result = getArrayDecayedType(QualType(Ty,0));
2409 } else if (isa<FunctionType>(Ty)) {
2410 Result = getPointerType(QualType(Ty, 0));
2411 } else {
2412 Result = QualType(Ty, 0);
2413 }
2414
2415 return CanQualType::CreateUnsafe(Result);
2416}
2417
Chris Lattnered0d0792008-04-06 22:41:35 +00002418/// getCanonicalType - Return the canonical (structural) type corresponding to
2419/// the specified potentially non-canonical type. The non-canonical version
2420/// of a type may have many "decorated" versions of types. Decorators can
2421/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2422/// to be free of any of these, allowing two canonical types to be compared
2423/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002424CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002425 QualifierCollector Quals;
2426 const Type *Ptr = Quals.strip(T);
2427 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002428
John McCall8ccfcb52009-09-24 19:53:00 +00002429 // The canonical internal type will be the canonical type *except*
2430 // that we push type qualifiers down through array types.
2431
2432 // If there are no new qualifiers to push down, stop here.
2433 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002434 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002435
John McCall8ccfcb52009-09-24 19:53:00 +00002436 // If the type qualifiers are on an array type, get the canonical
2437 // type of the array with the qualifiers applied to the element
2438 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002439 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2440 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002441 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattner7adf0762008-08-04 07:31:14 +00002443 // Get the canonical version of the element with the extra qualifiers on it.
2444 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002445 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002446 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002447
Chris Lattner7adf0762008-08-04 07:31:14 +00002448 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002449 return CanQualType::CreateUnsafe(
2450 getConstantArrayType(NewEltTy, CAT->getSize(),
2451 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002452 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002453 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002454 return CanQualType::CreateUnsafe(
2455 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002456 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002457
Douglas Gregor4619e432008-12-05 23:32:09 +00002458 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002459 return CanQualType::CreateUnsafe(
2460 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002461 DSAT->getSizeExpr() ?
2462 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002463 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002464 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002465 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002466
Chris Lattner7adf0762008-08-04 07:31:14 +00002467 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002468 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002469 VAT->getSizeExpr() ?
2470 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002471 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002472 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002473 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002474}
2475
Chandler Carruth607f38e2009-12-29 07:16:59 +00002476QualType ASTContext::getUnqualifiedArrayType(QualType T,
2477 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002478 Quals = T.getQualifiers();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002479 if (!isa<ArrayType>(T)) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002480 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002481 }
2482
Chandler Carruth607f38e2009-12-29 07:16:59 +00002483 const ArrayType *AT = cast<ArrayType>(T);
2484 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002485 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002486 if (Elt == UnqualElt)
2487 return T;
2488
2489 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2490 return getConstantArrayType(UnqualElt, CAT->getSize(),
2491 CAT->getSizeModifier(), 0);
2492 }
2493
2494 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2495 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2496 }
2497
2498 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2499 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2500 DSAT->getSizeModifier(), 0,
2501 SourceRange());
2502}
2503
John McCall847e2a12009-11-24 18:42:40 +00002504DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2505 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2506 return TD->getDeclName();
2507
2508 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2509 if (DTN->isIdentifier()) {
2510 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2511 } else {
2512 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2513 }
2514 }
2515
John McCalld28ae272009-12-02 08:04:21 +00002516 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2517 assert(Storage);
2518 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002519}
2520
Douglas Gregor6bc50582009-05-07 06:41:52 +00002521TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2522 // If this template name refers to a template, the canonical
2523 // template name merely stores the template itself.
2524 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002525 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002526
John McCalld28ae272009-12-02 08:04:21 +00002527 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002528
Douglas Gregor6bc50582009-05-07 06:41:52 +00002529 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2530 assert(DTN && "Non-dependent template names must refer to template decls.");
2531 return DTN->CanonicalTemplateName;
2532}
2533
Douglas Gregoradee3e32009-11-11 23:06:43 +00002534bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2535 X = getCanonicalTemplateName(X);
2536 Y = getCanonicalTemplateName(Y);
2537 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2538}
2539
Mike Stump11289f42009-09-09 15:08:12 +00002540TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002541ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2542 switch (Arg.getKind()) {
2543 case TemplateArgument::Null:
2544 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002545
Douglas Gregora8e02e72009-07-28 23:00:59 +00002546 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002547 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002548
Douglas Gregora8e02e72009-07-28 23:00:59 +00002549 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002550 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002551
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002552 case TemplateArgument::Template:
2553 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2554
Douglas Gregora8e02e72009-07-28 23:00:59 +00002555 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002556 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002557 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002558
Douglas Gregora8e02e72009-07-28 23:00:59 +00002559 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002560 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002561
Douglas Gregora8e02e72009-07-28 23:00:59 +00002562 case TemplateArgument::Pack: {
2563 // FIXME: Allocate in ASTContext
2564 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2565 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002566 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002567 AEnd = Arg.pack_end();
2568 A != AEnd; (void)++A, ++Idx)
2569 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002570
Douglas Gregora8e02e72009-07-28 23:00:59 +00002571 TemplateArgument Result;
2572 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2573 return Result;
2574 }
2575 }
2576
2577 // Silence GCC warning
2578 assert(false && "Unhandled template argument kind");
2579 return TemplateArgument();
2580}
2581
Douglas Gregor333489b2009-03-27 23:10:48 +00002582NestedNameSpecifier *
2583ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002584 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002585 return 0;
2586
2587 switch (NNS->getKind()) {
2588 case NestedNameSpecifier::Identifier:
2589 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002590 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002591 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2592 NNS->getAsIdentifier());
2593
2594 case NestedNameSpecifier::Namespace:
2595 // A namespace is canonical; build a nested-name-specifier with
2596 // this namespace and no prefix.
2597 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2598
2599 case NestedNameSpecifier::TypeSpec:
2600 case NestedNameSpecifier::TypeSpecWithTemplate: {
2601 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002602 return NestedNameSpecifier::Create(*this, 0,
2603 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002604 T.getTypePtr());
2605 }
2606
2607 case NestedNameSpecifier::Global:
2608 // The global specifier is canonical and unique.
2609 return NNS;
2610 }
2611
2612 // Required to silence a GCC warning
2613 return 0;
2614}
2615
Chris Lattner7adf0762008-08-04 07:31:14 +00002616
2617const ArrayType *ASTContext::getAsArrayType(QualType T) {
2618 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002619 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002620 // Handle the common positive case fast.
2621 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2622 return AT;
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
John McCall8ccfcb52009-09-24 19:53:00 +00002625 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002626 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002627 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002628 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002629
John McCall8ccfcb52009-09-24 19:53:00 +00002630 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002631 // implements C99 6.7.3p8: "If the specification of an array type includes
2632 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002633
Chris Lattner7adf0762008-08-04 07:31:14 +00002634 // If we get here, we either have type qualifiers on the type, or we have
2635 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002636 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002637
John McCall8ccfcb52009-09-24 19:53:00 +00002638 QualifierCollector Qs;
2639 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002640
Chris Lattner7adf0762008-08-04 07:31:14 +00002641 // If we have a simple case, just return now.
2642 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002643 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002644 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002645
Chris Lattner7adf0762008-08-04 07:31:14 +00002646 // Otherwise, we have an array and we have qualifiers on it. Push the
2647 // qualifiers into the array element type and return a new array type.
2648 // Get the canonical version of the element with the extra qualifiers on it.
2649 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002650 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002651
Chris Lattner7adf0762008-08-04 07:31:14 +00002652 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2653 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2654 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002655 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002656 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2657 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2658 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002659 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002660
Mike Stump11289f42009-09-09 15:08:12 +00002661 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002662 = dyn_cast<DependentSizedArrayType>(ATy))
2663 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002664 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002665 DSAT->getSizeExpr() ?
2666 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002667 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002668 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002669 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chris Lattner7adf0762008-08-04 07:31:14 +00002671 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002672 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002673 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002674 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002675 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002676 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002677 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002678}
2679
2680
Chris Lattnera21ad802008-04-02 05:18:44 +00002681/// getArrayDecayedType - Return the properly qualified result of decaying the
2682/// specified array type to a pointer. This operation is non-trivial when
2683/// handling typedefs etc. The canonical type of "T" must be an array type,
2684/// this returns a pointer to a properly qualified element of the array.
2685///
2686/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2687QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002688 // Get the element type with 'getAsArrayType' so that we don't lose any
2689 // typedefs in the element type of the array. This also handles propagation
2690 // of type qualifiers from the array type into the element type if present
2691 // (C99 6.7.3p8).
2692 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2693 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002694
Chris Lattner7adf0762008-08-04 07:31:14 +00002695 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002696
2697 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002698 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002699}
2700
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002701QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002702 QualifierCollector Qs;
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002703 while (true) {
John McCall8ccfcb52009-09-24 19:53:00 +00002704 const Type *UT = Qs.strip(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002705 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2706 QT = AT->getElementType();
Mike Stumpea086c72009-07-25 23:24:03 +00002707 } else {
John McCall8ccfcb52009-09-24 19:53:00 +00002708 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002709 }
2710 }
2711}
2712
Anders Carlsson4bf82142009-09-25 01:23:32 +00002713QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2714 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002715
Anders Carlsson4bf82142009-09-25 01:23:32 +00002716 if (const ArrayType *AT = getAsArrayType(ElemTy))
2717 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002718
Anders Carlssone0808df2008-12-21 03:44:36 +00002719 return ElemTy;
2720}
2721
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002722/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002723uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002724ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2725 uint64_t ElementCount = 1;
2726 do {
2727 ElementCount *= CA->getSize().getZExtValue();
2728 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2729 } while (CA);
2730 return ElementCount;
2731}
2732
Steve Naroff0af91202007-04-27 21:51:21 +00002733/// getFloatingRank - Return a relative rank for floating point types.
2734/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002735static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002736 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002737 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002738
John McCall9dd450b2009-09-21 23:43:11 +00002739 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2740 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002741 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002742 case BuiltinType::Float: return FloatRank;
2743 case BuiltinType::Double: return DoubleRank;
2744 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002745 }
2746}
2747
Mike Stump11289f42009-09-09 15:08:12 +00002748/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2749/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002750/// 'typeDomain' is a real floating point or complex type.
2751/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002752QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2753 QualType Domain) const {
2754 FloatingRank EltRank = getFloatingRank(Size);
2755 if (Domain->isComplexType()) {
2756 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002757 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002758 case FloatRank: return FloatComplexTy;
2759 case DoubleRank: return DoubleComplexTy;
2760 case LongDoubleRank: return LongDoubleComplexTy;
2761 }
Steve Naroff0af91202007-04-27 21:51:21 +00002762 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002763
2764 assert(Domain->isRealFloatingType() && "Unknown domain!");
2765 switch (EltRank) {
2766 default: assert(0 && "getFloatingRank(): illegal value for rank");
2767 case FloatRank: return FloatTy;
2768 case DoubleRank: return DoubleTy;
2769 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002770 }
Steve Naroffe4718892007-04-27 18:30:00 +00002771}
2772
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002773/// getFloatingTypeOrder - Compare the rank of the two specified floating
2774/// point types, ignoring the domain of the type (i.e. 'double' ==
2775/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002776/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002777int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2778 FloatingRank LHSR = getFloatingRank(LHS);
2779 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002780
Chris Lattnerb90739d2008-04-06 23:38:49 +00002781 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002782 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002783 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002784 return 1;
2785 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002786}
2787
Chris Lattner76a00cf2008-04-06 22:59:24 +00002788/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2789/// routine will assert if passed a built-in type that isn't an integer or enum,
2790/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002791unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002792 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002793 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002794 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002795
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002796 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2797 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2798
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002799 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2800 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2801
2802 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2803 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2804
Chris Lattner76a00cf2008-04-06 22:59:24 +00002805 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002806 default: assert(0 && "getIntegerRank(): not a built-in integer");
2807 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002808 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002809 case BuiltinType::Char_S:
2810 case BuiltinType::Char_U:
2811 case BuiltinType::SChar:
2812 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002813 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002814 case BuiltinType::Short:
2815 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002816 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002817 case BuiltinType::Int:
2818 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002819 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002820 case BuiltinType::Long:
2821 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002822 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002823 case BuiltinType::LongLong:
2824 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002825 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002826 case BuiltinType::Int128:
2827 case BuiltinType::UInt128:
2828 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002829 }
2830}
2831
Eli Friedman629ffb92009-08-20 04:21:42 +00002832/// \brief Whether this is a promotable bitfield reference according
2833/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2834///
2835/// \returns the type this bit-field will promote to, or NULL if no
2836/// promotion occurs.
2837QualType ASTContext::isPromotableBitField(Expr *E) {
2838 FieldDecl *Field = E->getBitField();
2839 if (!Field)
2840 return QualType();
2841
2842 QualType FT = Field->getType();
2843
2844 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2845 uint64_t BitWidth = BitWidthAP.getZExtValue();
2846 uint64_t IntSize = getTypeSize(IntTy);
2847 // GCC extension compatibility: if the bit-field size is less than or equal
2848 // to the size of int, it gets promoted no matter what its type is.
2849 // For instance, unsigned long bf : 4 gets promoted to signed int.
2850 if (BitWidth < IntSize)
2851 return IntTy;
2852
2853 if (BitWidth == IntSize)
2854 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2855
2856 // Types bigger than int are not subject to promotions, and therefore act
2857 // like the base type.
2858 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2859 // is ridiculous.
2860 return QualType();
2861}
2862
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002863/// getPromotedIntegerType - Returns the type that Promotable will
2864/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2865/// integer type.
2866QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2867 assert(!Promotable.isNull());
2868 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002869 if (const EnumType *ET = Promotable->getAs<EnumType>())
2870 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002871 if (Promotable->isSignedIntegerType())
2872 return IntTy;
2873 uint64_t PromotableSize = getTypeSize(Promotable);
2874 uint64_t IntSize = getTypeSize(IntTy);
2875 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2876 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2877}
2878
Mike Stump11289f42009-09-09 15:08:12 +00002879/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002880/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002881/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002882int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002883 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2884 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002885 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002886
Chris Lattner76a00cf2008-04-06 22:59:24 +00002887 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2888 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002889
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002890 unsigned LHSRank = getIntegerRank(LHSC);
2891 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002893 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2894 if (LHSRank == RHSRank) return 0;
2895 return LHSRank > RHSRank ? 1 : -1;
2896 }
Mike Stump11289f42009-09-09 15:08:12 +00002897
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002898 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2899 if (LHSUnsigned) {
2900 // If the unsigned [LHS] type is larger, return it.
2901 if (LHSRank >= RHSRank)
2902 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002903
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002904 // If the signed type can represent all values of the unsigned type, it
2905 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002906 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002907 return -1;
2908 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002909
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002910 // If the unsigned [RHS] type is larger, return it.
2911 if (RHSRank >= LHSRank)
2912 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002913
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002914 // If the signed type can represent all values of the unsigned type, it
2915 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002916 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002917 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002918}
Anders Carlsson98f07902007-08-17 05:31:46 +00002919
Anders Carlsson6d417272009-11-14 21:45:58 +00002920static RecordDecl *
2921CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2922 SourceLocation L, IdentifierInfo *Id) {
2923 if (Ctx.getLangOptions().CPlusPlus)
2924 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2925 else
2926 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2927}
2928
Mike Stump11289f42009-09-09 15:08:12 +00002929// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002930QualType ASTContext::getCFConstantStringType() {
2931 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002932 CFConstantStringTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00002933 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2934 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002935 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002936
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002937 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002938
Anders Carlsson98f07902007-08-17 05:31:46 +00002939 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002940 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002941 // int flags;
2942 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002943 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002944 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002945 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002946 FieldTypes[3] = LongTy;
2947
Anders Carlsson98f07902007-08-17 05:31:46 +00002948 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002949 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002950 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002951 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002952 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002953 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002954 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002955 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002956 }
2957
Douglas Gregord5058122010-02-11 01:19:42 +00002958 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002959 }
Mike Stump11289f42009-09-09 15:08:12 +00002960
Anders Carlsson98f07902007-08-17 05:31:46 +00002961 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002962}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002963
Douglas Gregor512b0772009-04-23 22:29:11 +00002964void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002965 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002966 assert(Rec && "Invalid CFConstantStringType");
2967 CFConstantStringTypeDecl = Rec->getDecl();
2968}
2969
Mike Stump11289f42009-09-09 15:08:12 +00002970QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002971 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00002972 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00002973 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2974 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00002975 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002976
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002977 QualType FieldTypes[] = {
2978 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00002979 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002980 getPointerType(UnsignedLongTy),
2981 getConstantArrayType(UnsignedLongTy,
2982 llvm::APInt(32, 5), ArrayType::Normal, 0)
2983 };
Mike Stump11289f42009-09-09 15:08:12 +00002984
Douglas Gregor91f84212008-12-11 16:49:14 +00002985 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002986 FieldDecl *Field = FieldDecl::Create(*this,
2987 ObjCFastEnumerationStateTypeDecl,
2988 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002989 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002990 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002991 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002992 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002993 }
Mike Stump11289f42009-09-09 15:08:12 +00002994
Douglas Gregord5058122010-02-11 01:19:42 +00002995 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002996 }
Mike Stump11289f42009-09-09 15:08:12 +00002997
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002998 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2999}
3000
Mike Stumpd0153282009-10-20 02:12:22 +00003001QualType ASTContext::getBlockDescriptorType() {
3002 if (BlockDescriptorType)
3003 return getTagDeclType(BlockDescriptorType);
3004
3005 RecordDecl *T;
3006 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003007 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3008 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003009 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003010
3011 QualType FieldTypes[] = {
3012 UnsignedLongTy,
3013 UnsignedLongTy,
3014 };
3015
3016 const char *FieldNames[] = {
3017 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003018 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003019 };
3020
3021 for (size_t i = 0; i < 2; ++i) {
3022 FieldDecl *Field = FieldDecl::Create(*this,
3023 T,
3024 SourceLocation(),
3025 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003026 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003027 /*BitWidth=*/0,
3028 /*Mutable=*/false);
3029 T->addDecl(Field);
3030 }
3031
Douglas Gregord5058122010-02-11 01:19:42 +00003032 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003033
3034 BlockDescriptorType = T;
3035
3036 return getTagDeclType(BlockDescriptorType);
3037}
3038
3039void ASTContext::setBlockDescriptorType(QualType T) {
3040 const RecordType *Rec = T->getAs<RecordType>();
3041 assert(Rec && "Invalid BlockDescriptorType");
3042 BlockDescriptorType = Rec->getDecl();
3043}
3044
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003045QualType ASTContext::getBlockDescriptorExtendedType() {
3046 if (BlockDescriptorExtendedType)
3047 return getTagDeclType(BlockDescriptorExtendedType);
3048
3049 RecordDecl *T;
3050 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003051 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3052 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003053 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003054
3055 QualType FieldTypes[] = {
3056 UnsignedLongTy,
3057 UnsignedLongTy,
3058 getPointerType(VoidPtrTy),
3059 getPointerType(VoidPtrTy)
3060 };
3061
3062 const char *FieldNames[] = {
3063 "reserved",
3064 "Size",
3065 "CopyFuncPtr",
3066 "DestroyFuncPtr"
3067 };
3068
3069 for (size_t i = 0; i < 4; ++i) {
3070 FieldDecl *Field = FieldDecl::Create(*this,
3071 T,
3072 SourceLocation(),
3073 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003074 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003075 /*BitWidth=*/0,
3076 /*Mutable=*/false);
3077 T->addDecl(Field);
3078 }
3079
Douglas Gregord5058122010-02-11 01:19:42 +00003080 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003081
3082 BlockDescriptorExtendedType = T;
3083
3084 return getTagDeclType(BlockDescriptorExtendedType);
3085}
3086
3087void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3088 const RecordType *Rec = T->getAs<RecordType>();
3089 assert(Rec && "Invalid BlockDescriptorType");
3090 BlockDescriptorExtendedType = Rec->getDecl();
3091}
3092
Mike Stump94967902009-10-21 18:16:27 +00003093bool ASTContext::BlockRequiresCopying(QualType Ty) {
3094 if (Ty->isBlockPointerType())
3095 return true;
3096 if (isObjCNSObjectType(Ty))
3097 return true;
3098 if (Ty->isObjCObjectPointerType())
3099 return true;
3100 return false;
3101}
3102
3103QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3104 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003105 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003106 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003107 // unsigned int __flags;
3108 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003109 // void *__copy_helper; // as needed
3110 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003111 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003112 // } *
3113
Mike Stump94967902009-10-21 18:16:27 +00003114 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3115
3116 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003117 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003118 llvm::SmallString<36> Name;
3119 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3120 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003121 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003122 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3123 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003124 T->startDefinition();
3125 QualType Int32Ty = IntTy;
3126 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3127 QualType FieldTypes[] = {
3128 getPointerType(VoidPtrTy),
3129 getPointerType(getTagDeclType(T)),
3130 Int32Ty,
3131 Int32Ty,
3132 getPointerType(VoidPtrTy),
3133 getPointerType(VoidPtrTy),
3134 Ty
3135 };
3136
3137 const char *FieldNames[] = {
3138 "__isa",
3139 "__forwarding",
3140 "__flags",
3141 "__size",
3142 "__copy_helper",
3143 "__destroy_helper",
3144 DeclName,
3145 };
3146
3147 for (size_t i = 0; i < 7; ++i) {
3148 if (!HasCopyAndDispose && i >=4 && i <= 5)
3149 continue;
3150 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3151 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003152 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003153 /*BitWidth=*/0, /*Mutable=*/false);
3154 T->addDecl(Field);
3155 }
3156
Douglas Gregord5058122010-02-11 01:19:42 +00003157 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003158
3159 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003160}
3161
3162
3163QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003164 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003165 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003166 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003167 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003168 llvm::SmallString<36> Name;
3169 llvm::raw_svector_ostream(Name) << "__block_literal_"
3170 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003171 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003172 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3173 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003174 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003175 QualType FieldTypes[] = {
3176 getPointerType(VoidPtrTy),
3177 IntTy,
3178 IntTy,
3179 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003180 (BlockHasCopyDispose ?
3181 getPointerType(getBlockDescriptorExtendedType()) :
3182 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003183 };
3184
3185 const char *FieldNames[] = {
3186 "__isa",
3187 "__flags",
3188 "__reserved",
3189 "__FuncPtr",
3190 "__descriptor"
3191 };
3192
3193 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003194 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003195 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003196 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003197 /*BitWidth=*/0, /*Mutable=*/false);
3198 T->addDecl(Field);
3199 }
3200
3201 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3202 const Expr *E = BlockDeclRefDecls[i];
3203 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3204 clang::IdentifierInfo *Name = 0;
3205 if (BDRE) {
3206 const ValueDecl *D = BDRE->getDecl();
3207 Name = &Idents.get(D->getName());
3208 }
3209 QualType FieldType = E->getType();
3210
3211 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003212 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3213 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003214
3215 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003216 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003217 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpd0153282009-10-20 02:12:22 +00003218 T->addDecl(Field);
3219 }
3220
Douglas Gregord5058122010-02-11 01:19:42 +00003221 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003222
3223 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003224}
3225
Douglas Gregor512b0772009-04-23 22:29:11 +00003226void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003227 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003228 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3229 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3230}
3231
Anders Carlsson18acd442007-10-29 06:33:42 +00003232// This returns true if a type has been typedefed to BOOL:
3233// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003234static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003235 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003236 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3237 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003238
Anders Carlssond8499822007-10-29 05:01:08 +00003239 return false;
3240}
3241
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003242/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003243/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003244CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003245 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003246
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003247 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003248 if (sz.isPositive() && type->isIntegralType())
3249 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003250 // Treat arrays as pointers, since that's how they're passed in.
3251 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003252 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003253 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003254}
3255
3256static inline
3257std::string charUnitsToString(const CharUnits &CU) {
3258 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003259}
3260
David Chisnall950a9512009-11-17 19:33:30 +00003261/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3262/// declaration.
3263void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3264 std::string& S) {
3265 const BlockDecl *Decl = Expr->getBlockDecl();
3266 QualType BlockTy =
3267 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3268 // Encode result type.
3269 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3270 // Compute size of all parameters.
3271 // Start with computing size of a pointer in number of bytes.
3272 // FIXME: There might(should) be a better way of doing this computation!
3273 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003274 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3275 CharUnits ParmOffset = PtrSize;
David Chisnall950a9512009-11-17 19:33:30 +00003276 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3277 E = Decl->param_end(); PI != E; ++PI) {
3278 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003279 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003280 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003281 ParmOffset += sz;
3282 }
3283 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003284 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003285 // Block pointer and offset.
3286 S += "@?0";
3287 ParmOffset = PtrSize;
3288
3289 // Argument types.
3290 ParmOffset = PtrSize;
3291 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3292 Decl->param_end(); PI != E; ++PI) {
3293 ParmVarDecl *PVDecl = *PI;
3294 QualType PType = PVDecl->getOriginalType();
3295 if (const ArrayType *AT =
3296 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3297 // Use array's original type only if it has known number of
3298 // elements.
3299 if (!isa<ConstantArrayType>(AT))
3300 PType = PVDecl->getType();
3301 } else if (PType->isFunctionType())
3302 PType = PVDecl->getType();
3303 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003304 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003305 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003306 }
3307}
3308
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003309/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003310/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003311void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003312 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003313 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003314 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003315 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003316 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003317 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003318 // Compute size of all parameters.
3319 // Start with computing size of a pointer in number of bytes.
3320 // FIXME: There might(should) be a better way of doing this computation!
3321 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003322 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003323 // The first two arguments (self and _cmd) are pointers; account for
3324 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003325 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003326 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3327 E = Decl->param_end(); PI != E; ++PI) {
3328 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003329 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003330 assert (sz.isPositive() &&
3331 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003332 ParmOffset += sz;
3333 }
Ken Dyck40775002010-01-11 17:06:35 +00003334 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003335 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003336 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003337
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003338 // Argument types.
3339 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003340 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3341 E = Decl->param_end(); PI != E; ++PI) {
3342 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003343 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003344 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003345 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3346 // Use array's original type only if it has known number of
3347 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003348 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003349 PType = PVDecl->getType();
3350 } else if (PType->isFunctionType())
3351 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003352 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003353 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003354 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003355 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003356 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003357 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003358 }
3359}
3360
Daniel Dunbar4932b362008-08-28 04:38:10 +00003361/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003362/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003363/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3364/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003365/// Property attributes are stored as a comma-delimited C string. The simple
3366/// attributes readonly and bycopy are encoded as single characters. The
3367/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3368/// encoded as single characters, followed by an identifier. Property types
3369/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003370/// these attributes are defined by the following enumeration:
3371/// @code
3372/// enum PropertyAttributes {
3373/// kPropertyReadOnly = 'R', // property is read-only.
3374/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3375/// kPropertyByref = '&', // property is a reference to the value last assigned
3376/// kPropertyDynamic = 'D', // property is dynamic
3377/// kPropertyGetter = 'G', // followed by getter selector name
3378/// kPropertySetter = 'S', // followed by setter selector name
3379/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3380/// kPropertyType = 't' // followed by old-style type encoding.
3381/// kPropertyWeak = 'W' // 'weak' property
3382/// kPropertyStrong = 'P' // property GC'able
3383/// kPropertyNonAtomic = 'N' // property non-atomic
3384/// };
3385/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003386void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003387 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003388 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003389 // Collect information from the property implementation decl(s).
3390 bool Dynamic = false;
3391 ObjCPropertyImplDecl *SynthesizePID = 0;
3392
3393 // FIXME: Duplicated code due to poor abstraction.
3394 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003395 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003396 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3397 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003398 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003399 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003400 ObjCPropertyImplDecl *PID = *i;
3401 if (PID->getPropertyDecl() == PD) {
3402 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3403 Dynamic = true;
3404 } else {
3405 SynthesizePID = PID;
3406 }
3407 }
3408 }
3409 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003410 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003411 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003412 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003413 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003414 ObjCPropertyImplDecl *PID = *i;
3415 if (PID->getPropertyDecl() == PD) {
3416 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3417 Dynamic = true;
3418 } else {
3419 SynthesizePID = PID;
3420 }
3421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003423 }
3424 }
3425
3426 // FIXME: This is not very efficient.
3427 S = "T";
3428
3429 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003430 // GCC has some special rules regarding encoding of properties which
3431 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003432 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003433 true /* outermost type */,
3434 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003435
3436 if (PD->isReadOnly()) {
3437 S += ",R";
3438 } else {
3439 switch (PD->getSetterKind()) {
3440 case ObjCPropertyDecl::Assign: break;
3441 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003442 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003443 }
3444 }
3445
3446 // It really isn't clear at all what this means, since properties
3447 // are "dynamic by default".
3448 if (Dynamic)
3449 S += ",D";
3450
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003451 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3452 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003453
Daniel Dunbar4932b362008-08-28 04:38:10 +00003454 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3455 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003456 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003457 }
3458
3459 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3460 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003461 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003462 }
3463
3464 if (SynthesizePID) {
3465 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3466 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003467 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003468 }
3469
3470 // FIXME: OBJCGC: weak & strong
3471}
3472
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003473/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003474/// Another legacy compatibility encoding: 32-bit longs are encoded as
3475/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003476/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3477///
3478void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003479 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003480 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003481 if (BT->getKind() == BuiltinType::ULong &&
3482 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003483 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003484 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003485 if (BT->getKind() == BuiltinType::Long &&
3486 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003487 PointeeTy = IntTy;
3488 }
3489 }
3490}
3491
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003492void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003493 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003494 // We follow the behavior of gcc, expanding structures which are
3495 // directly pointed to, and expanding embedded structures. Note that
3496 // these rules are sufficient to prevent recursive encoding of the
3497 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003498 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003499 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003500}
3501
Mike Stump11289f42009-09-09 15:08:12 +00003502static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003503 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003504 const Expr *E = FD->getBitWidth();
3505 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3506 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003507 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003508 S += 'b';
3509 S += llvm::utostr(N);
3510}
3511
Daniel Dunbar07d07852009-10-18 21:17:35 +00003512// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003513void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3514 bool ExpandPointedToStructures,
3515 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003516 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003517 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003518 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003519 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003520 if (FD && FD->isBitField())
3521 return EncodeBitField(this, S, FD);
3522 char encoding;
3523 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003524 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003525 case BuiltinType::Void: encoding = 'v'; break;
3526 case BuiltinType::Bool: encoding = 'B'; break;
3527 case BuiltinType::Char_U:
3528 case BuiltinType::UChar: encoding = 'C'; break;
3529 case BuiltinType::UShort: encoding = 'S'; break;
3530 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003531 case BuiltinType::ULong:
3532 encoding =
3533 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003534 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003535 case BuiltinType::UInt128: encoding = 'T'; break;
3536 case BuiltinType::ULongLong: encoding = 'Q'; break;
3537 case BuiltinType::Char_S:
3538 case BuiltinType::SChar: encoding = 'c'; break;
3539 case BuiltinType::Short: encoding = 's'; break;
3540 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003541 case BuiltinType::Long:
3542 encoding =
3543 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003544 break;
3545 case BuiltinType::LongLong: encoding = 'q'; break;
3546 case BuiltinType::Int128: encoding = 't'; break;
3547 case BuiltinType::Float: encoding = 'f'; break;
3548 case BuiltinType::Double: encoding = 'd'; break;
3549 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003550 }
Mike Stump11289f42009-09-09 15:08:12 +00003551
Chris Lattnere7cabb92009-07-13 00:10:46 +00003552 S += encoding;
3553 return;
3554 }
Mike Stump11289f42009-09-09 15:08:12 +00003555
John McCall9dd450b2009-09-21 23:43:11 +00003556 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003557 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003558 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003559 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003560 return;
3561 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003562
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003563 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003564 if (PT->isObjCSelType()) {
3565 S += ':';
3566 return;
3567 }
Anders Carlssond8499822007-10-29 05:01:08 +00003568 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003569
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003570 bool isReadOnly = false;
3571 // For historical/compatibility reasons, the read-only qualifier of the
3572 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3573 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003574 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003575 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003576 if (OutermostType && T.isConstQualified()) {
3577 isReadOnly = true;
3578 S += 'r';
3579 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003580 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003581 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003582 while (P->getAs<PointerType>())
3583 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003584 if (P.isConstQualified()) {
3585 isReadOnly = true;
3586 S += 'r';
3587 }
3588 }
3589 if (isReadOnly) {
3590 // Another legacy compatibility encoding. Some ObjC qualifier and type
3591 // combinations need to be rearranged.
3592 // Rewrite "in const" from "nr" to "rn"
3593 const char * s = S.c_str();
3594 int len = S.length();
3595 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3596 std::string replace = "rn";
3597 S.replace(S.end()-2, S.end(), replace);
3598 }
3599 }
Mike Stump11289f42009-09-09 15:08:12 +00003600
Anders Carlssond8499822007-10-29 05:01:08 +00003601 if (PointeeTy->isCharType()) {
3602 // char pointer types should be encoded as '*' unless it is a
3603 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003604 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003605 S += '*';
3606 return;
3607 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003608 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003609 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3610 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3611 S += '#';
3612 return;
3613 }
3614 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3615 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3616 S += '@';
3617 return;
3618 }
3619 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003620 }
Anders Carlssond8499822007-10-29 05:01:08 +00003621 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003622 getLegacyIntegralTypeEncoding(PointeeTy);
3623
Mike Stump11289f42009-09-09 15:08:12 +00003624 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003625 NULL);
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 (const ArrayType *AT =
3630 // Ignore type qualifiers etc.
3631 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003632 if (isa<IncompleteArrayType>(AT)) {
3633 // Incomplete arrays are encoded as a pointer to the array element.
3634 S += '^';
3635
Mike Stump11289f42009-09-09 15:08:12 +00003636 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003637 false, ExpandStructures, FD);
3638 } else {
3639 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003640
Anders Carlssond05f44b2009-02-22 01:38:57 +00003641 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3642 S += llvm::utostr(CAT->getSize().getZExtValue());
3643 else {
3644 //Variable length arrays are encoded as a regular array with 0 elements.
3645 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3646 S += '0';
3647 }
Mike Stump11289f42009-09-09 15:08:12 +00003648
3649 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003650 false, ExpandStructures, FD);
3651 S += ']';
3652 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003653 return;
3654 }
Mike Stump11289f42009-09-09 15:08:12 +00003655
John McCall9dd450b2009-09-21 23:43:11 +00003656 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003657 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003658 return;
3659 }
Mike Stump11289f42009-09-09 15:08:12 +00003660
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003661 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003662 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003663 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003664 // Anonymous structures print as '?'
3665 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3666 S += II->getName();
3667 } else {
3668 S += '?';
3669 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003670 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003671 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003672 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3673 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003674 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003675 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003676 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003677 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003678 S += '"';
3679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003681 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003682 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003683 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003684 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003685 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003686 QualType qt = Field->getType();
3687 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003688 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003689 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003690 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003691 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003692 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003693 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003694 return;
3695 }
Mike Stump11289f42009-09-09 15:08:12 +00003696
Chris Lattnere7cabb92009-07-13 00:10:46 +00003697 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003698 if (FD && FD->isBitField())
3699 EncodeBitField(this, S, FD);
3700 else
3701 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003702 return;
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Chris Lattnere7cabb92009-07-13 00:10:46 +00003705 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003706 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003707 return;
3708 }
Mike Stump11289f42009-09-09 15:08:12 +00003709
John McCall8ccfcb52009-09-24 19:53:00 +00003710 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003711 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003712 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003713 S += '{';
3714 const IdentifierInfo *II = OI->getIdentifier();
3715 S += II->getName();
3716 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003717 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003718 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003719 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003720 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003721 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003722 RecFields[i]);
3723 else
Mike Stump11289f42009-09-09 15:08:12 +00003724 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003725 FD);
3726 }
3727 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003728 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003729 }
Mike Stump11289f42009-09-09 15:08:12 +00003730
John McCall9dd450b2009-09-21 23:43:11 +00003731 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003732 if (OPT->isObjCIdType()) {
3733 S += '@';
3734 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003735 }
Mike Stump11289f42009-09-09 15:08:12 +00003736
Steve Narofff0c86112009-10-28 22:03:49 +00003737 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3738 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3739 // Since this is a binary compatibility issue, need to consult with runtime
3740 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003741 S += '#';
3742 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
Chris Lattnere7cabb92009-07-13 00:10:46 +00003745 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003746 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003747 ExpandPointedToStructures,
3748 ExpandStructures, FD);
3749 if (FD || EncodingProperty) {
3750 // Note that we do extended encoding of protocol qualifer list
3751 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003752 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003753 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3754 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003755 S += '<';
3756 S += (*I)->getNameAsString();
3757 S += '>';
3758 }
3759 S += '"';
3760 }
3761 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003762 }
Mike Stump11289f42009-09-09 15:08:12 +00003763
Chris Lattnere7cabb92009-07-13 00:10:46 +00003764 QualType PointeeTy = OPT->getPointeeType();
3765 if (!EncodingProperty &&
3766 isa<TypedefType>(PointeeTy.getTypePtr())) {
3767 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003768 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003769 // {...};
3770 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003771 getObjCEncodingForTypeImpl(PointeeTy, S,
3772 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003773 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003774 return;
3775 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003776
3777 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003778 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003779 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003780 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003781 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3782 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003783 S += '<';
3784 S += (*I)->getNameAsString();
3785 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003786 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003787 S += '"';
3788 }
3789 return;
3790 }
Mike Stump11289f42009-09-09 15:08:12 +00003791
Chris Lattnere7cabb92009-07-13 00:10:46 +00003792 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003793}
3794
Mike Stump11289f42009-09-09 15:08:12 +00003795void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003796 std::string& S) const {
3797 if (QT & Decl::OBJC_TQ_In)
3798 S += 'n';
3799 if (QT & Decl::OBJC_TQ_Inout)
3800 S += 'N';
3801 if (QT & Decl::OBJC_TQ_Out)
3802 S += 'o';
3803 if (QT & Decl::OBJC_TQ_Bycopy)
3804 S += 'O';
3805 if (QT & Decl::OBJC_TQ_Byref)
3806 S += 'R';
3807 if (QT & Decl::OBJC_TQ_Oneway)
3808 S += 'V';
3809}
3810
Chris Lattnere7cabb92009-07-13 00:10:46 +00003811void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003812 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003813
Anders Carlsson87c149b2007-10-11 01:00:40 +00003814 BuiltinVaListType = T;
3815}
3816
Chris Lattnere7cabb92009-07-13 00:10:46 +00003817void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003818 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003819}
3820
Chris Lattnere7cabb92009-07-13 00:10:46 +00003821void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003822 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003823}
3824
Chris Lattnere7cabb92009-07-13 00:10:46 +00003825void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003826 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003827}
3828
Chris Lattnere7cabb92009-07-13 00:10:46 +00003829void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003830 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003831}
3832
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003833void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003834 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003835 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003836
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003837 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003838}
3839
John McCalld28ae272009-12-02 08:04:21 +00003840/// \brief Retrieve the template name that corresponds to a non-empty
3841/// lookup.
John McCallad371252010-01-20 00:46:10 +00003842TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3843 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003844 unsigned size = End - Begin;
3845 assert(size > 1 && "set is not overloaded!");
3846
3847 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3848 size * sizeof(FunctionTemplateDecl*));
3849 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3850
3851 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003852 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003853 NamedDecl *D = *I;
3854 assert(isa<FunctionTemplateDecl>(D) ||
3855 (isa<UsingShadowDecl>(D) &&
3856 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3857 *Storage++ = D;
3858 }
3859
3860 return TemplateName(OT);
3861}
3862
Douglas Gregordc572a32009-03-30 22:58:21 +00003863/// \brief Retrieve the template name that represents a qualified
3864/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003865TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003866 bool TemplateKeyword,
3867 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003868 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003869 llvm::FoldingSetNodeID ID;
3870 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3871
3872 void *InsertPos = 0;
3873 QualifiedTemplateName *QTN =
3874 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3875 if (!QTN) {
3876 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3877 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3878 }
3879
3880 return TemplateName(QTN);
3881}
3882
3883/// \brief Retrieve the template name that represents a dependent
3884/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003885TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003886 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003887 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003888 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003889
3890 llvm::FoldingSetNodeID ID;
3891 DependentTemplateName::Profile(ID, NNS, Name);
3892
3893 void *InsertPos = 0;
3894 DependentTemplateName *QTN =
3895 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3896
3897 if (QTN)
3898 return TemplateName(QTN);
3899
3900 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3901 if (CanonNNS == NNS) {
3902 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3903 } else {
3904 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3905 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003906 DependentTemplateName *CheckQTN =
3907 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3908 assert(!CheckQTN && "Dependent type name canonicalization broken");
3909 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00003910 }
3911
3912 DependentTemplateNames.InsertNode(QTN, InsertPos);
3913 return TemplateName(QTN);
3914}
3915
Douglas Gregor71395fa2009-11-04 00:56:37 +00003916/// \brief Retrieve the template name that represents a dependent
3917/// template name such as \c MetaFun::template operator+.
3918TemplateName
3919ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3920 OverloadedOperatorKind Operator) {
3921 assert((!NNS || NNS->isDependent()) &&
3922 "Nested name specifier must be dependent");
3923
3924 llvm::FoldingSetNodeID ID;
3925 DependentTemplateName::Profile(ID, NNS, Operator);
3926
3927 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003928 DependentTemplateName *QTN
3929 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00003930
3931 if (QTN)
3932 return TemplateName(QTN);
3933
3934 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3935 if (CanonNNS == NNS) {
3936 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3937 } else {
3938 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3939 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003940
3941 DependentTemplateName *CheckQTN
3942 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3943 assert(!CheckQTN && "Dependent template name canonicalization broken");
3944 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00003945 }
3946
3947 DependentTemplateNames.InsertNode(QTN, InsertPos);
3948 return TemplateName(QTN);
3949}
3950
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003951/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00003952/// TargetInfo, produce the corresponding type. The unsigned @p Type
3953/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00003954CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003955 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00003956 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003957 case TargetInfo::SignedShort: return ShortTy;
3958 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3959 case TargetInfo::SignedInt: return IntTy;
3960 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3961 case TargetInfo::SignedLong: return LongTy;
3962 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3963 case TargetInfo::SignedLongLong: return LongLongTy;
3964 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3965 }
3966
3967 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00003968 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003969}
Ted Kremenek77c51b22008-07-24 23:58:27 +00003970
3971//===----------------------------------------------------------------------===//
3972// Type Predicates.
3973//===----------------------------------------------------------------------===//
3974
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003975/// isObjCNSObjectType - Return true if this is an NSObject object using
3976/// NSObject attribute on a c-style pointer type.
3977/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00003978/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003979///
3980bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3981 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3982 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003983 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003984 return true;
3985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003987}
3988
Fariborz Jahanian96207692009-02-18 21:49:28 +00003989/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3990/// garbage collection attribute.
3991///
John McCall8ccfcb52009-09-24 19:53:00 +00003992Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3993 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003994 if (getLangOptions().ObjC1 &&
3995 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00003996 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00003997 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00003998 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003999 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004000 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004001 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004002 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004003 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004004 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004005 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004006 // Non-pointers have none gc'able attribute regardless of the attribute
4007 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004008 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004009 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004010 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004011 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004012}
4013
Chris Lattner49af6a42008-04-07 06:51:04 +00004014//===----------------------------------------------------------------------===//
4015// Type Compatibility Testing
4016//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004017
Mike Stump11289f42009-09-09 15:08:12 +00004018/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004019/// compatible.
4020static bool areCompatVectorTypes(const VectorType *LHS,
4021 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004022 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004023 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004024 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004025}
4026
Steve Naroff8e6aee52009-07-23 01:01:38 +00004027//===----------------------------------------------------------------------===//
4028// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4029//===----------------------------------------------------------------------===//
4030
4031/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4032/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004033bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4034 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004035 if (lProto == rProto)
4036 return true;
4037 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4038 E = rProto->protocol_end(); PI != E; ++PI)
4039 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4040 return true;
4041 return false;
4042}
4043
Steve Naroff8e6aee52009-07-23 01:01:38 +00004044/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4045/// return true if lhs's protocols conform to rhs's protocol; false
4046/// otherwise.
4047bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4048 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4049 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4050 return false;
4051}
4052
4053/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4054/// ObjCQualifiedIDType.
4055bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4056 bool compare) {
4057 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004058 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004059 lhs->isObjCIdType() || lhs->isObjCClassType())
4060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004061 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004062 rhs->isObjCIdType() || rhs->isObjCClassType())
4063 return true;
4064
4065 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004066 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004067
Steve Naroff8e6aee52009-07-23 01:01:38 +00004068 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004069
Steve Naroff8e6aee52009-07-23 01:01:38 +00004070 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004071 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004072 // make sure we check the class hierarchy.
4073 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4074 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4075 E = lhsQID->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 (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004080 return false;
4081 }
4082 }
4083 // If there are no qualifiers and no interface, we have an 'id'.
4084 return true;
4085 }
Mike Stump11289f42009-09-09 15:08:12 +00004086 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004087 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4088 E = lhsQID->qual_end(); I != E; ++I) {
4089 ObjCProtocolDecl *lhsProto = *I;
4090 bool match = false;
4091
4092 // when comparing an id<P> on lhs with a static type on rhs,
4093 // see if static class implements all of id's protocols, directly or
4094 // through its super class and categories.
4095 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4096 E = rhsOPT->qual_end(); J != E; ++J) {
4097 ObjCProtocolDecl *rhsProto = *J;
4098 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4099 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4100 match = true;
4101 break;
4102 }
4103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004105 // make sure we check the class hierarchy.
4106 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4107 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4108 E = lhsQID->qual_end(); I != E; ++I) {
4109 // when comparing an id<P> on lhs with a static type on rhs,
4110 // see if static class implements all of id's protocols, directly or
4111 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004112 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004113 match = true;
4114 break;
4115 }
4116 }
4117 }
4118 if (!match)
4119 return false;
4120 }
Mike Stump11289f42009-09-09 15:08:12 +00004121
Steve Naroff8e6aee52009-07-23 01:01:38 +00004122 return true;
4123 }
Mike Stump11289f42009-09-09 15:08:12 +00004124
Steve Naroff8e6aee52009-07-23 01:01:38 +00004125 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4126 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4127
Mike Stump11289f42009-09-09 15:08:12 +00004128 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004129 lhs->getAsObjCInterfacePointerType()) {
4130 if (lhsOPT->qual_empty()) {
4131 bool match = false;
4132 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4133 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4134 E = rhsQID->qual_end(); I != E; ++I) {
4135 // when comparing an id<P> on lhs with a static type on rhs,
4136 // see if static class implements all of id's protocols, directly or
4137 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004138 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004139 match = true;
4140 break;
4141 }
4142 }
4143 if (!match)
4144 return false;
4145 }
4146 return true;
4147 }
Mike Stump11289f42009-09-09 15:08:12 +00004148 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004149 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4150 E = lhsOPT->qual_end(); I != E; ++I) {
4151 ObjCProtocolDecl *lhsProto = *I;
4152 bool match = false;
4153
4154 // when comparing an id<P> on lhs with a static type on rhs,
4155 // see if static class implements all of id's protocols, directly or
4156 // through its super class and categories.
4157 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4158 E = rhsQID->qual_end(); J != E; ++J) {
4159 ObjCProtocolDecl *rhsProto = *J;
4160 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4161 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4162 match = true;
4163 break;
4164 }
4165 }
4166 if (!match)
4167 return false;
4168 }
4169 return true;
4170 }
4171 return false;
4172}
4173
Eli Friedman47f77112008-08-22 00:56:42 +00004174/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004175/// compatible for assignment from RHS to LHS. This handles validation of any
4176/// protocol qualifiers on the LHS or RHS.
4177///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004178bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4179 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004180 // If either type represents the built-in 'id' or 'Class' types, return true.
4181 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004182 return true;
4183
Steve Naroff8e6aee52009-07-23 01:01:38 +00004184 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00004185 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4186 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004187 false);
4188
Steve Naroff7cae42b2009-07-10 23:34:53 +00004189 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4190 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff8e6aee52009-07-23 01:01:38 +00004191 if (LHS && RHS) // We have 2 user-defined types.
4192 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004193
Steve Naroff8e6aee52009-07-23 01:01:38 +00004194 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004195}
4196
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004197/// getIntersectionOfProtocols - This routine finds the intersection of set
4198/// of protocols inherited from two distinct objective-c pointer objects.
4199/// It is used to build composite qualifier list of the composite type of
4200/// the conditional expression involving two objective-c pointer objects.
4201static
4202void getIntersectionOfProtocols(ASTContext &Context,
4203 const ObjCObjectPointerType *LHSOPT,
4204 const ObjCObjectPointerType *RHSOPT,
4205 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4206
4207 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4208 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4209
4210 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4211 unsigned LHSNumProtocols = LHS->getNumProtocols();
4212 if (LHSNumProtocols > 0)
4213 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4214 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004215 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4216 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004217 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4218 LHSInheritedProtocols.end());
4219 }
4220
4221 unsigned RHSNumProtocols = RHS->getNumProtocols();
4222 if (RHSNumProtocols > 0) {
4223 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4224 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4225 if (InheritedProtocolSet.count(RHSProtocols[i]))
4226 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4227 }
4228 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004229 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004230 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004231 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4232 RHSInheritedProtocols.begin(),
4233 E = RHSInheritedProtocols.end(); I != E; ++I)
4234 if (InheritedProtocolSet.count((*I)))
4235 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004236 }
4237}
4238
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004239/// areCommonBaseCompatible - Returns common base class of the two classes if
4240/// one found. Note that this is O'2 algorithm. But it will be called as the
4241/// last type comparison in a ?-exp of ObjC pointer types before a
4242/// warning is issued. So, its invokation is extremely rare.
4243QualType ASTContext::areCommonBaseCompatible(
4244 const ObjCObjectPointerType *LHSOPT,
4245 const ObjCObjectPointerType *RHSOPT) {
4246 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4247 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4248 if (!LHS || !RHS)
4249 return QualType();
4250
4251 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4252 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4253 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004254 if (canAssignObjCInterfaces(LHS, RHS)) {
4255 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4256 getIntersectionOfProtocols(*this,
4257 LHSOPT, RHSOPT, IntersectionOfProtocols);
4258 if (IntersectionOfProtocols.empty())
4259 LHSTy = getObjCObjectPointerType(LHSTy);
4260 else
4261 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4262 IntersectionOfProtocols.size());
4263 return LHSTy;
4264 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004265 }
4266
4267 return QualType();
4268}
4269
Eli Friedman47f77112008-08-22 00:56:42 +00004270bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4271 const ObjCInterfaceType *RHS) {
Chris Lattner49af6a42008-04-07 06:51:04 +00004272 // Verify that the base decls are compatible: the RHS must be a subclass of
4273 // the LHS.
4274 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4275 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004276
Chris Lattner49af6a42008-04-07 06:51:04 +00004277 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4278 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004279 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004280 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004281
Chris Lattner49af6a42008-04-07 06:51:04 +00004282 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4283 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004284 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004285 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004286
Steve Naroffc277ad12009-07-18 15:33:26 +00004287 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4288 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004289 LHSPI != LHSPE; LHSPI++) {
4290 bool RHSImplementsProtocol = false;
4291
4292 // If the RHS doesn't implement the protocol on the left, the types
4293 // are incompatible.
Steve Naroffc277ad12009-07-18 15:33:26 +00004294 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004295 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004296 RHSPI != RHSPE; RHSPI++) {
4297 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004298 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004299 break;
4300 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004301 }
4302 // FIXME: For better diagnostics, consider passing back the protocol name.
4303 if (!RHSImplementsProtocol)
4304 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004305 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004306 // The RHS implements all protocols listed on the LHS.
4307 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004308}
4309
Steve Naroffb7605152009-02-12 17:52:19 +00004310bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4311 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004312 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4313 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004314
Steve Naroff7cae42b2009-07-10 23:34:53 +00004315 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004316 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004317
4318 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4319 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004320}
4321
Mike Stump11289f42009-09-09 15:08:12 +00004322/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004323/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004324/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004325/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004326bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004327 if (getLangOptions().CPlusPlus)
4328 return hasSameType(LHS, RHS);
4329
Eli Friedman47f77112008-08-22 00:56:42 +00004330 return !mergeTypes(LHS, RHS).isNull();
4331}
4332
4333QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall9dd450b2009-09-21 23:43:11 +00004334 const FunctionType *lbase = lhs->getAs<FunctionType>();
4335 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004336 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4337 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004338 bool allLTypes = true;
4339 bool allRTypes = true;
4340
4341 // Check return type
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004342 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004343 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004344 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004345 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004346 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004347 allRTypes = false;
Mike Stumpea086c72009-07-25 23:24:03 +00004348 // FIXME: double check this
Mike Stump8c5d7992009-07-25 21:26:53 +00004349 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4350 if (NoReturn != lbase->getNoReturnAttr())
4351 allLTypes = false;
4352 if (NoReturn != rbase->getNoReturnAttr())
4353 allRTypes = false;
Douglas Gregor8c940862010-01-18 17:14:39 +00004354 CallingConv lcc = lbase->getCallConv();
4355 CallingConv rcc = rbase->getCallConv();
4356 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004357 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004358 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004359
Eli Friedman47f77112008-08-22 00:56:42 +00004360 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004361 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4362 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004363 unsigned lproto_nargs = lproto->getNumArgs();
4364 unsigned rproto_nargs = rproto->getNumArgs();
4365
4366 // Compatible functions must have the same number of arguments
4367 if (lproto_nargs != rproto_nargs)
4368 return QualType();
4369
4370 // Variadic and non-variadic functions aren't compatible
4371 if (lproto->isVariadic() != rproto->isVariadic())
4372 return QualType();
4373
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004374 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4375 return QualType();
4376
Eli Friedman47f77112008-08-22 00:56:42 +00004377 // Check argument compatibility
4378 llvm::SmallVector<QualType, 10> types;
4379 for (unsigned i = 0; i < lproto_nargs; i++) {
4380 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4381 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4382 QualType argtype = mergeTypes(largtype, rargtype);
4383 if (argtype.isNull()) return QualType();
4384 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004385 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4386 allLTypes = false;
4387 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4388 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004389 }
4390 if (allLTypes) return lhs;
4391 if (allRTypes) return rhs;
4392 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004393 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor8870a492010-02-12 17:17:28 +00004394 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004395 }
4396
4397 if (lproto) allRTypes = false;
4398 if (rproto) allLTypes = false;
4399
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004400 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004401 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004402 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004403 if (proto->isVariadic()) return QualType();
4404 // Check that the types are compatible with the types that
4405 // would result from default argument promotions (C99 6.7.5.3p15).
4406 // The only types actually affected are promotable integer
4407 // types and floats, which would be passed as a different
4408 // type depending on whether the prototype is visible.
4409 unsigned proto_nargs = proto->getNumArgs();
4410 for (unsigned i = 0; i < proto_nargs; ++i) {
4411 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004412
4413 // Look at the promotion type of enum types, since that is the type used
4414 // to pass enum values.
4415 if (const EnumType *Enum = argTy->getAs<EnumType>())
4416 argTy = Enum->getDecl()->getPromotionType();
4417
Eli Friedman47f77112008-08-22 00:56:42 +00004418 if (argTy->isPromotableIntegerType() ||
4419 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4420 return QualType();
4421 }
4422
4423 if (allLTypes) return lhs;
4424 if (allRTypes) return rhs;
4425 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004426 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004427 proto->getTypeQuals(),
4428 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004429 }
4430
4431 if (allLTypes) return lhs;
4432 if (allRTypes) return rhs;
Douglas Gregor8c940862010-01-18 17:14:39 +00004433 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004434}
4435
4436QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004437 // C++ [expr]: If an expression initially has the type "reference to T", the
4438 // type is adjusted to "T" prior to any further analysis, the expression
4439 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004440 // expression is an lvalue unless the reference is an rvalue reference and
4441 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004442 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4443 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4444
Eli Friedman47f77112008-08-22 00:56:42 +00004445 QualType LHSCan = getCanonicalType(LHS),
4446 RHSCan = getCanonicalType(RHS);
4447
4448 // If two types are identical, they are compatible.
4449 if (LHSCan == RHSCan)
4450 return LHS;
4451
John McCall8ccfcb52009-09-24 19:53:00 +00004452 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004453 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4454 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004455 if (LQuals != RQuals) {
4456 // If any of these qualifiers are different, we have a type
4457 // mismatch.
4458 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4459 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4460 return QualType();
4461
4462 // Exactly one GC qualifier difference is allowed: __strong is
4463 // okay if the other type has no GC qualifier but is an Objective
4464 // C object pointer (i.e. implicitly strong by default). We fix
4465 // this by pretending that the unqualified type was actually
4466 // qualified __strong.
4467 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4468 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4469 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4470
4471 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4472 return QualType();
4473
4474 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4475 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4476 }
4477 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4478 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4479 }
Eli Friedman47f77112008-08-22 00:56:42 +00004480 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004481 }
4482
4483 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004484
Eli Friedmandcca6332009-06-01 01:22:52 +00004485 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4486 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004487
Chris Lattnerfd652912008-01-14 05:45:46 +00004488 // We want to consider the two function types to be the same for these
4489 // comparisons, just force one to the other.
4490 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4491 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004492
4493 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004494 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4495 LHSClass = Type::ConstantArray;
4496 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4497 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004498
Nate Begemance4d7fc2008-04-18 23:10:10 +00004499 // Canonicalize ExtVector -> Vector.
4500 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4501 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004502
Chris Lattner95554662008-04-07 05:43:21 +00004503 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004504 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004505 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004506 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004507 // Compatibility is based on the underlying type, not the promotion
4508 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004509 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004510 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4511 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004512 }
John McCall9dd450b2009-09-21 23:43:11 +00004513 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004514 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4515 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004516 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004517
Eli Friedman47f77112008-08-22 00:56:42 +00004518 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004519 }
Eli Friedman47f77112008-08-22 00:56:42 +00004520
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004521 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004522 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004523#define TYPE(Class, Base)
4524#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004525#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004526#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4527#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4528#include "clang/AST/TypeNodes.def"
4529 assert(false && "Non-canonical and dependent types shouldn't get here");
4530 return QualType();
4531
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004532 case Type::LValueReference:
4533 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004534 case Type::MemberPointer:
4535 assert(false && "C++ should never be in mergeTypes");
4536 return QualType();
4537
4538 case Type::IncompleteArray:
4539 case Type::VariableArray:
4540 case Type::FunctionProto:
4541 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004542 assert(false && "Types are eliminated above");
4543 return QualType();
4544
Chris Lattnerfd652912008-01-14 05:45:46 +00004545 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004546 {
4547 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004548 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4549 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004550 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4551 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004552 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004553 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004554 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004555 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004556 return getPointerType(ResultType);
4557 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004558 case Type::BlockPointer:
4559 {
4560 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004561 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4562 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroff68e167d2008-12-10 17:49:55 +00004563 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4564 if (ResultType.isNull()) return QualType();
4565 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4566 return LHS;
4567 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4568 return RHS;
4569 return getBlockPointerType(ResultType);
4570 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004571 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004572 {
4573 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4574 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4575 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4576 return QualType();
4577
4578 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4579 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4580 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4581 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004582 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4583 return LHS;
4584 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4585 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004586 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4587 ArrayType::ArraySizeModifier(), 0);
4588 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4589 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004590 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4591 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004592 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4593 return LHS;
4594 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4595 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004596 if (LVAT) {
4597 // FIXME: This isn't correct! But tricky to implement because
4598 // the array's size has to be the size of LHS, but the type
4599 // has to be different.
4600 return LHS;
4601 }
4602 if (RVAT) {
4603 // FIXME: This isn't correct! But tricky to implement because
4604 // the array's size has to be the size of RHS, but the type
4605 // has to be different.
4606 return RHS;
4607 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004608 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4609 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004610 return getIncompleteArrayType(ResultType,
4611 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004612 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004613 case Type::FunctionNoProto:
Eli Friedman47f77112008-08-22 00:56:42 +00004614 return mergeFunctionTypes(LHS, RHS);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004615 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004616 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004617 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004618 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004619 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004620 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004621 case Type::Complex:
4622 // Distinct complex types are incompatible.
4623 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004624 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004625 // FIXME: The merged type should be an ExtVector!
John McCall9dd450b2009-09-21 23:43:11 +00004626 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004627 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004628 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004629 case Type::ObjCInterface: {
Steve Naroff7a7814c2009-02-21 16:18:07 +00004630 // Check if the interfaces are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004631 // FIXME: This should be type compatibility, e.g. whether
4632 // "LHS x; RHS x;" at global scope is legal.
John McCall9dd450b2009-09-21 23:43:11 +00004633 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4634 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff7a7814c2009-02-21 16:18:07 +00004635 if (LHSIface && RHSIface &&
4636 canAssignObjCInterfaces(LHSIface, RHSIface))
4637 return LHS;
4638
Eli Friedman47f77112008-08-22 00:56:42 +00004639 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004640 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004641 case Type::ObjCObjectPointer: {
John McCall9dd450b2009-09-21 23:43:11 +00004642 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4643 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004644 return LHS;
4645
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004646 return QualType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004647 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004648 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004649
4650 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004651}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004652
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004653//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004654// Integer Predicates
4655//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004656
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004657unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004658 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004659 return 1;
John McCall56774992009-12-09 09:09:27 +00004660 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004661 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004662 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004663 return (unsigned)getTypeSize(T);
4664}
4665
4666QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4667 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004668
4669 // Turn <4 x signed int> -> <4 x unsigned int>
4670 if (const VectorType *VTy = T->getAs<VectorType>())
4671 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004672 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004673
4674 // For enums, we return the unsigned version of the base type.
4675 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004676 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004677
4678 const BuiltinType *BTy = T->getAs<BuiltinType>();
4679 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004680 switch (BTy->getKind()) {
4681 case BuiltinType::Char_S:
4682 case BuiltinType::SChar:
4683 return UnsignedCharTy;
4684 case BuiltinType::Short:
4685 return UnsignedShortTy;
4686 case BuiltinType::Int:
4687 return UnsignedIntTy;
4688 case BuiltinType::Long:
4689 return UnsignedLongTy;
4690 case BuiltinType::LongLong:
4691 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004692 case BuiltinType::Int128:
4693 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004694 default:
4695 assert(0 && "Unexpected signed integer type");
4696 return QualType();
4697 }
4698}
4699
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004700ExternalASTSource::~ExternalASTSource() { }
4701
4702void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004703
4704
4705//===----------------------------------------------------------------------===//
4706// Builtin Type Computation
4707//===----------------------------------------------------------------------===//
4708
4709/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4710/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004711static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004712 ASTContext::GetBuiltinTypeError &Error,
4713 bool AllowTypeModifiers = true) {
4714 // Modifiers.
4715 int HowLong = 0;
4716 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004717
Chris Lattnerecd79c62009-06-14 00:45:47 +00004718 // Read the modifiers first.
4719 bool Done = false;
4720 while (!Done) {
4721 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004722 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004723 case 'S':
4724 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4725 assert(!Signed && "Can't use 'S' modifier multiple times!");
4726 Signed = true;
4727 break;
4728 case 'U':
4729 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4730 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4731 Unsigned = true;
4732 break;
4733 case 'L':
4734 assert(HowLong <= 2 && "Can't have LLLL modifier");
4735 ++HowLong;
4736 break;
4737 }
4738 }
4739
4740 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004741
Chris Lattnerecd79c62009-06-14 00:45:47 +00004742 // Read the base type.
4743 switch (*Str++) {
4744 default: assert(0 && "Unknown builtin type letter!");
4745 case 'v':
4746 assert(HowLong == 0 && !Signed && !Unsigned &&
4747 "Bad modifiers used with 'v'!");
4748 Type = Context.VoidTy;
4749 break;
4750 case 'f':
4751 assert(HowLong == 0 && !Signed && !Unsigned &&
4752 "Bad modifiers used with 'f'!");
4753 Type = Context.FloatTy;
4754 break;
4755 case 'd':
4756 assert(HowLong < 2 && !Signed && !Unsigned &&
4757 "Bad modifiers used with 'd'!");
4758 if (HowLong)
4759 Type = Context.LongDoubleTy;
4760 else
4761 Type = Context.DoubleTy;
4762 break;
4763 case 's':
4764 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4765 if (Unsigned)
4766 Type = Context.UnsignedShortTy;
4767 else
4768 Type = Context.ShortTy;
4769 break;
4770 case 'i':
4771 if (HowLong == 3)
4772 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4773 else if (HowLong == 2)
4774 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4775 else if (HowLong == 1)
4776 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4777 else
4778 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4779 break;
4780 case 'c':
4781 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4782 if (Signed)
4783 Type = Context.SignedCharTy;
4784 else if (Unsigned)
4785 Type = Context.UnsignedCharTy;
4786 else
4787 Type = Context.CharTy;
4788 break;
4789 case 'b': // boolean
4790 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4791 Type = Context.BoolTy;
4792 break;
4793 case 'z': // size_t.
4794 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4795 Type = Context.getSizeType();
4796 break;
4797 case 'F':
4798 Type = Context.getCFConstantStringType();
4799 break;
4800 case 'a':
4801 Type = Context.getBuiltinVaListType();
4802 assert(!Type.isNull() && "builtin va list type not initialized!");
4803 break;
4804 case 'A':
4805 // This is a "reference" to a va_list; however, what exactly
4806 // this means depends on how va_list is defined. There are two
4807 // different kinds of va_list: ones passed by value, and ones
4808 // passed by reference. An example of a by-value va_list is
4809 // x86, where va_list is a char*. An example of by-ref va_list
4810 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4811 // we want this argument to be a char*&; for x86-64, we want
4812 // it to be a __va_list_tag*.
4813 Type = Context.getBuiltinVaListType();
4814 assert(!Type.isNull() && "builtin va list type not initialized!");
4815 if (Type->isArrayType()) {
4816 Type = Context.getArrayDecayedType(Type);
4817 } else {
4818 Type = Context.getLValueReferenceType(Type);
4819 }
4820 break;
4821 case 'V': {
4822 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004823 unsigned NumElements = strtoul(Str, &End, 10);
4824 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004825
Chris Lattnerecd79c62009-06-14 00:45:47 +00004826 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004827
Chris Lattnerecd79c62009-06-14 00:45:47 +00004828 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004829 // FIXME: Don't know what to do about AltiVec.
4830 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004831 break;
4832 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004833 case 'X': {
4834 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4835 Type = Context.getComplexType(ElementType);
4836 break;
4837 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004838 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004839 Type = Context.getFILEType();
4840 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004841 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004842 return QualType();
4843 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004844 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004845 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004846 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004847 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004848 else
4849 Type = Context.getjmp_bufType();
4850
Mike Stump2adb4da2009-07-28 23:47:15 +00004851 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004852 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004853 return QualType();
4854 }
4855 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004856 }
Mike Stump11289f42009-09-09 15:08:12 +00004857
Chris Lattnerecd79c62009-06-14 00:45:47 +00004858 if (!AllowTypeModifiers)
4859 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Chris Lattnerecd79c62009-06-14 00:45:47 +00004861 Done = false;
4862 while (!Done) {
4863 switch (*Str++) {
4864 default: Done = true; --Str; break;
4865 case '*':
4866 Type = Context.getPointerType(Type);
4867 break;
4868 case '&':
4869 Type = Context.getLValueReferenceType(Type);
4870 break;
4871 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4872 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00004873 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00004874 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00004875 case 'D':
4876 Type = Context.getVolatileType(Type);
4877 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004878 }
4879 }
Mike Stump11289f42009-09-09 15:08:12 +00004880
Chris Lattnerecd79c62009-06-14 00:45:47 +00004881 return Type;
4882}
4883
4884/// GetBuiltinType - Return the type for the specified builtin.
4885QualType ASTContext::GetBuiltinType(unsigned id,
4886 GetBuiltinTypeError &Error) {
4887 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00004888
Chris Lattnerecd79c62009-06-14 00:45:47 +00004889 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004890
Chris Lattnerecd79c62009-06-14 00:45:47 +00004891 Error = GE_None;
4892 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4893 if (Error != GE_None)
4894 return QualType();
4895 while (TypeStr[0] && TypeStr[0] != '.') {
4896 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4897 if (Error != GE_None)
4898 return QualType();
4899
4900 // Do array -> pointer decay. The builtin should use the decayed type.
4901 if (Ty->isArrayType())
4902 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004903
Chris Lattnerecd79c62009-06-14 00:45:47 +00004904 ArgTypes.push_back(Ty);
4905 }
4906
4907 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4908 "'.' should only occur at end of builtin type list!");
4909
4910 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4911 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4912 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00004913
4914 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00004915 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004916 TypeStr[0] == '.', 0, false, false, 0, 0,
4917 false, CC_Default);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004918}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004919
4920QualType
4921ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4922 // Perform the usual unary conversions. We do this early so that
4923 // integral promotions to "int" can allow us to exit early, in the
4924 // lhs == rhs check. Also, for conversion purposes, we ignore any
4925 // qualifiers. For example, "const float" and "float" are
4926 // equivalent.
4927 if (lhs->isPromotableIntegerType())
4928 lhs = getPromotedIntegerType(lhs);
4929 else
4930 lhs = lhs.getUnqualifiedType();
4931 if (rhs->isPromotableIntegerType())
4932 rhs = getPromotedIntegerType(rhs);
4933 else
4934 rhs = rhs.getUnqualifiedType();
4935
4936 // If both types are identical, no conversion is needed.
4937 if (lhs == rhs)
4938 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00004939
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004940 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4941 // The caller can deal with this (e.g. pointer + int).
4942 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4943 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00004944
4945 // At this point, we have two different arithmetic types.
4946
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004947 // Handle complex types first (C99 6.3.1.8p1).
4948 if (lhs->isComplexType() || rhs->isComplexType()) {
4949 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00004950 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004951 // convert the rhs to the lhs complex type.
4952 return lhs;
4953 }
Mike Stump11289f42009-09-09 15:08:12 +00004954 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004955 // convert the lhs to the rhs complex type.
4956 return rhs;
4957 }
4958 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00004959 // When both operands are complex, the shorter operand is converted to the
4960 // type of the longer, and that is the type of the result. This corresponds
4961 // to what is done when combining two real floating-point operands.
4962 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004963 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00004964 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004965 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00004966 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004967 // "double _Complex" is promoted to "long double _Complex".
4968 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00004969
4970 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004971 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00004972 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004973 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00004974 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004975 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4976 // domains match. This is a requirement for our implementation, C99
4977 // does not require this promotion.
4978 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4979 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4980 return rhs;
4981 } else { // handle "_Complex double, double".
4982 return lhs;
4983 }
4984 }
4985 return lhs; // The domain/size match exactly.
4986 }
4987 // Now handle "real" floating types (i.e. float, double, long double).
4988 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4989 // if we have an integer operand, the result is the real floating type.
4990 if (rhs->isIntegerType()) {
4991 // convert rhs to the lhs floating point type.
4992 return lhs;
4993 }
4994 if (rhs->isComplexIntegerType()) {
4995 // convert rhs to the complex floating point type.
4996 return getComplexType(lhs);
4997 }
4998 if (lhs->isIntegerType()) {
4999 // convert lhs to the rhs floating point type.
5000 return rhs;
5001 }
Mike Stump11289f42009-09-09 15:08:12 +00005002 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005003 // convert lhs to the complex floating point type.
5004 return getComplexType(rhs);
5005 }
5006 // We have two real floating types, float/complex combos were handled above.
5007 // Convert the smaller operand to the bigger result.
5008 int result = getFloatingTypeOrder(lhs, rhs);
5009 if (result > 0) // convert the rhs
5010 return lhs;
5011 assert(result < 0 && "illegal float comparison");
5012 return rhs; // convert the lhs
5013 }
5014 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5015 // Handle GCC complex int extension.
5016 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5017 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5018
5019 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005020 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005021 rhsComplexInt->getElementType()) >= 0)
5022 return lhs; // convert the rhs
5023 return rhs;
5024 } else if (lhsComplexInt && rhs->isIntegerType()) {
5025 // convert the rhs to the lhs complex type.
5026 return lhs;
5027 } else if (rhsComplexInt && lhs->isIntegerType()) {
5028 // convert the lhs to the rhs complex type.
5029 return rhs;
5030 }
5031 }
5032 // Finally, we have two differing integer types.
5033 // The rules for this case are in C99 6.3.1.8
5034 int compare = getIntegerTypeOrder(lhs, rhs);
5035 bool lhsSigned = lhs->isSignedIntegerType(),
5036 rhsSigned = rhs->isSignedIntegerType();
5037 QualType destType;
5038 if (lhsSigned == rhsSigned) {
5039 // Same signedness; use the higher-ranked type
5040 destType = compare >= 0 ? lhs : rhs;
5041 } else if (compare != (lhsSigned ? 1 : -1)) {
5042 // The unsigned type has greater than or equal rank to the
5043 // signed type, so use the unsigned type
5044 destType = lhsSigned ? rhs : lhs;
5045 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5046 // The two types are different widths; if we are here, that
5047 // means the signed type is larger than the unsigned type, so
5048 // use the signed type.
5049 destType = lhsSigned ? lhs : rhs;
5050 } else {
5051 // The signed type is higher-ranked than the unsigned type,
5052 // but isn't actually any bigger (like unsigned int and long
5053 // on most 32-bit systems). Use the unsigned type corresponding
5054 // to the signed type.
5055 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5056 }
5057 return destType;
5058}