blob: 23478e4f3c9e9d3f0e31cf17831782d5bfbf66b6 [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),
Fariborz Jahaniane804c282010-04-23 17:41:07 +000044 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000045 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000046 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Douglas Gregor9507d462010-03-19 22:13:20 +000047 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +000049 BuiltinInfo(builtins),
50 DeclarationNames(*this),
51 ExternalSource(0), PrintingPolicy(LOpts),
John McCallc62bb642010-03-24 05:22:00 +000052 LastSDM(0, 0) {
David Chisnall9f57c292009-08-17 16:35:33 +000053 ObjCIdRedefinitionType = QualType();
54 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000055 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000056 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000057 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000058 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000059}
60
Chris Lattnerd5973eb2006-11-12 00:53:46 +000061ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000062 // Release the DenseMaps associated with DeclContext objects.
63 // FIXME: Is this the ideal solution?
64 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +000065
66 // Release all of the memory associated with overridden C++ methods.
67 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
68 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
69 OM != OMEnd; ++OM)
70 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +000071
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000072 if (FreeMemory) {
73 // Deallocate all the types.
74 while (!Types.empty()) {
75 Types.back()->Destroy(*this);
76 Types.pop_back();
77 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000078
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000079 for (llvm::FoldingSet<ExtQuals>::iterator
80 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
81 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000082 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000083 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000084
Ted Kremenekc3015a92010-03-08 20:56:29 +000085 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
86 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
87 // Increment in loop to prevent using deallocated memory.
88 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
89 R->Destroy(*this);
90 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000091
Ted Kremenekc3015a92010-03-08 20:56:29 +000092 for (llvm::DenseMap<const ObjCContainerDecl*,
93 const ASTRecordLayout*>::iterator
94 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
95 // Increment in loop to prevent using deallocated memory.
96 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
97 R->Destroy(*this);
98 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000099 }
100
Douglas Gregorf21eb492009-03-26 23:50:42 +0000101 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000102 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
103 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000104 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000105 NNS != NNSEnd; ) {
106 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000107 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000108 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000109
110 if (GlobalNestedNameSpecifier)
111 GlobalNestedNameSpecifier->Destroy(*this);
112
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000113 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000114}
115
Mike Stump11289f42009-09-09 15:08:12 +0000116void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000117ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
118 ExternalSource.reset(Source.take());
119}
120
Chris Lattner4eb445d2007-01-26 01:27:23 +0000121void ASTContext::PrintStats() const {
122 fprintf(stderr, "*** AST Context Stats:\n");
123 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000124
Douglas Gregora30d0462009-05-26 14:40:08 +0000125 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000126#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000127#define ABSTRACT_TYPE(Name, Parent)
128#include "clang/AST/TypeNodes.def"
129 0 // Extra
130 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000131
Chris Lattner4eb445d2007-01-26 01:27:23 +0000132 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
133 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000134 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000135 }
136
Douglas Gregora30d0462009-05-26 14:40:08 +0000137 unsigned Idx = 0;
138 unsigned TotalBytes = 0;
139#define TYPE(Name, Parent) \
140 if (counts[Idx]) \
141 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
142 TotalBytes += counts[Idx] * sizeof(Name##Type); \
143 ++Idx;
144#define ABSTRACT_TYPE(Name, Parent)
145#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000146
Douglas Gregora30d0462009-05-26 14:40:08 +0000147 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000148
149 if (ExternalSource.get()) {
150 fprintf(stderr, "\n");
151 ExternalSource->PrintStats();
152 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000153}
154
155
John McCall48f2d582009-10-23 23:03:21 +0000156void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000157 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000158 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000159 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000160}
161
Chris Lattner970e54e2006-11-12 00:37:36 +0000162void ASTContext::InitBuiltinTypes() {
163 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattner970e54e2006-11-12 00:37:36 +0000165 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000166 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner970e54e2006-11-12 00:37:36 +0000168 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000169 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000170 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000171 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000172 InitBuiltinType(CharTy, BuiltinType::Char_S);
173 else
174 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000175 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000176 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
177 InitBuiltinType(ShortTy, BuiltinType::Short);
178 InitBuiltinType(IntTy, BuiltinType::Int);
179 InitBuiltinType(LongTy, BuiltinType::Long);
180 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner970e54e2006-11-12 00:37:36 +0000182 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000183 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
184 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
185 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
186 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
187 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner970e54e2006-11-12 00:37:36 +0000189 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000190 InitBuiltinType(FloatTy, BuiltinType::Float);
191 InitBuiltinType(DoubleTy, BuiltinType::Double);
192 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000193
Chris Lattnerf122cef2009-04-30 02:43:43 +0000194 // GNU extension, 128-bit integers.
195 InitBuiltinType(Int128Ty, BuiltinType::Int128);
196 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
197
Chris Lattner007cb022009-02-26 23:43:47 +0000198 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
199 InitBuiltinType(WCharTy, BuiltinType::WChar);
200 else // C99
201 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000202
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000203 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
204 InitBuiltinType(Char16Ty, BuiltinType::Char16);
205 else // C99
206 Char16Ty = getFromTargetType(Target.getChar16Type());
207
208 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
209 InitBuiltinType(Char32Ty, BuiltinType::Char32);
210 else // C99
211 Char32Ty = getFromTargetType(Target.getChar32Type());
212
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000214 InitBuiltinType(OverloadTy, BuiltinType::Overload);
215
216 // Placeholder type for type-dependent expressions whose type is
217 // completely unknown. No code should ever check a type against
218 // DependentTy and users should never see it; however, it is here to
219 // help diagnose failures to properly check for type-dependent
220 // expressions.
221 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222
Mike Stump11289f42009-09-09 15:08:12 +0000223 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000224 // not yet been deduced.
225 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner970e54e2006-11-12 00:37:36 +0000227 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000228 FloatComplexTy = getComplexType(FloatTy);
229 DoubleComplexTy = getComplexType(DoubleTy);
230 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000231
Steve Naroff66e9f332007-10-15 14:41:52 +0000232 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000233
Steve Naroff1329fa02009-07-15 18:40:39 +0000234 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
235 ObjCIdTypedefType = QualType();
236 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000237 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000238
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000239 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000240 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
241 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000242 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000243
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000244 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000245
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000246 // void * type
247 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000248
249 // nullptr type (C++0x 2.14.7)
250 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000251}
252
Douglas Gregor86d142a2009-10-08 07:24:58 +0000253MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000254ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000255 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000256 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000257 = InstantiatedFromStaticDataMember.find(Var);
258 if (Pos == InstantiatedFromStaticDataMember.end())
259 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000261 return Pos->second;
262}
263
Mike Stump11289f42009-09-09 15:08:12 +0000264void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000265ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
266 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000267 assert(Inst->isStaticDataMember() && "Not a static data member");
268 assert(Tmpl->isStaticDataMember() && "Not a static data member");
269 assert(!InstantiatedFromStaticDataMember[Inst] &&
270 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000271 InstantiatedFromStaticDataMember[Inst]
272 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000273}
274
John McCalle61f2ba2009-11-18 02:36:19 +0000275NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000276ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000277 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000278 = InstantiatedFromUsingDecl.find(UUD);
279 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000280 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000281
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000282 return Pos->second;
283}
284
285void
John McCallb96ec562009-12-04 22:46:56 +0000286ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
287 assert((isa<UsingDecl>(Pattern) ||
288 isa<UnresolvedUsingValueDecl>(Pattern) ||
289 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
290 "pattern decl is not a using decl");
291 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
292 InstantiatedFromUsingDecl[Inst] = Pattern;
293}
294
295UsingShadowDecl *
296ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
297 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
298 = InstantiatedFromUsingShadowDecl.find(Inst);
299 if (Pos == InstantiatedFromUsingShadowDecl.end())
300 return 0;
301
302 return Pos->second;
303}
304
305void
306ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
307 UsingShadowDecl *Pattern) {
308 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
309 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000310}
311
Anders Carlsson5da84842009-09-01 04:26:58 +0000312FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
313 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
314 = InstantiatedFromUnnamedFieldDecl.find(Field);
315 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
316 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson5da84842009-09-01 04:26:58 +0000318 return Pos->second;
319}
320
321void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
322 FieldDecl *Tmpl) {
323 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
324 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
325 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
326 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000327
Anders Carlsson5da84842009-09-01 04:26:58 +0000328 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
329}
330
Douglas Gregor832940b2010-03-02 23:58:15 +0000331ASTContext::overridden_cxx_method_iterator
332ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
334 = OverriddenMethods.find(Method);
335 if (Pos == OverriddenMethods.end())
336 return 0;
337
338 return Pos->second.begin();
339}
340
341ASTContext::overridden_cxx_method_iterator
342ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
343 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
344 = OverriddenMethods.find(Method);
345 if (Pos == OverriddenMethods.end())
346 return 0;
347
348 return Pos->second.end();
349}
350
351void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
352 const CXXMethodDecl *Overridden) {
353 OverriddenMethods[Method].push_back(Overridden);
354}
355
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000356namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000357 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000358 : std::binary_function<SourceRange, SourceRange, bool> {
359 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000361 public:
362 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000363
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000364 bool operator()(SourceRange X, SourceRange Y) {
365 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
366 }
367 };
368}
369
Chris Lattner53cfe802007-07-18 17:52:12 +0000370//===----------------------------------------------------------------------===//
371// Type Sizing and Analysis
372//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000373
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000374/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
375/// scalar floating point type.
376const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000377 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000378 assert(BT && "Not a floating point type!");
379 switch (BT->getKind()) {
380 default: assert(0 && "Not a floating point type!");
381 case BuiltinType::Float: return Target.getFloatFormat();
382 case BuiltinType::Double: return Target.getDoubleFormat();
383 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
384 }
385}
386
Ken Dyck160146e2010-01-27 17:10:57 +0000387/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000388/// specified decl. Note that bitfields do not have a valid alignment, so
389/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000390/// If @p RefAsPointee, references are treated like their underlying type
391/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000392CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000393 unsigned Align = Target.getCharWidth();
394
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000395 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000396 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000397
Chris Lattner68061312009-01-24 21:53:27 +0000398 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
399 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000400 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000401 if (RefAsPointee)
402 T = RT->getPointeeType();
403 else
404 T = getPointerType(RT->getPointeeType());
405 }
406 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000407 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000408 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
409 T = cast<ArrayType>(T)->getElementType();
410
411 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
412 }
Charles Davis3fc51072010-02-23 04:52:00 +0000413 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
414 // In the case of a field in a packed struct, we want the minimum
415 // of the alignment of the field and the alignment of the struct.
416 Align = std::min(Align,
417 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
418 }
Chris Lattner68061312009-01-24 21:53:27 +0000419 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000420
Ken Dyck160146e2010-01-27 17:10:57 +0000421 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000422}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000423
Chris Lattner983a8bb2007-07-13 22:13:22 +0000424/// getTypeSize - Return the size of the specified type, in bits. This method
425/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000426///
427/// FIXME: Pointers into different addr spaces could have different sizes and
428/// alignment requirements: getPointerInfo should take an AddrSpace, this
429/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000430std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000431ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000432 uint64_t Width=0;
433 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000434 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000435#define TYPE(Class, Base)
436#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000437#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000438#define DEPENDENT_TYPE(Class, Base) case Type::Class:
439#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000440 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000441 break;
442
Chris Lattner355332d2007-07-13 22:27:08 +0000443 case Type::FunctionNoProto:
444 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000445 // GCC extension: alignof(function) = 32 bits
446 Width = 0;
447 Align = 32;
448 break;
449
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000450 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000451 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000452 Width = 0;
453 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
454 break;
455
Steve Naroff5c131802007-08-30 01:06:46 +0000456 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000457 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000458
Chris Lattner37e05872008-03-05 18:54:05 +0000459 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000460 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000461 Align = EltInfo.second;
462 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000463 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000464 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000465 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000466 const VectorType *VT = cast<VectorType>(T);
467 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
468 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000469 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000470 // If the alignment is not a power of 2, round up to the next power of 2.
471 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000472 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000473 Align = llvm::NextPowerOf2(Align);
474 Width = llvm::RoundUpToAlignment(Width, Align);
475 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000476 break;
477 }
Chris Lattner647fb222007-07-18 18:26:58 +0000478
Chris Lattner7570e9c2008-03-08 08:52:55 +0000479 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000480 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000481 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000482 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000483 // GCC extension: alignof(void) = 8 bits.
484 Width = 0;
485 Align = 8;
486 break;
487
Chris Lattner6a4f7452007-12-19 19:23:28 +0000488 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000489 Width = Target.getBoolWidth();
490 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000491 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000492 case BuiltinType::Char_S:
493 case BuiltinType::Char_U:
494 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000495 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000496 Width = Target.getCharWidth();
497 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000498 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000499 case BuiltinType::WChar:
500 Width = Target.getWCharWidth();
501 Align = Target.getWCharAlign();
502 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000503 case BuiltinType::Char16:
504 Width = Target.getChar16Width();
505 Align = Target.getChar16Align();
506 break;
507 case BuiltinType::Char32:
508 Width = Target.getChar32Width();
509 Align = Target.getChar32Align();
510 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000511 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000512 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000513 Width = Target.getShortWidth();
514 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000515 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000516 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000517 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000518 Width = Target.getIntWidth();
519 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000520 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000521 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000522 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000523 Width = Target.getLongWidth();
524 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000525 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000526 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000527 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000528 Width = Target.getLongLongWidth();
529 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000530 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000531 case BuiltinType::Int128:
532 case BuiltinType::UInt128:
533 Width = 128;
534 Align = 128; // int128_t is 128-bit aligned on all targets.
535 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000536 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000537 Width = Target.getFloatWidth();
538 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000539 break;
540 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000541 Width = Target.getDoubleWidth();
542 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000543 break;
544 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000545 Width = Target.getLongDoubleWidth();
546 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000547 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000548 case BuiltinType::NullPtr:
549 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
550 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000551 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000552 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000553 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000554 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000555 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000556 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000557 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000558 case Type::BlockPointer: {
559 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
560 Width = Target.getPointerWidth(AS);
561 Align = Target.getPointerAlign(AS);
562 break;
563 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000564 case Type::LValueReference:
565 case Type::RValueReference: {
566 // alignof and sizeof should never enter this code path here, so we go
567 // the pointer route.
568 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
569 Width = Target.getPointerWidth(AS);
570 Align = Target.getPointerAlign(AS);
571 break;
572 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000573 case Type::Pointer: {
574 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000575 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000576 Align = Target.getPointerAlign(AS);
577 break;
578 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000579 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000580 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000581 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000582 getTypeInfo(getPointerDiffType());
583 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000584 if (Pointee->isFunctionType())
585 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000586 Align = PtrDiffInfo.second;
587 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000588 }
Chris Lattner647fb222007-07-18 18:26:58 +0000589 case Type::Complex: {
590 // Complex types have the same alignment as their elements, but twice the
591 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000592 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000593 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000594 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000595 Align = EltInfo.second;
596 break;
597 }
John McCall8b07ec22010-05-15 11:32:37 +0000598 case Type::ObjCObject:
599 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000600 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000601 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000602 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
603 Width = Layout.getSize();
604 Align = Layout.getAlignment();
605 break;
606 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000607 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000608 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000609 const TagType *TT = cast<TagType>(T);
610
611 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000612 Width = 1;
613 Align = 1;
614 break;
615 }
Mike Stump11289f42009-09-09 15:08:12 +0000616
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000617 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000618 return getTypeInfo(ET->getDecl()->getIntegerType());
619
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000620 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000621 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
622 Width = Layout.getSize();
623 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000624 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000625 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000626
Chris Lattner63d2b362009-10-22 05:17:15 +0000627 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000628 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
629 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000630
Douglas Gregoref462e62009-04-30 17:32:17 +0000631 case Type::Typedef: {
632 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000633 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000634 Align = std::max(Aligned->getMaxAlignment(),
635 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000636 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
637 } else
638 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000639 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000640 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000641
642 case Type::TypeOfExpr:
643 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
644 .getTypePtr());
645
646 case Type::TypeOf:
647 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
648
Anders Carlsson81df7b82009-06-24 19:06:50 +0000649 case Type::Decltype:
650 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
651 .getTypePtr());
652
Abramo Bagnara6150c882010-05-11 21:36:43 +0000653 case Type::Elaborated:
654 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000655
Douglas Gregoref462e62009-04-30 17:32:17 +0000656 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000657 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000658 "Cannot request the size of a dependent type");
659 // FIXME: this is likely to be wrong once we support template
660 // aliases, since a template alias could refer to a typedef that
661 // has an __aligned__ attribute on it.
662 return getTypeInfo(getCanonicalType(T));
663 }
Mike Stump11289f42009-09-09 15:08:12 +0000664
Chris Lattner53cfe802007-07-18 17:52:12 +0000665 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000666 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000667}
668
Ken Dyck8c89d592009-12-22 14:23:30 +0000669/// getTypeSizeInChars - Return the size of the specified type, in characters.
670/// This method does not work on incomplete types.
671CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000672 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000673}
674CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000675 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000676}
677
Ken Dycka6046ab2010-01-26 17:25:18 +0000678/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000679/// characters. This method does not work on incomplete types.
680CharUnits ASTContext::getTypeAlignInChars(QualType T) {
681 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
682}
683CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
684 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
685}
686
Chris Lattnera3402cd2009-01-27 18:08:34 +0000687/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
688/// type for the current target in bits. This can be different than the ABI
689/// alignment in cases where it is beneficial for performance to overalign
690/// a data type.
691unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
692 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000693
694 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000695 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000696 T = CT->getElementType().getTypePtr();
697 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
698 T->isSpecificBuiltinType(BuiltinType::LongLong))
699 return std::max(ABIAlign, (unsigned)getTypeSize(T));
700
Chris Lattnera3402cd2009-01-27 18:08:34 +0000701 return ABIAlign;
702}
703
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000704static void CollectLocalObjCIvars(ASTContext *Ctx,
705 const ObjCInterfaceDecl *OI,
706 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000707 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
708 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000709 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000710 if (!IVDecl->isInvalidDecl())
711 Fields.push_back(cast<FieldDecl>(IVDecl));
712 }
713}
714
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000715void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
716 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
717 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
718 CollectObjCIvars(SuperClass, Fields);
719 CollectLocalObjCIvars(this, OI, Fields);
720}
721
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000722/// ShallowCollectObjCIvars -
723/// Collect all ivars, including those synthesized, in the current class.
724///
725void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000726 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000727 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
728 E = OI->ivar_end(); I != E; ++I) {
729 Ivars.push_back(*I);
730 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000731
732 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000733}
734
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000735/// CollectNonClassIvars -
736/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000737/// This includes synthesized ivars (via @synthesize) and those in
738// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000739///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000740void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000741 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000742 // Find ivars declared in class extension.
743 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
744 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
745 E = CDecl->ivar_end(); I != E; ++I) {
746 Ivars.push_back(*I);
747 }
748 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000749
Ted Kremenek86838aa2010-03-11 19:44:54 +0000750 // Also add any ivar defined in this class's implementation. This
751 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000752 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
753 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
754 E = ImplDecl->ivar_end(); I != E; ++I)
755 Ivars.push_back(*I);
756 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000757}
758
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000759/// CollectInheritedProtocols - Collect all protocols in current class and
760/// those inherited by it.
761void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000762 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000763 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
764 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
765 PE = OI->protocol_end(); P != PE; ++P) {
766 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000767 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000768 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000769 PE = Proto->protocol_end(); P != PE; ++P) {
770 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000771 CollectInheritedProtocols(*P, Protocols);
772 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000773 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000774
775 // Categories of this Interface.
776 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
777 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
778 CollectInheritedProtocols(CDeclChain, Protocols);
779 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
780 while (SD) {
781 CollectInheritedProtocols(SD, Protocols);
782 SD = SD->getSuperClass();
783 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000784 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000785 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
786 PE = OC->protocol_end(); P != PE; ++P) {
787 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000788 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000789 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
790 PE = Proto->protocol_end(); P != PE; ++P)
791 CollectInheritedProtocols(*P, Protocols);
792 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000793 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000794 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
795 PE = OP->protocol_end(); P != PE; ++P) {
796 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000797 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000798 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
799 PE = Proto->protocol_end(); P != PE; ++P)
800 CollectInheritedProtocols(*P, Protocols);
801 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000802 }
803}
804
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000805unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
806 unsigned count = 0;
807 // Count ivars declared in class extension.
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000808 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension())
809 count += CDecl->ivar_size();
810
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000811 // Count ivar defined in this class's implementation. This
812 // includes synthesized ivars.
813 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000814 count += ImplDecl->ivar_size();
815
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000816 return count;
817}
818
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000819/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
820ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
821 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
822 I = ObjCImpls.find(D);
823 if (I != ObjCImpls.end())
824 return cast<ObjCImplementationDecl>(I->second);
825 return 0;
826}
827/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
828ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
829 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
830 I = ObjCImpls.find(D);
831 if (I != ObjCImpls.end())
832 return cast<ObjCCategoryImplDecl>(I->second);
833 return 0;
834}
835
836/// \brief Set the implementation of ObjCInterfaceDecl.
837void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
838 ObjCImplementationDecl *ImplD) {
839 assert(IFaceD && ImplD && "Passed null params");
840 ObjCImpls[IFaceD] = ImplD;
841}
842/// \brief Set the implementation of ObjCCategoryDecl.
843void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
844 ObjCCategoryImplDecl *ImplD) {
845 assert(CatD && ImplD && "Passed null params");
846 ObjCImpls[CatD] = ImplD;
847}
848
John McCallbcd03502009-12-07 02:54:59 +0000849/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000850///
John McCallbcd03502009-12-07 02:54:59 +0000851/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000852/// the TypeLoc wrappers.
853///
854/// \param T the type that will be the basis for type source info. This type
855/// should refer to how the declarator was written in source code, not to
856/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000857TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000858 unsigned DataSize) {
859 if (!DataSize)
860 DataSize = TypeLoc::getFullDataSizeForType(T);
861 else
862 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000863 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000864
John McCallbcd03502009-12-07 02:54:59 +0000865 TypeSourceInfo *TInfo =
866 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
867 new (TInfo) TypeSourceInfo(T);
868 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000869}
870
John McCallbcd03502009-12-07 02:54:59 +0000871TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +0000872 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +0000873 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +0000874 DI->getTypeLoc().initialize(L);
875 return DI;
876}
877
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000878/// getInterfaceLayoutImpl - Get or compute information about the
879/// layout of the given interface.
880///
881/// \param Impl - If given, also include the layout of the interface's
882/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +0000883const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000884ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
885 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +0000886 assert(!D->isForwardDecl() && "Invalid interface decl!");
887
Devang Pateldbb72632008-06-04 21:54:36 +0000888 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +0000889 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +0000890 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
891 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
892 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +0000893
Daniel Dunbar2b65fe32009-05-03 11:16:44 +0000894 // Add in synthesized ivar count if laying out an implementation.
895 if (Impl) {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000896 unsigned SynthCount = CountNonClassIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +0000897 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +0000898 // entry. Note we can't cache this because we simply free all
899 // entries later; however we shouldn't look up implementations
900 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000901 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +0000902 return getObjCLayout(D, 0);
903 }
904
Mike Stump11289f42009-09-09 15:08:12 +0000905 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +0000906 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
907 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +0000908
Devang Pateldbb72632008-06-04 21:54:36 +0000909 return *NewEntry;
910}
911
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000912const ASTRecordLayout &
913ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
914 return getObjCLayout(D, 0);
915}
916
917const ASTRecordLayout &
918ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
919 return getObjCLayout(D->getClassInterface(), D);
920}
921
Devang Patele11664a2007-11-01 19:11:01 +0000922/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +0000923/// specified record (struct/union/class), which indicates its size and field
924/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +0000925const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000926 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +0000927 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +0000928
Chris Lattner53cfe802007-07-18 17:52:12 +0000929 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +0000930 // Note that we can't save a reference to the entry because this function
931 // is recursive.
932 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +0000933 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +0000934
Mike Stump11289f42009-09-09 15:08:12 +0000935 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +0000936 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +0000937 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +0000938
Daniel Dunbarccabe482010-04-19 20:44:53 +0000939 if (getLangOptions().DumpRecordLayouts) {
940 llvm::errs() << "\n*** Dumping AST Record Layout\n";
941 DumpRecordLayout(D, llvm::errs());
942 }
943
Chris Lattner647fb222007-07-18 18:26:58 +0000944 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +0000945}
946
Anders Carlsson5ebf8b42009-12-07 04:35:11 +0000947const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000948 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +0000949 assert(RD && "Cannot get key function for forward declarations!");
950
951 const CXXMethodDecl *&Entry = KeyFunctions[RD];
952 if (!Entry)
953 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
954 else
955 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
956 "Key function changed!");
957
958 return Entry;
959}
960
Chris Lattner983a8bb2007-07-13 22:13:22 +0000961//===----------------------------------------------------------------------===//
962// Type creation/memoization methods
963//===----------------------------------------------------------------------===//
964
John McCall8ccfcb52009-09-24 19:53:00 +0000965QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
966 unsigned Fast = Quals.getFastQualifiers();
967 Quals.removeFastQualifiers();
968
969 // Check if we've already instantiated this type.
970 llvm::FoldingSetNodeID ID;
971 ExtQuals::Profile(ID, TypeNode, Quals);
972 void *InsertPos = 0;
973 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
974 assert(EQ->getQualifiers() == Quals);
975 QualType T = QualType(EQ, Fast);
976 return T;
977 }
978
John McCall90d1c2d2009-09-24 23:30:46 +0000979 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +0000980 ExtQualNodes.InsertNode(New, InsertPos);
981 QualType T = QualType(New, Fast);
982 return T;
983}
984
985QualType ASTContext::getVolatileType(QualType T) {
986 QualType CanT = getCanonicalType(T);
987 if (CanT.isVolatileQualified()) return T;
988
989 QualifierCollector Quals;
990 const Type *TypeNode = Quals.strip(T);
991 Quals.addVolatile();
992
993 return getExtQualType(TypeNode, Quals);
994}
995
Fariborz Jahanianece85822009-02-17 18:27:45 +0000996QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +0000997 QualType CanT = getCanonicalType(T);
998 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +0000999 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001000
John McCall8ccfcb52009-09-24 19:53:00 +00001001 // If we are composing extended qualifiers together, merge together
1002 // into one ExtQuals node.
1003 QualifierCollector Quals;
1004 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001005
John McCall8ccfcb52009-09-24 19:53:00 +00001006 // If this type already has an address space specified, it cannot get
1007 // another one.
1008 assert(!Quals.hasAddressSpace() &&
1009 "Type cannot be in multiple addr spaces!");
1010 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001011
John McCall8ccfcb52009-09-24 19:53:00 +00001012 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001013}
1014
Chris Lattnerd60183d2009-02-18 22:53:11 +00001015QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001016 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001017 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001018 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001019 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001020
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001021 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001022 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001023 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001024 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1025 return getPointerType(ResultType);
1026 }
1027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
John McCall8ccfcb52009-09-24 19:53:00 +00001029 // If we are composing extended qualifiers together, merge together
1030 // into one ExtQuals node.
1031 QualifierCollector Quals;
1032 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001033
John McCall8ccfcb52009-09-24 19:53:00 +00001034 // If this type already has an ObjCGC specified, it cannot get
1035 // another one.
1036 assert(!Quals.hasObjCGCAttr() &&
1037 "Type cannot have multiple ObjCGCs!");
1038 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001039
John McCall8ccfcb52009-09-24 19:53:00 +00001040 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001041}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001042
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001043static QualType getExtFunctionType(ASTContext& Context, QualType T,
1044 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001045 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001046 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1047 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001048 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001049 if (ResultType == Pointee)
1050 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001051
1052 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001053 } else if (const BlockPointerType *BlockPointer
1054 = T->getAs<BlockPointerType>()) {
1055 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001056 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001057 if (ResultType == Pointee)
1058 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001059
1060 ResultType = Context.getBlockPointerType(ResultType);
1061 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001062 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001063 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001064
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001065 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001066 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001067 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001068 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001069 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001070 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001071 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1072 FPT->getNumArgs(), FPT->isVariadic(),
1073 FPT->getTypeQuals(),
1074 FPT->hasExceptionSpec(),
1075 FPT->hasAnyExceptionSpec(),
1076 FPT->getNumExceptions(),
1077 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001078 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001079 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001080 } else
1081 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001082
1083 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1084}
1085
1086QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001087 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001088 return getExtFunctionType(*this, T,
1089 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001090}
1091
1092QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001093 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001094 return getExtFunctionType(*this, T,
1095 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001096}
1097
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001098QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1099 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1100 return getExtFunctionType(*this, T,
1101 Info.withRegParm(RegParm));
1102}
1103
Chris Lattnerc6395932007-06-22 20:56:16 +00001104/// getComplexType - Return the uniqued reference to the type for a complex
1105/// number with the specified element type.
1106QualType ASTContext::getComplexType(QualType T) {
1107 // Unique pointers, to guarantee there is only one pointer of a particular
1108 // structure.
1109 llvm::FoldingSetNodeID ID;
1110 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001111
Chris Lattnerc6395932007-06-22 20:56:16 +00001112 void *InsertPos = 0;
1113 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1114 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattnerc6395932007-06-22 20:56:16 +00001116 // If the pointee type isn't canonical, this won't be a canonical type either,
1117 // so fill in the canonical type field.
1118 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001119 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001120 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattnerc6395932007-06-22 20:56:16 +00001122 // Get the new insert position for the node we care about.
1123 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001124 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001125 }
John McCall90d1c2d2009-09-24 23:30:46 +00001126 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001127 Types.push_back(New);
1128 ComplexTypes.InsertNode(New, InsertPos);
1129 return QualType(New, 0);
1130}
1131
Chris Lattner970e54e2006-11-12 00:37:36 +00001132/// getPointerType - Return the uniqued reference to the type for a pointer to
1133/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001134QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001135 // Unique pointers, to guarantee there is only one pointer of a particular
1136 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001137 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001138 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001139
Chris Lattner67521df2007-01-27 01:29:36 +00001140 void *InsertPos = 0;
1141 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001142 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Chris Lattner7ccecb92006-11-12 08:50:50 +00001144 // If the pointee type isn't canonical, this won't be a canonical type either,
1145 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001146 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001147 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001148 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001149
Chris Lattner67521df2007-01-27 01:29:36 +00001150 // Get the new insert position for the node we care about.
1151 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001152 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001153 }
John McCall90d1c2d2009-09-24 23:30:46 +00001154 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001155 Types.push_back(New);
1156 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001157 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001158}
1159
Mike Stump11289f42009-09-09 15:08:12 +00001160/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001161/// a pointer to the specified block.
1162QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001163 assert(T->isFunctionType() && "block of function types only");
1164 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001165 // structure.
1166 llvm::FoldingSetNodeID ID;
1167 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Steve Naroffec33ed92008-08-27 16:04:49 +00001169 void *InsertPos = 0;
1170 if (BlockPointerType *PT =
1171 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1172 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001173
1174 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001175 // type either so fill in the canonical type field.
1176 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001177 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001178 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001179
Steve Naroffec33ed92008-08-27 16:04:49 +00001180 // Get the new insert position for the node we care about.
1181 BlockPointerType *NewIP =
1182 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001183 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001184 }
John McCall90d1c2d2009-09-24 23:30:46 +00001185 BlockPointerType *New
1186 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001187 Types.push_back(New);
1188 BlockPointerTypes.InsertNode(New, InsertPos);
1189 return QualType(New, 0);
1190}
1191
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001192/// getLValueReferenceType - Return the uniqued reference to the type for an
1193/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001194QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001195 // Unique pointers, to guarantee there is only one pointer of a particular
1196 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001197 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001198 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001199
1200 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001201 if (LValueReferenceType *RT =
1202 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001203 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001204
John McCallfc93cf92009-10-22 22:37:11 +00001205 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1206
Bill Wendling3708c182007-05-27 10:15:43 +00001207 // If the referencee type isn't canonical, this won't be a canonical type
1208 // either, so fill in the canonical type field.
1209 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001210 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1211 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1212 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001213
Bill Wendling3708c182007-05-27 10:15:43 +00001214 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001215 LValueReferenceType *NewIP =
1216 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001217 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001218 }
1219
John McCall90d1c2d2009-09-24 23:30:46 +00001220 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001221 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1222 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001223 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001224 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001225
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001226 return QualType(New, 0);
1227}
1228
1229/// getRValueReferenceType - Return the uniqued reference to the type for an
1230/// rvalue reference to the specified type.
1231QualType ASTContext::getRValueReferenceType(QualType T) {
1232 // Unique pointers, to guarantee there is only one pointer of a particular
1233 // structure.
1234 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001235 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001236
1237 void *InsertPos = 0;
1238 if (RValueReferenceType *RT =
1239 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1240 return QualType(RT, 0);
1241
John McCallfc93cf92009-10-22 22:37:11 +00001242 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1243
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001244 // If the referencee type isn't canonical, this won't be a canonical type
1245 // either, so fill in the canonical type field.
1246 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001247 if (InnerRef || !T.isCanonical()) {
1248 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1249 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001250
1251 // Get the new insert position for the node we care about.
1252 RValueReferenceType *NewIP =
1253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1254 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1255 }
1256
John McCall90d1c2d2009-09-24 23:30:46 +00001257 RValueReferenceType *New
1258 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001259 Types.push_back(New);
1260 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001261 return QualType(New, 0);
1262}
1263
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001264/// getMemberPointerType - Return the uniqued reference to the type for a
1265/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001266QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001267 // Unique pointers, to guarantee there is only one pointer of a particular
1268 // structure.
1269 llvm::FoldingSetNodeID ID;
1270 MemberPointerType::Profile(ID, T, Cls);
1271
1272 void *InsertPos = 0;
1273 if (MemberPointerType *PT =
1274 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1275 return QualType(PT, 0);
1276
1277 // If the pointee or class type isn't canonical, this won't be a canonical
1278 // type either, so fill in the canonical type field.
1279 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001280 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001281 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1282
1283 // Get the new insert position for the node we care about.
1284 MemberPointerType *NewIP =
1285 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1286 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1287 }
John McCall90d1c2d2009-09-24 23:30:46 +00001288 MemberPointerType *New
1289 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001290 Types.push_back(New);
1291 MemberPointerTypes.InsertNode(New, InsertPos);
1292 return QualType(New, 0);
1293}
1294
Mike Stump11289f42009-09-09 15:08:12 +00001295/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001296/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001297QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001298 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001299 ArrayType::ArraySizeModifier ASM,
1300 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001301 assert((EltTy->isDependentType() ||
1302 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001303 "Constant array of VLAs is illegal!");
1304
Chris Lattnere2df3f92009-05-13 04:12:56 +00001305 // Convert the array size into a canonical width matching the pointer size for
1306 // the target.
1307 llvm::APInt ArySize(ArySizeIn);
1308 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattner23b7eb62007-06-15 23:05:46 +00001310 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001311 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001312
Chris Lattner36f8e652007-01-27 08:31:04 +00001313 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001314 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001315 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001316 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattner7ccecb92006-11-12 08:50:50 +00001318 // If the element type isn't canonical, this won't be a canonical type either,
1319 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001320 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001321 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001322 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001323 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001324 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001325 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001326 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001327 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCall90d1c2d2009-09-24 23:30:46 +00001330 ConstantArrayType *New = new(*this,TypeAlignment)
1331 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001332 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001333 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001334 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001335}
1336
Steve Naroffcadebd02007-08-30 18:14:25 +00001337/// getVariableArrayType - Returns a non-unique reference to the type for a
1338/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001339QualType ASTContext::getVariableArrayType(QualType EltTy,
1340 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001341 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001342 unsigned EltTypeQuals,
1343 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001344 // Since we don't unique expressions, it isn't possible to unique VLA's
1345 // that have an expression provided for their size.
1346
John McCall90d1c2d2009-09-24 23:30:46 +00001347 VariableArrayType *New = new(*this, TypeAlignment)
1348 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001349
1350 VariableArrayTypes.push_back(New);
1351 Types.push_back(New);
1352 return QualType(New, 0);
1353}
1354
Douglas Gregor4619e432008-12-05 23:32:09 +00001355/// getDependentSizedArrayType - Returns a non-unique reference to
1356/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001357/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001358QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1359 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001360 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001361 unsigned EltTypeQuals,
1362 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001363 assert((!NumElts || NumElts->isTypeDependent() ||
1364 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001365 "Size must be type- or value-dependent!");
1366
Douglas Gregorf3f95522009-07-31 00:23:35 +00001367 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001368 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001369 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001370
1371 if (NumElts) {
1372 // Dependently-sized array types that do not have a specified
1373 // number of elements will have their sizes deduced from an
1374 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001375 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1376 EltTypeQuals, NumElts);
1377
1378 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1379 }
1380
Douglas Gregorf3f95522009-07-31 00:23:35 +00001381 DependentSizedArrayType *New;
1382 if (Canon) {
1383 // We already have a canonical version of this array type; use it as
1384 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001385 New = new (*this, TypeAlignment)
1386 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1387 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001388 } else {
1389 QualType CanonEltTy = getCanonicalType(EltTy);
1390 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001391 New = new (*this, TypeAlignment)
1392 DependentSizedArrayType(*this, EltTy, QualType(),
1393 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001394
Douglas Gregorc42075a2010-02-04 18:10:26 +00001395 if (NumElts) {
1396 DependentSizedArrayType *CanonCheck
1397 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1398 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1399 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001400 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001401 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001402 } else {
1403 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1404 ASM, EltTypeQuals,
1405 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001406 New = new (*this, TypeAlignment)
1407 DependentSizedArrayType(*this, EltTy, Canon,
1408 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001409 }
1410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
Douglas Gregor4619e432008-12-05 23:32:09 +00001412 Types.push_back(New);
1413 return QualType(New, 0);
1414}
1415
Eli Friedmanbd258282008-02-15 18:16:39 +00001416QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1417 ArrayType::ArraySizeModifier ASM,
1418 unsigned EltTypeQuals) {
1419 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001420 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001421
1422 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001423 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001424 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1425 return QualType(ATP, 0);
1426
1427 // If the element type isn't canonical, this won't be a canonical type
1428 // either, so fill in the canonical type field.
1429 QualType Canonical;
1430
John McCallb692a092009-10-22 20:10:53 +00001431 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001432 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001433 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001434
1435 // Get the new insert position for the node we care about.
1436 IncompleteArrayType *NewIP =
1437 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001438 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001439 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001440
John McCall90d1c2d2009-09-24 23:30:46 +00001441 IncompleteArrayType *New = new (*this, TypeAlignment)
1442 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001443
1444 IncompleteArrayTypes.InsertNode(New, InsertPos);
1445 Types.push_back(New);
1446 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001447}
1448
Steve Naroff91fcddb2007-07-18 18:00:27 +00001449/// getVectorType - Return the unique reference to a vector type of
1450/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001451QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1452 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001453 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Chris Lattner76a00cf2008-04-06 22:59:24 +00001455 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001456 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001457
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001458 // Check if we've already instantiated a vector of this type.
1459 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001460 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1461 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001462 void *InsertPos = 0;
1463 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1464 return QualType(VTP, 0);
1465
1466 // If the element type isn't canonical, this won't be a canonical type either,
1467 // so fill in the canonical type field.
1468 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001469 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1470 Canonical = getVectorType(getCanonicalType(vecType),
1471 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001472
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001473 // Get the new insert position for the node we care about.
1474 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001475 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001476 }
John McCall90d1c2d2009-09-24 23:30:46 +00001477 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001478 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001479 VectorTypes.InsertNode(New, InsertPos);
1480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
Nate Begemance4d7fc2008-04-18 23:10:10 +00001484/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001485/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001486QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001487 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattner76a00cf2008-04-06 22:59:24 +00001489 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001490 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001491
Steve Naroff91fcddb2007-07-18 18:00:27 +00001492 // Check if we've already instantiated a vector of this type.
1493 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001494 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001495 void *InsertPos = 0;
1496 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1497 return QualType(VTP, 0);
1498
1499 // If the element type isn't canonical, this won't be a canonical type either,
1500 // so fill in the canonical type field.
1501 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001502 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001503 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001504
Steve Naroff91fcddb2007-07-18 18:00:27 +00001505 // Get the new insert position for the node we care about.
1506 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001507 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001508 }
John McCall90d1c2d2009-09-24 23:30:46 +00001509 ExtVectorType *New = new (*this, TypeAlignment)
1510 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001511 VectorTypes.InsertNode(New, InsertPos);
1512 Types.push_back(New);
1513 return QualType(New, 0);
1514}
1515
Mike Stump11289f42009-09-09 15:08:12 +00001516QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001517 Expr *SizeExpr,
1518 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001519 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001520 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001521 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Douglas Gregor352169a2009-07-31 03:54:25 +00001523 void *InsertPos = 0;
1524 DependentSizedExtVectorType *Canon
1525 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1526 DependentSizedExtVectorType *New;
1527 if (Canon) {
1528 // We already have a canonical version of this array type; use it as
1529 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001530 New = new (*this, TypeAlignment)
1531 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1532 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001533 } else {
1534 QualType CanonVecTy = getCanonicalType(vecType);
1535 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001536 New = new (*this, TypeAlignment)
1537 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1538 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001539
1540 DependentSizedExtVectorType *CanonCheck
1541 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1542 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1543 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001544 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1545 } else {
1546 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1547 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001548 New = new (*this, TypeAlignment)
1549 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001550 }
1551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Douglas Gregor758a8692009-06-17 21:51:59 +00001553 Types.push_back(New);
1554 return QualType(New, 0);
1555}
1556
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001557/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001558///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001559QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1560 const FunctionType::ExtInfo &Info) {
1561 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001562 // Unique functions, to guarantee there is only one function of a particular
1563 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001564 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001565 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattner47955de2007-01-27 08:37:20 +00001567 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001568 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001569 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001570 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001572 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001573 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001574 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001575 Canonical =
1576 getFunctionNoProtoType(getCanonicalType(ResultTy),
1577 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001578
Chris Lattner47955de2007-01-27 08:37:20 +00001579 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001580 FunctionNoProtoType *NewIP =
1581 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001582 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
John McCall90d1c2d2009-09-24 23:30:46 +00001585 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001586 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001587 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001588 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001589 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001590}
1591
1592/// getFunctionType - Return a normal function type with a typed argument
1593/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001594QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001595 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001596 unsigned TypeQuals, bool hasExceptionSpec,
1597 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001598 const QualType *ExArray,
1599 const FunctionType::ExtInfo &Info) {
1600 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001601 // Unique functions, to guarantee there is only one function of a particular
1602 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001603 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001604 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001605 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001606 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001607
1608 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001609 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001610 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001611 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001612
1613 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001614 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001615 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001616 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001617 isCanonical = false;
1618
1619 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001620 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001621 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001622 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001623 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001624 CanonicalArgs.reserve(NumArgs);
1625 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001626 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001627
Chris Lattner76a00cf2008-04-06 22:59:24 +00001628 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001629 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001630 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001631 false, 0, 0,
1632 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001633
Chris Lattnerfd4de792007-01-27 01:15:32 +00001634 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001635 FunctionProtoType *NewIP =
1636 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001637 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001638 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001639
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001640 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001641 // for two variable size arrays (for parameter and exception types) at the
1642 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001643 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001644 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1645 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001646 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001647 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001648 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001649 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001650 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001651 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001652 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001653}
Chris Lattneref51c202006-11-10 07:17:23 +00001654
John McCalle78aac42010-03-10 03:28:59 +00001655#ifndef NDEBUG
1656static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1657 if (!isa<CXXRecordDecl>(D)) return false;
1658 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1659 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1660 return true;
1661 if (RD->getDescribedClassTemplate() &&
1662 !isa<ClassTemplateSpecializationDecl>(RD))
1663 return true;
1664 return false;
1665}
1666#endif
1667
1668/// getInjectedClassNameType - Return the unique reference to the
1669/// injected class name type for the specified templated declaration.
1670QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1671 QualType TST) {
1672 assert(NeedsInjectedClassNameType(Decl));
1673 if (Decl->TypeForDecl) {
1674 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1675 } else if (CXXRecordDecl *PrevDecl
1676 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1677 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1678 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1679 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1680 } else {
John McCall2408e322010-04-27 00:57:59 +00001681 Decl->TypeForDecl =
1682 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001683 Types.push_back(Decl->TypeForDecl);
1684 }
1685 return QualType(Decl->TypeForDecl, 0);
1686}
1687
Douglas Gregor83a586e2008-04-13 21:07:44 +00001688/// getTypeDeclType - Return the unique reference to the type for the
1689/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001690QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001691 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001692 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001693
John McCall81e38502010-02-16 03:57:14 +00001694 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001695 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001696
John McCall96f0b5f2010-03-10 06:48:02 +00001697 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1698 "Template type parameter types are always available.");
1699
John McCall81e38502010-02-16 03:57:14 +00001700 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001701 assert(!Record->getPreviousDeclaration() &&
1702 "struct/union has previous declaration");
1703 assert(!NeedsInjectedClassNameType(Record));
1704 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001705 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001706 assert(!Enum->getPreviousDeclaration() &&
1707 "enum has previous declaration");
1708 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001709 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001710 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1711 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001712 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001713 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001714
John McCall96f0b5f2010-03-10 06:48:02 +00001715 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001716 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001717}
1718
Chris Lattner32d920b2007-01-26 02:01:53 +00001719/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001720/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001721QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001722 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001723
Chris Lattner76a00cf2008-04-06 22:59:24 +00001724 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001725 Decl->TypeForDecl = new(*this, TypeAlignment)
1726 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001727 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001728 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001729}
1730
John McCallcebee162009-10-18 09:09:24 +00001731/// \brief Retrieve a substitution-result type.
1732QualType
1733ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1734 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001735 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001736 && "replacement types must always be canonical");
1737
1738 llvm::FoldingSetNodeID ID;
1739 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1740 void *InsertPos = 0;
1741 SubstTemplateTypeParmType *SubstParm
1742 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1743
1744 if (!SubstParm) {
1745 SubstParm = new (*this, TypeAlignment)
1746 SubstTemplateTypeParmType(Parm, Replacement);
1747 Types.push_back(SubstParm);
1748 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1749 }
1750
1751 return QualType(SubstParm, 0);
1752}
1753
Douglas Gregoreff93e02009-02-05 23:33:38 +00001754/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001755/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001756/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001757QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001758 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00001759 IdentifierInfo *Name) {
1760 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001761 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001762 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001763 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001764 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1765
1766 if (TypeParm)
1767 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001768
Anders Carlsson90036dc2009-06-16 00:30:48 +00001769 if (Name) {
1770 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00001771 TypeParm = new (*this, TypeAlignment)
1772 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001773
1774 TemplateTypeParmType *TypeCheck
1775 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1776 assert(!TypeCheck && "Template type parameter canonical type broken");
1777 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001778 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001779 TypeParm = new (*this, TypeAlignment)
1780 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001781
1782 Types.push_back(TypeParm);
1783 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1784
1785 return QualType(TypeParm, 0);
1786}
1787
John McCalle78aac42010-03-10 03:28:59 +00001788TypeSourceInfo *
1789ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1790 SourceLocation NameLoc,
1791 const TemplateArgumentListInfo &Args,
1792 QualType CanonType) {
1793 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1794
1795 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1796 TemplateSpecializationTypeLoc TL
1797 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1798 TL.setTemplateNameLoc(NameLoc);
1799 TL.setLAngleLoc(Args.getLAngleLoc());
1800 TL.setRAngleLoc(Args.getRAngleLoc());
1801 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1802 TL.setArgLocInfo(i, Args[i].getLocInfo());
1803 return DI;
1804}
1805
Mike Stump11289f42009-09-09 15:08:12 +00001806QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001807ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001808 const TemplateArgumentListInfo &Args,
John McCall2408e322010-04-27 00:57:59 +00001809 QualType Canon,
1810 bool IsCurrentInstantiation) {
John McCall6b51f282009-11-23 01:53:49 +00001811 unsigned NumArgs = Args.size();
1812
John McCall0ad16662009-10-29 08:12:44 +00001813 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1814 ArgVec.reserve(NumArgs);
1815 for (unsigned i = 0; i != NumArgs; ++i)
1816 ArgVec.push_back(Args[i].getArgument());
1817
John McCall2408e322010-04-27 00:57:59 +00001818 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1819 Canon, IsCurrentInstantiation);
John McCall0ad16662009-10-29 08:12:44 +00001820}
1821
1822QualType
1823ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001824 const TemplateArgument *Args,
1825 unsigned NumArgs,
John McCall2408e322010-04-27 00:57:59 +00001826 QualType Canon,
1827 bool IsCurrentInstantiation) {
Douglas Gregor15301382009-07-30 17:40:51 +00001828 if (!Canon.isNull())
1829 Canon = getCanonicalType(Canon);
1830 else {
John McCall2408e322010-04-27 00:57:59 +00001831 assert(!IsCurrentInstantiation &&
1832 "current-instantiation specializations should always "
1833 "have a canonical type");
1834
Douglas Gregor15301382009-07-30 17:40:51 +00001835 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001836 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1837 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1838 CanonArgs.reserve(NumArgs);
1839 for (unsigned I = 0; I != NumArgs; ++I)
1840 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1841
1842 // Determine whether this canonical template specialization type already
1843 // exists.
1844 llvm::FoldingSetNodeID ID;
John McCall2408e322010-04-27 00:57:59 +00001845 TemplateSpecializationType::Profile(ID, CanonTemplate, false,
Douglas Gregor00044172009-07-29 16:09:57 +00001846 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001847
1848 void *InsertPos = 0;
1849 TemplateSpecializationType *Spec
1850 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregora8e02e72009-07-28 23:00:59 +00001852 if (!Spec) {
1853 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001854 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001855 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001856 TypeAlignment);
John McCall2408e322010-04-27 00:57:59 +00001857 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, false,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001858 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001859 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001860 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001861 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001862 }
Mike Stump11289f42009-09-09 15:08:12 +00001863
Douglas Gregor15301382009-07-30 17:40:51 +00001864 if (Canon.isNull())
1865 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001866 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001867 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001868 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001869
Douglas Gregora8e02e72009-07-28 23:00:59 +00001870 // Allocate the (non-canonical) template specialization type, but don't
1871 // try to unique it: these types typically have location information that
1872 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001873 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001874 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001875 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001876 TemplateSpecializationType *Spec
John McCall2408e322010-04-27 00:57:59 +00001877 = new (Mem) TemplateSpecializationType(*this, Template,
1878 IsCurrentInstantiation,
1879 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001880 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregor8bf42052009-02-09 18:46:07 +00001882 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001883 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001884}
1885
Mike Stump11289f42009-09-09 15:08:12 +00001886QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001887ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1888 NestedNameSpecifier *NNS,
1889 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001890 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001891 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001892
1893 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001894 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001895 if (T)
1896 return QualType(T, 0);
1897
Douglas Gregorc42075a2010-02-04 18:10:26 +00001898 QualType Canon = NamedType;
1899 if (!Canon.isCanonical()) {
1900 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001901 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1902 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001903 (void)CheckT;
1904 }
1905
Abramo Bagnara6150c882010-05-11 21:36:43 +00001906 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001907 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001908 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001909 return QualType(T, 0);
1910}
1911
Douglas Gregor02085352010-03-31 20:19:30 +00001912QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1913 NestedNameSpecifier *NNS,
1914 const IdentifierInfo *Name,
1915 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001916 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1917
1918 if (Canon.isNull()) {
1919 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001920 ElaboratedTypeKeyword CanonKeyword = Keyword;
1921 if (Keyword == ETK_None)
1922 CanonKeyword = ETK_Typename;
1923
1924 if (CanonNNS != NNS || CanonKeyword != Keyword)
1925 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001926 }
1927
1928 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001929 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001930
1931 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001932 DependentNameType *T
1933 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00001934 if (T)
1935 return QualType(T, 0);
1936
Douglas Gregor02085352010-03-31 20:19:30 +00001937 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00001938 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001939 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001940 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00001941}
1942
Mike Stump11289f42009-09-09 15:08:12 +00001943QualType
Douglas Gregor02085352010-03-31 20:19:30 +00001944ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1945 NestedNameSpecifier *NNS,
1946 const TemplateSpecializationType *TemplateId,
1947 QualType Canon) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001948 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1949
Douglas Gregorc42075a2010-02-04 18:10:26 +00001950 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001951 DependentNameType::Profile(ID, Keyword, NNS, TemplateId);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001952
1953 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001954 DependentNameType *T
1955 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001956 if (T)
1957 return QualType(T, 0);
1958
Douglas Gregordce2b622009-04-01 00:28:59 +00001959 if (Canon.isNull()) {
1960 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1961 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
Douglas Gregor02085352010-03-31 20:19:30 +00001962 ElaboratedTypeKeyword CanonKeyword = Keyword;
1963 if (Keyword == ETK_None)
1964 CanonKeyword = ETK_Typename;
1965 if (CanonNNS != NNS || CanonKeyword != Keyword ||
1966 CanonType != QualType(TemplateId, 0)) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001967 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00001968 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00001969 assert(CanonTemplateId &&
1970 "Canonical type must also be a template specialization type");
Douglas Gregor02085352010-03-31 20:19:30 +00001971 Canon = getDependentNameType(CanonKeyword, CanonNNS, CanonTemplateId);
Douglas Gregordce2b622009-04-01 00:28:59 +00001972 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00001973
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001974 DependentNameType *CheckT
1975 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001976 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00001977 }
1978
Douglas Gregor02085352010-03-31 20:19:30 +00001979 T = new (*this) DependentNameType(Keyword, NNS, TemplateId, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00001980 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001981 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001982 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00001983}
1984
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001985/// CmpProtocolNames - Comparison predicate for sorting protocols
1986/// alphabetically.
1987static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1988 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00001989 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001990}
1991
John McCall8b07ec22010-05-15 11:32:37 +00001992static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00001993 unsigned NumProtocols) {
1994 if (NumProtocols == 0) return true;
1995
1996 for (unsigned i = 1; i != NumProtocols; ++i)
1997 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1998 return false;
1999 return true;
2000}
2001
2002static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002003 unsigned &NumProtocols) {
2004 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002006 // Sort protocols, keyed by name.
2007 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2008
2009 // Remove duplicates.
2010 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2011 NumProtocols = ProtocolsEnd-Protocols;
2012}
2013
John McCall8b07ec22010-05-15 11:32:37 +00002014QualType ASTContext::getObjCObjectType(QualType BaseType,
2015 ObjCProtocolDecl * const *Protocols,
2016 unsigned NumProtocols) {
2017 // If the base type is an interface and there aren't any protocols
2018 // to add, then the interface type will do just fine.
2019 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2020 return BaseType;
2021
2022 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002023 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002024 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002025 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002026 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2027 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002028
John McCall8b07ec22010-05-15 11:32:37 +00002029 // Build the canonical type, which has the canonical base type and
2030 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002031 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002032 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2033 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2034 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002035 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2036 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002037 unsigned UniqueCount = NumProtocols;
2038
John McCallfc93cf92009-10-22 22:37:11 +00002039 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002040 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2041 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002042 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002043 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2044 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002045 }
2046
2047 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002048 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2049 }
2050
2051 unsigned Size = sizeof(ObjCObjectTypeImpl);
2052 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2053 void *Mem = Allocate(Size, TypeAlignment);
2054 ObjCObjectTypeImpl *T =
2055 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2056
2057 Types.push_back(T);
2058 ObjCObjectTypes.InsertNode(T, InsertPos);
2059 return QualType(T, 0);
2060}
2061
2062/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2063/// the given object type.
2064QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2065 llvm::FoldingSetNodeID ID;
2066 ObjCObjectPointerType::Profile(ID, ObjectT);
2067
2068 void *InsertPos = 0;
2069 if (ObjCObjectPointerType *QT =
2070 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2071 return QualType(QT, 0);
2072
2073 // Find the canonical object type.
2074 QualType Canonical;
2075 if (!ObjectT.isCanonical()) {
2076 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2077
2078 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002079 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2080 }
2081
Douglas Gregorf85bee62010-02-08 22:59:26 +00002082 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002083 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2084 ObjCObjectPointerType *QType =
2085 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002086
Steve Narofffb4330f2009-06-17 22:40:22 +00002087 Types.push_back(QType);
2088 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002089 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002090}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002091
Steve Naroffc277ad12009-07-18 15:33:26 +00002092/// getObjCInterfaceType - Return the unique reference to the type for the
2093/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002094QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2095 if (Decl->TypeForDecl)
2096 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002097
John McCall8b07ec22010-05-15 11:32:37 +00002098 // FIXME: redeclarations?
2099 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2100 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2101 Decl->TypeForDecl = T;
2102 Types.push_back(T);
2103 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002104}
2105
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002106/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2107/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002108/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002109/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002110/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002111QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002112 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002113 if (tofExpr->isTypeDependent()) {
2114 llvm::FoldingSetNodeID ID;
2115 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002116
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002117 void *InsertPos = 0;
2118 DependentTypeOfExprType *Canon
2119 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2120 if (Canon) {
2121 // We already have a "canonical" version of an identical, dependent
2122 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002123 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002124 QualType((TypeOfExprType*)Canon, 0));
2125 }
2126 else {
2127 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002128 Canon
2129 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002130 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2131 toe = Canon;
2132 }
2133 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002134 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002135 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002136 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002137 Types.push_back(toe);
2138 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002139}
2140
Steve Naroffa773cd52007-08-01 18:02:17 +00002141/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2142/// TypeOfType AST's. The only motivation to unique these nodes would be
2143/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002144/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002145/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002146QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002147 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002148 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002149 Types.push_back(tot);
2150 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002151}
2152
Anders Carlssonad6bd352009-06-24 21:24:56 +00002153/// getDecltypeForExpr - Given an expr, will return the decltype for that
2154/// expression, according to the rules in C++0x [dcl.type.simple]p4
2155static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002156 if (e->isTypeDependent())
2157 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002158
Anders Carlssonad6bd352009-06-24 21:24:56 +00002159 // If e is an id expression or a class member access, decltype(e) is defined
2160 // as the type of the entity named by e.
2161 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2162 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2163 return VD->getType();
2164 }
2165 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2166 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2167 return FD->getType();
2168 }
2169 // If e is a function call or an invocation of an overloaded operator,
2170 // (parentheses around e are ignored), decltype(e) is defined as the
2171 // return type of that function.
2172 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2173 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002174
Anders Carlssonad6bd352009-06-24 21:24:56 +00002175 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002176
2177 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002178 // defined as T&, otherwise decltype(e) is defined as T.
2179 if (e->isLvalue(Context) == Expr::LV_Valid)
2180 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002181
Anders Carlssonad6bd352009-06-24 21:24:56 +00002182 return T;
2183}
2184
Anders Carlsson81df7b82009-06-24 19:06:50 +00002185/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2186/// DecltypeType AST's. The only motivation to unique these nodes would be
2187/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002188/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002189/// on canonical type's (which are always unique).
2190QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002191 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002192 if (e->isTypeDependent()) {
2193 llvm::FoldingSetNodeID ID;
2194 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002195
Douglas Gregora21f6c32009-07-30 23:36:40 +00002196 void *InsertPos = 0;
2197 DependentDecltypeType *Canon
2198 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2199 if (Canon) {
2200 // We already have a "canonical" version of an equivalent, dependent
2201 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002202 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002203 QualType((DecltypeType*)Canon, 0));
2204 }
2205 else {
2206 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002207 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002208 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2209 dt = Canon;
2210 }
2211 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002212 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002213 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002214 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002215 Types.push_back(dt);
2216 return QualType(dt, 0);
2217}
2218
Chris Lattnerfb072462007-01-23 05:45:31 +00002219/// getTagDeclType - Return the unique reference to the type for the
2220/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002221QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002222 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002223 // FIXME: What is the design on getTagDeclType when it requires casting
2224 // away const? mutable?
2225 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002226}
2227
Mike Stump11289f42009-09-09 15:08:12 +00002228/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2229/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2230/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002231CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002232 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002233}
Chris Lattnerfb072462007-01-23 05:45:31 +00002234
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002235/// getSignedWCharType - Return the type of "signed wchar_t".
2236/// Used when in C++, as a GCC extension.
2237QualType ASTContext::getSignedWCharType() const {
2238 // FIXME: derive from "Target" ?
2239 return WCharTy;
2240}
2241
2242/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2243/// Used when in C++, as a GCC extension.
2244QualType ASTContext::getUnsignedWCharType() const {
2245 // FIXME: derive from "Target" ?
2246 return UnsignedIntTy;
2247}
2248
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002249/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2250/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2251QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002252 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002253}
2254
Chris Lattnera21ad802008-04-02 05:18:44 +00002255//===----------------------------------------------------------------------===//
2256// Type Operators
2257//===----------------------------------------------------------------------===//
2258
John McCallfc93cf92009-10-22 22:37:11 +00002259CanQualType ASTContext::getCanonicalParamType(QualType T) {
2260 // Push qualifiers into arrays, and then discard any remaining
2261 // qualifiers.
2262 T = getCanonicalType(T);
2263 const Type *Ty = T.getTypePtr();
2264
2265 QualType Result;
2266 if (isa<ArrayType>(Ty)) {
2267 Result = getArrayDecayedType(QualType(Ty,0));
2268 } else if (isa<FunctionType>(Ty)) {
2269 Result = getPointerType(QualType(Ty, 0));
2270 } else {
2271 Result = QualType(Ty, 0);
2272 }
2273
2274 return CanQualType::CreateUnsafe(Result);
2275}
2276
Chris Lattnered0d0792008-04-06 22:41:35 +00002277/// getCanonicalType - Return the canonical (structural) type corresponding to
2278/// the specified potentially non-canonical type. The non-canonical version
2279/// of a type may have many "decorated" versions of types. Decorators can
2280/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2281/// to be free of any of these, allowing two canonical types to be compared
2282/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002283CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002284 QualifierCollector Quals;
2285 const Type *Ptr = Quals.strip(T);
2286 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002287
John McCall8ccfcb52009-09-24 19:53:00 +00002288 // The canonical internal type will be the canonical type *except*
2289 // that we push type qualifiers down through array types.
2290
2291 // If there are no new qualifiers to push down, stop here.
2292 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002293 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002294
John McCall8ccfcb52009-09-24 19:53:00 +00002295 // If the type qualifiers are on an array type, get the canonical
2296 // type of the array with the qualifiers applied to the element
2297 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002298 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2299 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002300 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattner7adf0762008-08-04 07:31:14 +00002302 // Get the canonical version of the element with the extra qualifiers on it.
2303 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002304 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002305 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002306
Chris Lattner7adf0762008-08-04 07:31:14 +00002307 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002308 return CanQualType::CreateUnsafe(
2309 getConstantArrayType(NewEltTy, CAT->getSize(),
2310 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002311 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002312 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002313 return CanQualType::CreateUnsafe(
2314 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002315 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002316
Douglas Gregor4619e432008-12-05 23:32:09 +00002317 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002318 return CanQualType::CreateUnsafe(
2319 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002320 DSAT->getSizeExpr() ?
2321 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002322 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002323 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002324 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002325
Chris Lattner7adf0762008-08-04 07:31:14 +00002326 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002327 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002328 VAT->getSizeExpr() ?
2329 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002330 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002331 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002332 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002333}
2334
Chandler Carruth607f38e2009-12-29 07:16:59 +00002335QualType ASTContext::getUnqualifiedArrayType(QualType T,
2336 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002337 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002338 const ArrayType *AT = getAsArrayType(T);
2339 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002340 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002341 }
2342
Chandler Carruth607f38e2009-12-29 07:16:59 +00002343 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002344 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002345 if (Elt == UnqualElt)
2346 return T;
2347
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002348 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002349 return getConstantArrayType(UnqualElt, CAT->getSize(),
2350 CAT->getSizeModifier(), 0);
2351 }
2352
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002353 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002354 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2355 }
2356
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002357 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2358 return getVariableArrayType(UnqualElt,
2359 VAT->getSizeExpr() ?
2360 VAT->getSizeExpr()->Retain() : 0,
2361 VAT->getSizeModifier(),
2362 VAT->getIndexTypeCVRQualifiers(),
2363 VAT->getBracketsRange());
2364 }
2365
2366 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002367 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2368 DSAT->getSizeModifier(), 0,
2369 SourceRange());
2370}
2371
John McCall847e2a12009-11-24 18:42:40 +00002372DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2373 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2374 return TD->getDeclName();
2375
2376 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2377 if (DTN->isIdentifier()) {
2378 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2379 } else {
2380 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2381 }
2382 }
2383
John McCalld28ae272009-12-02 08:04:21 +00002384 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2385 assert(Storage);
2386 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002387}
2388
Douglas Gregor6bc50582009-05-07 06:41:52 +00002389TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2390 // If this template name refers to a template, the canonical
2391 // template name merely stores the template itself.
2392 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002393 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002394
John McCalld28ae272009-12-02 08:04:21 +00002395 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregor6bc50582009-05-07 06:41:52 +00002397 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2398 assert(DTN && "Non-dependent template names must refer to template decls.");
2399 return DTN->CanonicalTemplateName;
2400}
2401
Douglas Gregoradee3e32009-11-11 23:06:43 +00002402bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2403 X = getCanonicalTemplateName(X);
2404 Y = getCanonicalTemplateName(Y);
2405 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2406}
2407
Mike Stump11289f42009-09-09 15:08:12 +00002408TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002409ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2410 switch (Arg.getKind()) {
2411 case TemplateArgument::Null:
2412 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002413
Douglas Gregora8e02e72009-07-28 23:00:59 +00002414 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002415 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002416
Douglas Gregora8e02e72009-07-28 23:00:59 +00002417 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002418 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002419
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002420 case TemplateArgument::Template:
2421 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2422
Douglas Gregora8e02e72009-07-28 23:00:59 +00002423 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002424 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002425 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002426
Douglas Gregora8e02e72009-07-28 23:00:59 +00002427 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002428 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002429
Douglas Gregora8e02e72009-07-28 23:00:59 +00002430 case TemplateArgument::Pack: {
2431 // FIXME: Allocate in ASTContext
2432 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2433 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002434 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002435 AEnd = Arg.pack_end();
2436 A != AEnd; (void)++A, ++Idx)
2437 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002438
Douglas Gregora8e02e72009-07-28 23:00:59 +00002439 TemplateArgument Result;
2440 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2441 return Result;
2442 }
2443 }
2444
2445 // Silence GCC warning
2446 assert(false && "Unhandled template argument kind");
2447 return TemplateArgument();
2448}
2449
Douglas Gregor333489b2009-03-27 23:10:48 +00002450NestedNameSpecifier *
2451ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002452 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002453 return 0;
2454
2455 switch (NNS->getKind()) {
2456 case NestedNameSpecifier::Identifier:
2457 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002458 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002459 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2460 NNS->getAsIdentifier());
2461
2462 case NestedNameSpecifier::Namespace:
2463 // A namespace is canonical; build a nested-name-specifier with
2464 // this namespace and no prefix.
2465 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2466
2467 case NestedNameSpecifier::TypeSpec:
2468 case NestedNameSpecifier::TypeSpecWithTemplate: {
2469 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002470 return NestedNameSpecifier::Create(*this, 0,
2471 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002472 T.getTypePtr());
2473 }
2474
2475 case NestedNameSpecifier::Global:
2476 // The global specifier is canonical and unique.
2477 return NNS;
2478 }
2479
2480 // Required to silence a GCC warning
2481 return 0;
2482}
2483
Chris Lattner7adf0762008-08-04 07:31:14 +00002484
2485const ArrayType *ASTContext::getAsArrayType(QualType T) {
2486 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002487 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002488 // Handle the common positive case fast.
2489 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2490 return AT;
2491 }
Mike Stump11289f42009-09-09 15:08:12 +00002492
John McCall8ccfcb52009-09-24 19:53:00 +00002493 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002494 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002495 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002496 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002497
John McCall8ccfcb52009-09-24 19:53:00 +00002498 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002499 // implements C99 6.7.3p8: "If the specification of an array type includes
2500 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattner7adf0762008-08-04 07:31:14 +00002502 // If we get here, we either have type qualifiers on the type, or we have
2503 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002504 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002505
John McCall8ccfcb52009-09-24 19:53:00 +00002506 QualifierCollector Qs;
2507 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattner7adf0762008-08-04 07:31:14 +00002509 // If we have a simple case, just return now.
2510 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002511 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002512 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002513
Chris Lattner7adf0762008-08-04 07:31:14 +00002514 // Otherwise, we have an array and we have qualifiers on it. Push the
2515 // qualifiers into the array element type and return a new array type.
2516 // Get the canonical version of the element with the extra qualifiers on it.
2517 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002518 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002519
Chris Lattner7adf0762008-08-04 07:31:14 +00002520 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2521 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2522 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002523 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002524 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2525 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2526 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002527 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002528
Mike Stump11289f42009-09-09 15:08:12 +00002529 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002530 = dyn_cast<DependentSizedArrayType>(ATy))
2531 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002532 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002533 DSAT->getSizeExpr() ?
2534 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002535 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002536 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002537 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002538
Chris Lattner7adf0762008-08-04 07:31:14 +00002539 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002540 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002541 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002542 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002543 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002544 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002545 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002546}
2547
2548
Chris Lattnera21ad802008-04-02 05:18:44 +00002549/// getArrayDecayedType - Return the properly qualified result of decaying the
2550/// specified array type to a pointer. This operation is non-trivial when
2551/// handling typedefs etc. The canonical type of "T" must be an array type,
2552/// this returns a pointer to a properly qualified element of the array.
2553///
2554/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2555QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002556 // Get the element type with 'getAsArrayType' so that we don't lose any
2557 // typedefs in the element type of the array. This also handles propagation
2558 // of type qualifiers from the array type into the element type if present
2559 // (C99 6.7.3p8).
2560 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2561 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002562
Chris Lattner7adf0762008-08-04 07:31:14 +00002563 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002564
2565 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002566 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002567}
2568
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002569QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002570 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002571 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2572 QT = AT->getElementType();
2573 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002574}
2575
Anders Carlsson4bf82142009-09-25 01:23:32 +00002576QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2577 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002578
Anders Carlsson4bf82142009-09-25 01:23:32 +00002579 if (const ArrayType *AT = getAsArrayType(ElemTy))
2580 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002581
Anders Carlssone0808df2008-12-21 03:44:36 +00002582 return ElemTy;
2583}
2584
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002585/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002586uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002587ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2588 uint64_t ElementCount = 1;
2589 do {
2590 ElementCount *= CA->getSize().getZExtValue();
2591 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2592 } while (CA);
2593 return ElementCount;
2594}
2595
Steve Naroff0af91202007-04-27 21:51:21 +00002596/// getFloatingRank - Return a relative rank for floating point types.
2597/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002598static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002599 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002600 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002601
John McCall9dd450b2009-09-21 23:43:11 +00002602 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2603 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002604 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002605 case BuiltinType::Float: return FloatRank;
2606 case BuiltinType::Double: return DoubleRank;
2607 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002608 }
2609}
2610
Mike Stump11289f42009-09-09 15:08:12 +00002611/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2612/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002613/// 'typeDomain' is a real floating point or complex type.
2614/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002615QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2616 QualType Domain) const {
2617 FloatingRank EltRank = getFloatingRank(Size);
2618 if (Domain->isComplexType()) {
2619 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002620 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002621 case FloatRank: return FloatComplexTy;
2622 case DoubleRank: return DoubleComplexTy;
2623 case LongDoubleRank: return LongDoubleComplexTy;
2624 }
Steve Naroff0af91202007-04-27 21:51:21 +00002625 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002626
2627 assert(Domain->isRealFloatingType() && "Unknown domain!");
2628 switch (EltRank) {
2629 default: assert(0 && "getFloatingRank(): illegal value for rank");
2630 case FloatRank: return FloatTy;
2631 case DoubleRank: return DoubleTy;
2632 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002633 }
Steve Naroffe4718892007-04-27 18:30:00 +00002634}
2635
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002636/// getFloatingTypeOrder - Compare the rank of the two specified floating
2637/// point types, ignoring the domain of the type (i.e. 'double' ==
2638/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002639/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002640int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2641 FloatingRank LHSR = getFloatingRank(LHS);
2642 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002643
Chris Lattnerb90739d2008-04-06 23:38:49 +00002644 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002645 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002646 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002647 return 1;
2648 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002649}
2650
Chris Lattner76a00cf2008-04-06 22:59:24 +00002651/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2652/// routine will assert if passed a built-in type that isn't an integer or enum,
2653/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002654unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002655 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002656 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002657 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002658
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002659 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2660 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2661
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002662 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2663 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2664
2665 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2666 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2667
Chris Lattner76a00cf2008-04-06 22:59:24 +00002668 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002669 default: assert(0 && "getIntegerRank(): not a built-in integer");
2670 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002671 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002672 case BuiltinType::Char_S:
2673 case BuiltinType::Char_U:
2674 case BuiltinType::SChar:
2675 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002676 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002677 case BuiltinType::Short:
2678 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002679 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002680 case BuiltinType::Int:
2681 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002682 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002683 case BuiltinType::Long:
2684 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002685 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002686 case BuiltinType::LongLong:
2687 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002688 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002689 case BuiltinType::Int128:
2690 case BuiltinType::UInt128:
2691 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002692 }
2693}
2694
Eli Friedman629ffb92009-08-20 04:21:42 +00002695/// \brief Whether this is a promotable bitfield reference according
2696/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2697///
2698/// \returns the type this bit-field will promote to, or NULL if no
2699/// promotion occurs.
2700QualType ASTContext::isPromotableBitField(Expr *E) {
2701 FieldDecl *Field = E->getBitField();
2702 if (!Field)
2703 return QualType();
2704
2705 QualType FT = Field->getType();
2706
2707 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2708 uint64_t BitWidth = BitWidthAP.getZExtValue();
2709 uint64_t IntSize = getTypeSize(IntTy);
2710 // GCC extension compatibility: if the bit-field size is less than or equal
2711 // to the size of int, it gets promoted no matter what its type is.
2712 // For instance, unsigned long bf : 4 gets promoted to signed int.
2713 if (BitWidth < IntSize)
2714 return IntTy;
2715
2716 if (BitWidth == IntSize)
2717 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2718
2719 // Types bigger than int are not subject to promotions, and therefore act
2720 // like the base type.
2721 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2722 // is ridiculous.
2723 return QualType();
2724}
2725
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002726/// getPromotedIntegerType - Returns the type that Promotable will
2727/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2728/// integer type.
2729QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2730 assert(!Promotable.isNull());
2731 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002732 if (const EnumType *ET = Promotable->getAs<EnumType>())
2733 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002734 if (Promotable->isSignedIntegerType())
2735 return IntTy;
2736 uint64_t PromotableSize = getTypeSize(Promotable);
2737 uint64_t IntSize = getTypeSize(IntTy);
2738 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2739 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2740}
2741
Mike Stump11289f42009-09-09 15:08:12 +00002742/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002743/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002744/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002745int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002746 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2747 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002748 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002749
Chris Lattner76a00cf2008-04-06 22:59:24 +00002750 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2751 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002753 unsigned LHSRank = getIntegerRank(LHSC);
2754 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002755
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002756 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2757 if (LHSRank == RHSRank) return 0;
2758 return LHSRank > RHSRank ? 1 : -1;
2759 }
Mike Stump11289f42009-09-09 15:08:12 +00002760
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002761 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2762 if (LHSUnsigned) {
2763 // If the unsigned [LHS] type is larger, return it.
2764 if (LHSRank >= RHSRank)
2765 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002767 // If the signed type can represent all values of the unsigned type, it
2768 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002769 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002770 return -1;
2771 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002772
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002773 // If the unsigned [RHS] type is larger, return it.
2774 if (RHSRank >= LHSRank)
2775 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002776
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002777 // If the signed type can represent all values of the unsigned type, it
2778 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002779 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002780 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002781}
Anders Carlsson98f07902007-08-17 05:31:46 +00002782
Anders Carlsson6d417272009-11-14 21:45:58 +00002783static RecordDecl *
2784CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2785 SourceLocation L, IdentifierInfo *Id) {
2786 if (Ctx.getLangOptions().CPlusPlus)
2787 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2788 else
2789 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2790}
2791
Mike Stump11289f42009-09-09 15:08:12 +00002792// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002793QualType ASTContext::getCFConstantStringType() {
2794 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002795 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002796 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002797 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002798 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002799
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002800 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002801
Anders Carlsson98f07902007-08-17 05:31:46 +00002802 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002803 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002804 // int flags;
2805 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002806 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002807 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002808 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002809 FieldTypes[3] = LongTy;
2810
Anders Carlsson98f07902007-08-17 05:31:46 +00002811 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002812 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002813 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002814 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002815 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002816 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002817 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002818 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002819 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002820 }
2821
Douglas Gregord5058122010-02-11 01:19:42 +00002822 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002823 }
Mike Stump11289f42009-09-09 15:08:12 +00002824
Anders Carlsson98f07902007-08-17 05:31:46 +00002825 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002826}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002827
Douglas Gregor512b0772009-04-23 22:29:11 +00002828void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002829 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002830 assert(Rec && "Invalid CFConstantStringType");
2831 CFConstantStringTypeDecl = Rec->getDecl();
2832}
2833
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002834// getNSConstantStringType - Return the type used for constant NSStrings.
2835QualType ASTContext::getNSConstantStringType() {
2836 if (!NSConstantStringTypeDecl) {
2837 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002838 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002839 &Idents.get("__builtin_NSString"));
2840 NSConstantStringTypeDecl->startDefinition();
2841
2842 QualType FieldTypes[3];
2843
2844 // const int *isa;
2845 FieldTypes[0] = getPointerType(IntTy.withConst());
2846 // const char *str;
2847 FieldTypes[1] = getPointerType(CharTy.withConst());
2848 // unsigned int length;
2849 FieldTypes[2] = UnsignedIntTy;
2850
2851 // Create fields
2852 for (unsigned i = 0; i < 3; ++i) {
2853 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2854 SourceLocation(), 0,
2855 FieldTypes[i], /*TInfo=*/0,
2856 /*BitWidth=*/0,
2857 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002858 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002859 NSConstantStringTypeDecl->addDecl(Field);
2860 }
2861
2862 NSConstantStringTypeDecl->completeDefinition();
2863 }
2864
2865 return getTagDeclType(NSConstantStringTypeDecl);
2866}
2867
2868void ASTContext::setNSConstantStringType(QualType T) {
2869 const RecordType *Rec = T->getAs<RecordType>();
2870 assert(Rec && "Invalid NSConstantStringType");
2871 NSConstantStringTypeDecl = Rec->getDecl();
2872}
2873
Mike Stump11289f42009-09-09 15:08:12 +00002874QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002875 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00002876 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002877 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002878 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00002879 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002880
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002881 QualType FieldTypes[] = {
2882 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00002883 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002884 getPointerType(UnsignedLongTy),
2885 getConstantArrayType(UnsignedLongTy,
2886 llvm::APInt(32, 5), ArrayType::Normal, 0)
2887 };
Mike Stump11289f42009-09-09 15:08:12 +00002888
Douglas Gregor91f84212008-12-11 16:49:14 +00002889 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002890 FieldDecl *Field = FieldDecl::Create(*this,
2891 ObjCFastEnumerationStateTypeDecl,
2892 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002893 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002894 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002895 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002896 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002897 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002898 }
Mike Stump11289f42009-09-09 15:08:12 +00002899
Douglas Gregord5058122010-02-11 01:19:42 +00002900 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002901 }
Mike Stump11289f42009-09-09 15:08:12 +00002902
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002903 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2904}
2905
Mike Stumpd0153282009-10-20 02:12:22 +00002906QualType ASTContext::getBlockDescriptorType() {
2907 if (BlockDescriptorType)
2908 return getTagDeclType(BlockDescriptorType);
2909
2910 RecordDecl *T;
2911 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002912 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002913 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00002914 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002915
2916 QualType FieldTypes[] = {
2917 UnsignedLongTy,
2918 UnsignedLongTy,
2919 };
2920
2921 const char *FieldNames[] = {
2922 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002923 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00002924 };
2925
2926 for (size_t i = 0; i < 2; ++i) {
2927 FieldDecl *Field = FieldDecl::Create(*this,
2928 T,
2929 SourceLocation(),
2930 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002931 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00002932 /*BitWidth=*/0,
2933 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002934 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00002935 T->addDecl(Field);
2936 }
2937
Douglas Gregord5058122010-02-11 01:19:42 +00002938 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002939
2940 BlockDescriptorType = T;
2941
2942 return getTagDeclType(BlockDescriptorType);
2943}
2944
2945void ASTContext::setBlockDescriptorType(QualType T) {
2946 const RecordType *Rec = T->getAs<RecordType>();
2947 assert(Rec && "Invalid BlockDescriptorType");
2948 BlockDescriptorType = Rec->getDecl();
2949}
2950
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002951QualType ASTContext::getBlockDescriptorExtendedType() {
2952 if (BlockDescriptorExtendedType)
2953 return getTagDeclType(BlockDescriptorExtendedType);
2954
2955 RecordDecl *T;
2956 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002957 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002958 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00002959 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002960
2961 QualType FieldTypes[] = {
2962 UnsignedLongTy,
2963 UnsignedLongTy,
2964 getPointerType(VoidPtrTy),
2965 getPointerType(VoidPtrTy)
2966 };
2967
2968 const char *FieldNames[] = {
2969 "reserved",
2970 "Size",
2971 "CopyFuncPtr",
2972 "DestroyFuncPtr"
2973 };
2974
2975 for (size_t i = 0; i < 4; ++i) {
2976 FieldDecl *Field = FieldDecl::Create(*this,
2977 T,
2978 SourceLocation(),
2979 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002980 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002981 /*BitWidth=*/0,
2982 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002983 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002984 T->addDecl(Field);
2985 }
2986
Douglas Gregord5058122010-02-11 01:19:42 +00002987 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002988
2989 BlockDescriptorExtendedType = T;
2990
2991 return getTagDeclType(BlockDescriptorExtendedType);
2992}
2993
2994void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2995 const RecordType *Rec = T->getAs<RecordType>();
2996 assert(Rec && "Invalid BlockDescriptorType");
2997 BlockDescriptorExtendedType = Rec->getDecl();
2998}
2999
Mike Stump94967902009-10-21 18:16:27 +00003000bool ASTContext::BlockRequiresCopying(QualType Ty) {
3001 if (Ty->isBlockPointerType())
3002 return true;
3003 if (isObjCNSObjectType(Ty))
3004 return true;
3005 if (Ty->isObjCObjectPointerType())
3006 return true;
3007 return false;
3008}
3009
3010QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3011 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003012 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003013 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003014 // unsigned int __flags;
3015 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003016 // void *__copy_helper; // as needed
3017 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003018 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003019 // } *
3020
Mike Stump94967902009-10-21 18:16:27 +00003021 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3022
3023 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003024 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003025 llvm::SmallString<36> Name;
3026 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3027 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003028 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003029 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003030 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003031 T->startDefinition();
3032 QualType Int32Ty = IntTy;
3033 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3034 QualType FieldTypes[] = {
3035 getPointerType(VoidPtrTy),
3036 getPointerType(getTagDeclType(T)),
3037 Int32Ty,
3038 Int32Ty,
3039 getPointerType(VoidPtrTy),
3040 getPointerType(VoidPtrTy),
3041 Ty
3042 };
3043
3044 const char *FieldNames[] = {
3045 "__isa",
3046 "__forwarding",
3047 "__flags",
3048 "__size",
3049 "__copy_helper",
3050 "__destroy_helper",
3051 DeclName,
3052 };
3053
3054 for (size_t i = 0; i < 7; ++i) {
3055 if (!HasCopyAndDispose && i >=4 && i <= 5)
3056 continue;
3057 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3058 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003059 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003060 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003061 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003062 T->addDecl(Field);
3063 }
3064
Douglas Gregord5058122010-02-11 01:19:42 +00003065 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003066
3067 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003068}
3069
3070
3071QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003072 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003073 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003074 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003075 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003076 llvm::SmallString<36> Name;
3077 llvm::raw_svector_ostream(Name) << "__block_literal_"
3078 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003079 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003080 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003081 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003082 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003083 QualType FieldTypes[] = {
3084 getPointerType(VoidPtrTy),
3085 IntTy,
3086 IntTy,
3087 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003088 (BlockHasCopyDispose ?
3089 getPointerType(getBlockDescriptorExtendedType()) :
3090 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003091 };
3092
3093 const char *FieldNames[] = {
3094 "__isa",
3095 "__flags",
3096 "__reserved",
3097 "__FuncPtr",
3098 "__descriptor"
3099 };
3100
3101 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003102 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003103 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003104 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003105 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003106 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003107 T->addDecl(Field);
3108 }
3109
3110 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3111 const Expr *E = BlockDeclRefDecls[i];
3112 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3113 clang::IdentifierInfo *Name = 0;
3114 if (BDRE) {
3115 const ValueDecl *D = BDRE->getDecl();
3116 Name = &Idents.get(D->getName());
3117 }
3118 QualType FieldType = E->getType();
3119
3120 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003121 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3122 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003123
3124 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003125 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003126 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003127 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003128 T->addDecl(Field);
3129 }
3130
Douglas Gregord5058122010-02-11 01:19:42 +00003131 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003132
3133 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003134}
3135
Douglas Gregor512b0772009-04-23 22:29:11 +00003136void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003137 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003138 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3139 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3140}
3141
Anders Carlsson18acd442007-10-29 06:33:42 +00003142// This returns true if a type has been typedefed to BOOL:
3143// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003144static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003145 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003146 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3147 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003148
Anders Carlssond8499822007-10-29 05:01:08 +00003149 return false;
3150}
3151
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003152/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003153/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003154CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003155 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003156
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003157 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003158 if (sz.isPositive() && type->isIntegralType())
3159 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003160 // Treat arrays as pointers, since that's how they're passed in.
3161 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003162 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003163 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003164}
3165
3166static inline
3167std::string charUnitsToString(const CharUnits &CU) {
3168 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003169}
3170
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003171/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003172/// declaration.
3173void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3174 std::string& S) {
3175 const BlockDecl *Decl = Expr->getBlockDecl();
3176 QualType BlockTy =
3177 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3178 // Encode result type.
3179 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3180 // Compute size of all parameters.
3181 // Start with computing size of a pointer in number of bytes.
3182 // FIXME: There might(should) be a better way of doing this computation!
3183 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003184 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3185 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003186 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003187 E = Decl->param_end(); PI != E; ++PI) {
3188 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003189 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003190 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003191 ParmOffset += sz;
3192 }
3193 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003194 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003195 // Block pointer and offset.
3196 S += "@?0";
3197 ParmOffset = PtrSize;
3198
3199 // Argument types.
3200 ParmOffset = PtrSize;
3201 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3202 Decl->param_end(); PI != E; ++PI) {
3203 ParmVarDecl *PVDecl = *PI;
3204 QualType PType = PVDecl->getOriginalType();
3205 if (const ArrayType *AT =
3206 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3207 // Use array's original type only if it has known number of
3208 // elements.
3209 if (!isa<ConstantArrayType>(AT))
3210 PType = PVDecl->getType();
3211 } else if (PType->isFunctionType())
3212 PType = PVDecl->getType();
3213 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003214 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003215 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003216 }
3217}
3218
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003219/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003220/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003221void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003222 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003223 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003224 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003225 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003226 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003227 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003228 // Compute size of all parameters.
3229 // Start with computing size of a pointer in number of bytes.
3230 // FIXME: There might(should) be a better way of doing this computation!
3231 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003232 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003233 // The first two arguments (self and _cmd) are pointers; account for
3234 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003235 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003236 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003237 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003238 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003239 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003240 assert (sz.isPositive() &&
3241 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003242 ParmOffset += sz;
3243 }
Ken Dyck40775002010-01-11 17:06:35 +00003244 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003245 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003246 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003247
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003248 // Argument types.
3249 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003250 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003251 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003252 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003253 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003254 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003255 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3256 // Use array's original type only if it has known number of
3257 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003258 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003259 PType = PVDecl->getType();
3260 } else if (PType->isFunctionType())
3261 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003262 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003263 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003264 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003265 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003266 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003267 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003268 }
3269}
3270
Daniel Dunbar4932b362008-08-28 04:38:10 +00003271/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003272/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003273/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3274/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003275/// Property attributes are stored as a comma-delimited C string. The simple
3276/// attributes readonly and bycopy are encoded as single characters. The
3277/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3278/// encoded as single characters, followed by an identifier. Property types
3279/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003280/// these attributes are defined by the following enumeration:
3281/// @code
3282/// enum PropertyAttributes {
3283/// kPropertyReadOnly = 'R', // property is read-only.
3284/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3285/// kPropertyByref = '&', // property is a reference to the value last assigned
3286/// kPropertyDynamic = 'D', // property is dynamic
3287/// kPropertyGetter = 'G', // followed by getter selector name
3288/// kPropertySetter = 'S', // followed by setter selector name
3289/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3290/// kPropertyType = 't' // followed by old-style type encoding.
3291/// kPropertyWeak = 'W' // 'weak' property
3292/// kPropertyStrong = 'P' // property GC'able
3293/// kPropertyNonAtomic = 'N' // property non-atomic
3294/// };
3295/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003296void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003297 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003298 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003299 // Collect information from the property implementation decl(s).
3300 bool Dynamic = false;
3301 ObjCPropertyImplDecl *SynthesizePID = 0;
3302
3303 // FIXME: Duplicated code due to poor abstraction.
3304 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003305 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003306 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3307 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003308 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003309 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003310 ObjCPropertyImplDecl *PID = *i;
3311 if (PID->getPropertyDecl() == PD) {
3312 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3313 Dynamic = true;
3314 } else {
3315 SynthesizePID = PID;
3316 }
3317 }
3318 }
3319 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003320 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003321 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003322 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003323 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003324 ObjCPropertyImplDecl *PID = *i;
3325 if (PID->getPropertyDecl() == PD) {
3326 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3327 Dynamic = true;
3328 } else {
3329 SynthesizePID = PID;
3330 }
3331 }
Mike Stump11289f42009-09-09 15:08:12 +00003332 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003333 }
3334 }
3335
3336 // FIXME: This is not very efficient.
3337 S = "T";
3338
3339 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003340 // GCC has some special rules regarding encoding of properties which
3341 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003342 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003343 true /* outermost type */,
3344 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003345
3346 if (PD->isReadOnly()) {
3347 S += ",R";
3348 } else {
3349 switch (PD->getSetterKind()) {
3350 case ObjCPropertyDecl::Assign: break;
3351 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003352 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003353 }
3354 }
3355
3356 // It really isn't clear at all what this means, since properties
3357 // are "dynamic by default".
3358 if (Dynamic)
3359 S += ",D";
3360
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003361 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3362 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003363
Daniel Dunbar4932b362008-08-28 04:38:10 +00003364 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3365 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003366 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003367 }
3368
3369 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3370 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003371 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003372 }
3373
3374 if (SynthesizePID) {
3375 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3376 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003377 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003378 }
3379
3380 // FIXME: OBJCGC: weak & strong
3381}
3382
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003383/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003384/// Another legacy compatibility encoding: 32-bit longs are encoded as
3385/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003386/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3387///
3388void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003389 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003390 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003391 if (BT->getKind() == BuiltinType::ULong &&
3392 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003393 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003394 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003395 if (BT->getKind() == BuiltinType::Long &&
3396 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003397 PointeeTy = IntTy;
3398 }
3399 }
3400}
3401
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003402void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003403 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003404 // We follow the behavior of gcc, expanding structures which are
3405 // directly pointed to, and expanding embedded structures. Note that
3406 // these rules are sufficient to prevent recursive encoding of the
3407 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003408 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003409 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003410}
3411
Mike Stump11289f42009-09-09 15:08:12 +00003412static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003413 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003414 const Expr *E = FD->getBitWidth();
3415 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3416 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003417 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003418 S += 'b';
3419 S += llvm::utostr(N);
3420}
3421
Daniel Dunbar07d07852009-10-18 21:17:35 +00003422// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003423void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3424 bool ExpandPointedToStructures,
3425 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003426 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003427 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003428 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003429 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003430 if (FD && FD->isBitField())
3431 return EncodeBitField(this, S, FD);
3432 char encoding;
3433 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003434 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003435 case BuiltinType::Void: encoding = 'v'; break;
3436 case BuiltinType::Bool: encoding = 'B'; break;
3437 case BuiltinType::Char_U:
3438 case BuiltinType::UChar: encoding = 'C'; break;
3439 case BuiltinType::UShort: encoding = 'S'; break;
3440 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003441 case BuiltinType::ULong:
3442 encoding =
3443 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003444 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003445 case BuiltinType::UInt128: encoding = 'T'; break;
3446 case BuiltinType::ULongLong: encoding = 'Q'; break;
3447 case BuiltinType::Char_S:
3448 case BuiltinType::SChar: encoding = 'c'; break;
3449 case BuiltinType::Short: encoding = 's'; break;
3450 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003451 case BuiltinType::Long:
3452 encoding =
3453 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003454 break;
3455 case BuiltinType::LongLong: encoding = 'q'; break;
3456 case BuiltinType::Int128: encoding = 't'; break;
3457 case BuiltinType::Float: encoding = 'f'; break;
3458 case BuiltinType::Double: encoding = 'd'; break;
3459 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Chris Lattnere7cabb92009-07-13 00:10:46 +00003462 S += encoding;
3463 return;
3464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465
John McCall9dd450b2009-09-21 23:43:11 +00003466 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003467 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003468 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003469 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003470 return;
3471 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003472
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003473 // encoding for pointer or r3eference types.
3474 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003475 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003476 if (PT->isObjCSelType()) {
3477 S += ':';
3478 return;
3479 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003480 PointeeTy = PT->getPointeeType();
3481 }
3482 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3483 PointeeTy = RT->getPointeeType();
3484 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003485 bool isReadOnly = false;
3486 // For historical/compatibility reasons, the read-only qualifier of the
3487 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3488 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003489 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003490 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003491 if (OutermostType && T.isConstQualified()) {
3492 isReadOnly = true;
3493 S += 'r';
3494 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003495 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003496 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003497 while (P->getAs<PointerType>())
3498 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003499 if (P.isConstQualified()) {
3500 isReadOnly = true;
3501 S += 'r';
3502 }
3503 }
3504 if (isReadOnly) {
3505 // Another legacy compatibility encoding. Some ObjC qualifier and type
3506 // combinations need to be rearranged.
3507 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003508 if (llvm::StringRef(S).endswith("nr"))
3509 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003510 }
Mike Stump11289f42009-09-09 15:08:12 +00003511
Anders Carlssond8499822007-10-29 05:01:08 +00003512 if (PointeeTy->isCharType()) {
3513 // char pointer types should be encoded as '*' unless it is a
3514 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003515 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003516 S += '*';
3517 return;
3518 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003519 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003520 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3521 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3522 S += '#';
3523 return;
3524 }
3525 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3526 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3527 S += '@';
3528 return;
3529 }
3530 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003531 }
Anders Carlssond8499822007-10-29 05:01:08 +00003532 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003533 getLegacyIntegralTypeEncoding(PointeeTy);
3534
Mike Stump11289f42009-09-09 15:08:12 +00003535 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003536 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003537 return;
3538 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003539
Chris Lattnere7cabb92009-07-13 00:10:46 +00003540 if (const ArrayType *AT =
3541 // Ignore type qualifiers etc.
3542 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003543 if (isa<IncompleteArrayType>(AT)) {
3544 // Incomplete arrays are encoded as a pointer to the array element.
3545 S += '^';
3546
Mike Stump11289f42009-09-09 15:08:12 +00003547 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003548 false, ExpandStructures, FD);
3549 } else {
3550 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003551
Anders Carlssond05f44b2009-02-22 01:38:57 +00003552 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3553 S += llvm::utostr(CAT->getSize().getZExtValue());
3554 else {
3555 //Variable length arrays are encoded as a regular array with 0 elements.
3556 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3557 S += '0';
3558 }
Mike Stump11289f42009-09-09 15:08:12 +00003559
3560 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003561 false, ExpandStructures, FD);
3562 S += ']';
3563 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003564 return;
3565 }
Mike Stump11289f42009-09-09 15:08:12 +00003566
John McCall9dd450b2009-09-21 23:43:11 +00003567 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003568 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003569 return;
3570 }
Mike Stump11289f42009-09-09 15:08:12 +00003571
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003572 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003573 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003574 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003575 // Anonymous structures print as '?'
3576 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3577 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003578 if (ClassTemplateSpecializationDecl *Spec
3579 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3580 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3581 std::string TemplateArgsStr
3582 = TemplateSpecializationType::PrintTemplateArgumentList(
3583 TemplateArgs.getFlatArgumentList(),
3584 TemplateArgs.flat_size(),
3585 (*this).PrintingPolicy);
3586
3587 S += TemplateArgsStr;
3588 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003589 } else {
3590 S += '?';
3591 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003592 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003593 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003594 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3595 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003596 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003597 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003598 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003599 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003600 S += '"';
3601 }
Mike Stump11289f42009-09-09 15:08:12 +00003602
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003603 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003604 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003605 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003606 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003607 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003608 QualType qt = Field->getType();
3609 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003610 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003611 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003612 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003613 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003614 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003615 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003616 return;
3617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
Chris Lattnere7cabb92009-07-13 00:10:46 +00003619 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003620 if (FD && FD->isBitField())
3621 EncodeBitField(this, S, FD);
3622 else
3623 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003624 return;
3625 }
Mike Stump11289f42009-09-09 15:08:12 +00003626
Chris Lattnere7cabb92009-07-13 00:10:46 +00003627 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003628 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003629 return;
3630 }
Mike Stump11289f42009-09-09 15:08:12 +00003631
John McCall8b07ec22010-05-15 11:32:37 +00003632 // Ignore protocol qualifiers when mangling at this level.
3633 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3634 T = OT->getBaseType();
3635
John McCall8ccfcb52009-09-24 19:53:00 +00003636 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003637 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003638 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003639 S += '{';
3640 const IdentifierInfo *II = OI->getIdentifier();
3641 S += II->getName();
3642 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003643 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003644 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003645 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003646 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003647 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003648 RecFields[i]);
3649 else
Mike Stump11289f42009-09-09 15:08:12 +00003650 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003651 FD);
3652 }
3653 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003654 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003655 }
Mike Stump11289f42009-09-09 15:08:12 +00003656
John McCall9dd450b2009-09-21 23:43:11 +00003657 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003658 if (OPT->isObjCIdType()) {
3659 S += '@';
3660 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003661 }
Mike Stump11289f42009-09-09 15:08:12 +00003662
Steve Narofff0c86112009-10-28 22:03:49 +00003663 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3664 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3665 // Since this is a binary compatibility issue, need to consult with runtime
3666 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003667 S += '#';
3668 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003669 }
Mike Stump11289f42009-09-09 15:08:12 +00003670
Chris Lattnere7cabb92009-07-13 00:10:46 +00003671 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003672 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003673 ExpandPointedToStructures,
3674 ExpandStructures, FD);
3675 if (FD || EncodingProperty) {
3676 // Note that we do extended encoding of protocol qualifer list
3677 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003678 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003679 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3680 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003681 S += '<';
3682 S += (*I)->getNameAsString();
3683 S += '>';
3684 }
3685 S += '"';
3686 }
3687 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003688 }
Mike Stump11289f42009-09-09 15:08:12 +00003689
Chris Lattnere7cabb92009-07-13 00:10:46 +00003690 QualType PointeeTy = OPT->getPointeeType();
3691 if (!EncodingProperty &&
3692 isa<TypedefType>(PointeeTy.getTypePtr())) {
3693 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003694 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003695 // {...};
3696 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003697 getObjCEncodingForTypeImpl(PointeeTy, S,
3698 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003699 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003700 return;
3701 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003702
3703 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003704 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003705 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003706 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003707 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3708 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003709 S += '<';
3710 S += (*I)->getNameAsString();
3711 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003712 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003713 S += '"';
3714 }
3715 return;
3716 }
Mike Stump11289f42009-09-09 15:08:12 +00003717
John McCalla9e6e8d2010-05-17 23:56:34 +00003718 // gcc just blithely ignores member pointers.
3719 // TODO: maybe there should be a mangling for these
3720 if (T->getAs<MemberPointerType>())
3721 return;
3722
Chris Lattnere7cabb92009-07-13 00:10:46 +00003723 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003724}
3725
Mike Stump11289f42009-09-09 15:08:12 +00003726void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003727 std::string& S) const {
3728 if (QT & Decl::OBJC_TQ_In)
3729 S += 'n';
3730 if (QT & Decl::OBJC_TQ_Inout)
3731 S += 'N';
3732 if (QT & Decl::OBJC_TQ_Out)
3733 S += 'o';
3734 if (QT & Decl::OBJC_TQ_Bycopy)
3735 S += 'O';
3736 if (QT & Decl::OBJC_TQ_Byref)
3737 S += 'R';
3738 if (QT & Decl::OBJC_TQ_Oneway)
3739 S += 'V';
3740}
3741
Chris Lattnere7cabb92009-07-13 00:10:46 +00003742void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003743 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003744
Anders Carlsson87c149b2007-10-11 01:00:40 +00003745 BuiltinVaListType = T;
3746}
3747
Chris Lattnere7cabb92009-07-13 00:10:46 +00003748void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003749 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003750}
3751
Chris Lattnere7cabb92009-07-13 00:10:46 +00003752void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003753 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003754}
3755
Chris Lattnere7cabb92009-07-13 00:10:46 +00003756void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003757 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003758}
3759
Chris Lattnere7cabb92009-07-13 00:10:46 +00003760void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003761 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003762}
3763
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003764void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003765 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003766 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003767
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003768 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003769}
3770
John McCalld28ae272009-12-02 08:04:21 +00003771/// \brief Retrieve the template name that corresponds to a non-empty
3772/// lookup.
John McCallad371252010-01-20 00:46:10 +00003773TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3774 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003775 unsigned size = End - Begin;
3776 assert(size > 1 && "set is not overloaded!");
3777
3778 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3779 size * sizeof(FunctionTemplateDecl*));
3780 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3781
3782 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003783 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003784 NamedDecl *D = *I;
3785 assert(isa<FunctionTemplateDecl>(D) ||
3786 (isa<UsingShadowDecl>(D) &&
3787 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3788 *Storage++ = D;
3789 }
3790
3791 return TemplateName(OT);
3792}
3793
Douglas Gregordc572a32009-03-30 22:58:21 +00003794/// \brief Retrieve the template name that represents a qualified
3795/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003796TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003797 bool TemplateKeyword,
3798 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003799 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003800 llvm::FoldingSetNodeID ID;
3801 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3802
3803 void *InsertPos = 0;
3804 QualifiedTemplateName *QTN =
3805 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3806 if (!QTN) {
3807 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3808 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3809 }
3810
3811 return TemplateName(QTN);
3812}
3813
3814/// \brief Retrieve the template name that represents a dependent
3815/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003816TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003817 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003818 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003819 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003820
3821 llvm::FoldingSetNodeID ID;
3822 DependentTemplateName::Profile(ID, NNS, Name);
3823
3824 void *InsertPos = 0;
3825 DependentTemplateName *QTN =
3826 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3827
3828 if (QTN)
3829 return TemplateName(QTN);
3830
3831 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3832 if (CanonNNS == NNS) {
3833 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3834 } else {
3835 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3836 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003837 DependentTemplateName *CheckQTN =
3838 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3839 assert(!CheckQTN && "Dependent type name canonicalization broken");
3840 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00003841 }
3842
3843 DependentTemplateNames.InsertNode(QTN, InsertPos);
3844 return TemplateName(QTN);
3845}
3846
Douglas Gregor71395fa2009-11-04 00:56:37 +00003847/// \brief Retrieve the template name that represents a dependent
3848/// template name such as \c MetaFun::template operator+.
3849TemplateName
3850ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3851 OverloadedOperatorKind Operator) {
3852 assert((!NNS || NNS->isDependent()) &&
3853 "Nested name specifier must be dependent");
3854
3855 llvm::FoldingSetNodeID ID;
3856 DependentTemplateName::Profile(ID, NNS, Operator);
3857
3858 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003859 DependentTemplateName *QTN
3860 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00003861
3862 if (QTN)
3863 return TemplateName(QTN);
3864
3865 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3866 if (CanonNNS == NNS) {
3867 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3868 } else {
3869 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3870 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003871
3872 DependentTemplateName *CheckQTN
3873 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3874 assert(!CheckQTN && "Dependent template name canonicalization broken");
3875 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00003876 }
3877
3878 DependentTemplateNames.InsertNode(QTN, InsertPos);
3879 return TemplateName(QTN);
3880}
3881
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003882/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00003883/// TargetInfo, produce the corresponding type. The unsigned @p Type
3884/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00003885CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003886 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00003887 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003888 case TargetInfo::SignedShort: return ShortTy;
3889 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3890 case TargetInfo::SignedInt: return IntTy;
3891 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3892 case TargetInfo::SignedLong: return LongTy;
3893 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3894 case TargetInfo::SignedLongLong: return LongLongTy;
3895 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3896 }
3897
3898 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00003899 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003900}
Ted Kremenek77c51b22008-07-24 23:58:27 +00003901
3902//===----------------------------------------------------------------------===//
3903// Type Predicates.
3904//===----------------------------------------------------------------------===//
3905
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003906/// isObjCNSObjectType - Return true if this is an NSObject object using
3907/// NSObject attribute on a c-style pointer type.
3908/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00003909/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003910///
3911bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3912 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3913 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003914 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003915 return true;
3916 }
Mike Stump11289f42009-09-09 15:08:12 +00003917 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003918}
3919
Fariborz Jahanian96207692009-02-18 21:49:28 +00003920/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3921/// garbage collection attribute.
3922///
John McCall8ccfcb52009-09-24 19:53:00 +00003923Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3924 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003925 if (getLangOptions().ObjC1 &&
3926 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00003927 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00003928 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00003929 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003930 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00003931 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00003932 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003933 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003934 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003935 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003936 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00003937 // Non-pointers have none gc'able attribute regardless of the attribute
3938 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00003939 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003940 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003941 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00003942 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003943}
3944
Chris Lattner49af6a42008-04-07 06:51:04 +00003945//===----------------------------------------------------------------------===//
3946// Type Compatibility Testing
3947//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00003948
Mike Stump11289f42009-09-09 15:08:12 +00003949/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00003950/// compatible.
3951static bool areCompatVectorTypes(const VectorType *LHS,
3952 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00003953 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00003954 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00003955 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00003956}
3957
Steve Naroff8e6aee52009-07-23 01:01:38 +00003958//===----------------------------------------------------------------------===//
3959// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3960//===----------------------------------------------------------------------===//
3961
3962/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3963/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00003964bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3965 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00003966 if (lProto == rProto)
3967 return true;
3968 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3969 E = rProto->protocol_end(); PI != E; ++PI)
3970 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3971 return true;
3972 return false;
3973}
3974
Steve Naroff8e6aee52009-07-23 01:01:38 +00003975/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3976/// return true if lhs's protocols conform to rhs's protocol; false
3977/// otherwise.
3978bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3979 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3980 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3981 return false;
3982}
3983
3984/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3985/// ObjCQualifiedIDType.
3986bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3987 bool compare) {
3988 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00003989 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00003990 lhs->isObjCIdType() || lhs->isObjCClassType())
3991 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003992 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00003993 rhs->isObjCIdType() || rhs->isObjCClassType())
3994 return true;
3995
3996 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00003997 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00003998
Steve Naroff8e6aee52009-07-23 01:01:38 +00003999 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004000
Steve Naroff8e6aee52009-07-23 01:01:38 +00004001 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004002 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004003 // make sure we check the class hierarchy.
4004 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4005 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4006 E = lhsQID->qual_end(); I != E; ++I) {
4007 // when comparing an id<P> on lhs with a static type on rhs,
4008 // see if static class implements all of id's protocols, directly or
4009 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004010 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004011 return false;
4012 }
4013 }
4014 // If there are no qualifiers and no interface, we have an 'id'.
4015 return true;
4016 }
Mike Stump11289f42009-09-09 15:08:12 +00004017 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004018 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4019 E = lhsQID->qual_end(); I != E; ++I) {
4020 ObjCProtocolDecl *lhsProto = *I;
4021 bool match = false;
4022
4023 // when comparing an id<P> on lhs with a static type on rhs,
4024 // see if static class implements all of id's protocols, directly or
4025 // through its super class and categories.
4026 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4027 E = rhsOPT->qual_end(); J != E; ++J) {
4028 ObjCProtocolDecl *rhsProto = *J;
4029 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4030 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4031 match = true;
4032 break;
4033 }
4034 }
Mike Stump11289f42009-09-09 15:08:12 +00004035 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004036 // make sure we check the class hierarchy.
4037 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4038 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4039 E = lhsQID->qual_end(); I != E; ++I) {
4040 // when comparing an id<P> on lhs with a static type on rhs,
4041 // see if static class implements all of id's protocols, directly or
4042 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004043 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004044 match = true;
4045 break;
4046 }
4047 }
4048 }
4049 if (!match)
4050 return false;
4051 }
Mike Stump11289f42009-09-09 15:08:12 +00004052
Steve Naroff8e6aee52009-07-23 01:01:38 +00004053 return true;
4054 }
Mike Stump11289f42009-09-09 15:08:12 +00004055
Steve Naroff8e6aee52009-07-23 01:01:38 +00004056 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4057 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4058
Mike Stump11289f42009-09-09 15:08:12 +00004059 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004060 lhs->getAsObjCInterfacePointerType()) {
4061 if (lhsOPT->qual_empty()) {
4062 bool match = false;
4063 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4064 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4065 E = rhsQID->qual_end(); I != E; ++I) {
4066 // when comparing an id<P> on lhs with a static type on rhs,
4067 // see if static class implements all of id's protocols, directly or
4068 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004069 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004070 match = true;
4071 break;
4072 }
4073 }
4074 if (!match)
4075 return false;
4076 }
4077 return true;
4078 }
Mike Stump11289f42009-09-09 15:08:12 +00004079 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004080 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4081 E = lhsOPT->qual_end(); I != E; ++I) {
4082 ObjCProtocolDecl *lhsProto = *I;
4083 bool match = false;
4084
4085 // when comparing an id<P> on lhs with a static type on rhs,
4086 // see if static class implements all of id's protocols, directly or
4087 // through its super class and categories.
4088 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4089 E = rhsQID->qual_end(); J != E; ++J) {
4090 ObjCProtocolDecl *rhsProto = *J;
4091 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4092 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4093 match = true;
4094 break;
4095 }
4096 }
4097 if (!match)
4098 return false;
4099 }
4100 return true;
4101 }
4102 return false;
4103}
4104
Eli Friedman47f77112008-08-22 00:56:42 +00004105/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004106/// compatible for assignment from RHS to LHS. This handles validation of any
4107/// protocol qualifiers on the LHS or RHS.
4108///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004109bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4110 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004111 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4112 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4113
Steve Naroff1329fa02009-07-15 18:40:39 +00004114 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004115 if (LHS->isObjCUnqualifiedIdOrClass() ||
4116 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004117 return true;
4118
John McCall8b07ec22010-05-15 11:32:37 +00004119 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004120 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4121 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004122 false);
4123
John McCall8b07ec22010-05-15 11:32:37 +00004124 // If we have 2 user-defined types, fall into that path.
4125 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004126 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004127
Steve Naroff8e6aee52009-07-23 01:01:38 +00004128 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004129}
4130
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004131/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4132/// for providing type-safty for objective-c pointers used to pass/return
4133/// arguments in block literals. When passed as arguments, passing 'A*' where
4134/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4135/// not OK. For the return type, the opposite is not OK.
4136bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4137 const ObjCObjectPointerType *LHSOPT,
4138 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004139 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004140 return true;
4141
4142 if (LHSOPT->isObjCBuiltinType()) {
4143 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4144 }
4145
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004146 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004147 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4148 QualType(RHSOPT,0),
4149 false);
4150
4151 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4152 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4153 if (LHS && RHS) { // We have 2 user-defined types.
4154 if (LHS != RHS) {
4155 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4156 return false;
4157 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4158 return true;
4159 }
4160 else
4161 return true;
4162 }
4163 return false;
4164}
4165
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004166/// getIntersectionOfProtocols - This routine finds the intersection of set
4167/// of protocols inherited from two distinct objective-c pointer objects.
4168/// It is used to build composite qualifier list of the composite type of
4169/// the conditional expression involving two objective-c pointer objects.
4170static
4171void getIntersectionOfProtocols(ASTContext &Context,
4172 const ObjCObjectPointerType *LHSOPT,
4173 const ObjCObjectPointerType *RHSOPT,
4174 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4175
John McCall8b07ec22010-05-15 11:32:37 +00004176 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4177 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4178 assert(LHS->getInterface() && "LHS must have an interface base");
4179 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004180
4181 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4182 unsigned LHSNumProtocols = LHS->getNumProtocols();
4183 if (LHSNumProtocols > 0)
4184 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4185 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004186 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004187 Context.CollectInheritedProtocols(LHS->getInterface(),
4188 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004189 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4190 LHSInheritedProtocols.end());
4191 }
4192
4193 unsigned RHSNumProtocols = RHS->getNumProtocols();
4194 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004195 ObjCProtocolDecl **RHSProtocols =
4196 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004197 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4198 if (InheritedProtocolSet.count(RHSProtocols[i]))
4199 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4200 }
4201 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004202 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004203 Context.CollectInheritedProtocols(RHS->getInterface(),
4204 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004205 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4206 RHSInheritedProtocols.begin(),
4207 E = RHSInheritedProtocols.end(); I != E; ++I)
4208 if (InheritedProtocolSet.count((*I)))
4209 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004210 }
4211}
4212
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004213/// areCommonBaseCompatible - Returns common base class of the two classes if
4214/// one found. Note that this is O'2 algorithm. But it will be called as the
4215/// last type comparison in a ?-exp of ObjC pointer types before a
4216/// warning is issued. So, its invokation is extremely rare.
4217QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004218 const ObjCObjectPointerType *Lptr,
4219 const ObjCObjectPointerType *Rptr) {
4220 const ObjCObjectType *LHS = Lptr->getObjectType();
4221 const ObjCObjectType *RHS = Rptr->getObjectType();
4222 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4223 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4224 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004225 return QualType();
4226
John McCall8b07ec22010-05-15 11:32:37 +00004227 while ((LDecl = LDecl->getSuperClass())) {
4228 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004229 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004230 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4231 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4232
4233 QualType Result = QualType(LHS, 0);
4234 if (!Protocols.empty())
4235 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4236 Result = getObjCObjectPointerType(Result);
4237 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004238 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004239 }
4240
4241 return QualType();
4242}
4243
John McCall8b07ec22010-05-15 11:32:37 +00004244bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4245 const ObjCObjectType *RHS) {
4246 assert(LHS->getInterface() && "LHS is not an interface type");
4247 assert(RHS->getInterface() && "RHS is not an interface type");
4248
Chris Lattner49af6a42008-04-07 06:51:04 +00004249 // Verify that the base decls are compatible: the RHS must be a subclass of
4250 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004251 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004252 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004253
Chris Lattner49af6a42008-04-07 06:51:04 +00004254 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4255 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004256 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004257 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004258
Chris Lattner49af6a42008-04-07 06:51:04 +00004259 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4260 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004261 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004262 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCall8b07ec22010-05-15 11:32:37 +00004264 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4265 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004266 LHSPI != LHSPE; LHSPI++) {
4267 bool RHSImplementsProtocol = false;
4268
4269 // If the RHS doesn't implement the protocol on the left, the types
4270 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004271 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4272 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004273 RHSPI != RHSPE; RHSPI++) {
4274 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004275 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004276 break;
4277 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004278 }
4279 // FIXME: For better diagnostics, consider passing back the protocol name.
4280 if (!RHSImplementsProtocol)
4281 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004282 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004283 // The RHS implements all protocols listed on the LHS.
4284 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004285}
4286
Steve Naroffb7605152009-02-12 17:52:19 +00004287bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4288 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004289 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4290 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004291
Steve Naroff7cae42b2009-07-10 23:34:53 +00004292 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004293 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004294
4295 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4296 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004297}
4298
Mike Stump11289f42009-09-09 15:08:12 +00004299/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004300/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004301/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004302/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004303bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004304 if (getLangOptions().CPlusPlus)
4305 return hasSameType(LHS, RHS);
4306
Eli Friedman47f77112008-08-22 00:56:42 +00004307 return !mergeTypes(LHS, RHS).isNull();
4308}
4309
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004310bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4311 return !mergeTypes(LHS, RHS, true).isNull();
4312}
4313
4314QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4315 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004316 const FunctionType *lbase = lhs->getAs<FunctionType>();
4317 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004318 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4319 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004320 bool allLTypes = true;
4321 bool allRTypes = true;
4322
4323 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004324 QualType retType;
4325 if (OfBlockPointer)
4326 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4327 else
4328 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004329 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004330 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004331 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004332 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004333 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004334 // FIXME: double check this
4335 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4336 // rbase->getRegParmAttr() != 0 &&
4337 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004338 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4339 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004340 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4341 lbaseInfo.getRegParm();
4342 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4343 if (NoReturn != lbaseInfo.getNoReturn() ||
4344 RegParm != lbaseInfo.getRegParm())
4345 allLTypes = false;
4346 if (NoReturn != rbaseInfo.getNoReturn() ||
4347 RegParm != rbaseInfo.getRegParm())
4348 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004349 CallingConv lcc = lbaseInfo.getCC();
4350 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004351 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004352 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004353 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004354
Eli Friedman47f77112008-08-22 00:56:42 +00004355 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004356 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4357 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004358 unsigned lproto_nargs = lproto->getNumArgs();
4359 unsigned rproto_nargs = rproto->getNumArgs();
4360
4361 // Compatible functions must have the same number of arguments
4362 if (lproto_nargs != rproto_nargs)
4363 return QualType();
4364
4365 // Variadic and non-variadic functions aren't compatible
4366 if (lproto->isVariadic() != rproto->isVariadic())
4367 return QualType();
4368
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004369 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4370 return QualType();
4371
Eli Friedman47f77112008-08-22 00:56:42 +00004372 // Check argument compatibility
4373 llvm::SmallVector<QualType, 10> types;
4374 for (unsigned i = 0; i < lproto_nargs; i++) {
4375 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4376 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004377 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004378 if (argtype.isNull()) return QualType();
4379 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004380 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4381 allLTypes = false;
4382 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4383 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004384 }
4385 if (allLTypes) return lhs;
4386 if (allRTypes) return rhs;
4387 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004388 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004389 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004390 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004391 }
4392
4393 if (lproto) allRTypes = false;
4394 if (rproto) allLTypes = false;
4395
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004396 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004397 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004398 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004399 if (proto->isVariadic()) return QualType();
4400 // Check that the types are compatible with the types that
4401 // would result from default argument promotions (C99 6.7.5.3p15).
4402 // The only types actually affected are promotable integer
4403 // types and floats, which would be passed as a different
4404 // type depending on whether the prototype is visible.
4405 unsigned proto_nargs = proto->getNumArgs();
4406 for (unsigned i = 0; i < proto_nargs; ++i) {
4407 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004408
4409 // Look at the promotion type of enum types, since that is the type used
4410 // to pass enum values.
4411 if (const EnumType *Enum = argTy->getAs<EnumType>())
4412 argTy = Enum->getDecl()->getPromotionType();
4413
Eli Friedman47f77112008-08-22 00:56:42 +00004414 if (argTy->isPromotableIntegerType() ||
4415 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4416 return QualType();
4417 }
4418
4419 if (allLTypes) return lhs;
4420 if (allRTypes) return rhs;
4421 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004422 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004423 proto->getTypeQuals(),
4424 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004425 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004426 }
4427
4428 if (allLTypes) return lhs;
4429 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004430 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004431 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004432}
4433
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004434QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4435 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004436 // C++ [expr]: If an expression initially has the type "reference to T", the
4437 // type is adjusted to "T" prior to any further analysis, the expression
4438 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004439 // expression is an lvalue unless the reference is an rvalue reference and
4440 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004441 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4442 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4443
Eli Friedman47f77112008-08-22 00:56:42 +00004444 QualType LHSCan = getCanonicalType(LHS),
4445 RHSCan = getCanonicalType(RHS);
4446
4447 // If two types are identical, they are compatible.
4448 if (LHSCan == RHSCan)
4449 return LHS;
4450
John McCall8ccfcb52009-09-24 19:53:00 +00004451 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004452 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4453 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004454 if (LQuals != RQuals) {
4455 // If any of these qualifiers are different, we have a type
4456 // mismatch.
4457 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4458 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4459 return QualType();
4460
4461 // Exactly one GC qualifier difference is allowed: __strong is
4462 // okay if the other type has no GC qualifier but is an Objective
4463 // C object pointer (i.e. implicitly strong by default). We fix
4464 // this by pretending that the unqualified type was actually
4465 // qualified __strong.
4466 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4467 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4468 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4469
4470 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4471 return QualType();
4472
4473 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4474 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4475 }
4476 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4477 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4478 }
Eli Friedman47f77112008-08-22 00:56:42 +00004479 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004480 }
4481
4482 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004483
Eli Friedmandcca6332009-06-01 01:22:52 +00004484 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4485 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004486
Chris Lattnerfd652912008-01-14 05:45:46 +00004487 // We want to consider the two function types to be the same for these
4488 // comparisons, just force one to the other.
4489 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4490 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004491
4492 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004493 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4494 LHSClass = Type::ConstantArray;
4495 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4496 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004497
John McCall8b07ec22010-05-15 11:32:37 +00004498 // ObjCInterfaces are just specialized ObjCObjects.
4499 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4500 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4501
Nate Begemance4d7fc2008-04-18 23:10:10 +00004502 // Canonicalize ExtVector -> Vector.
4503 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4504 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004505
Chris Lattner95554662008-04-07 05:43:21 +00004506 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004507 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004508 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004509 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004510 // Compatibility is based on the underlying type, not the promotion
4511 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004512 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004513 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4514 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004515 }
John McCall9dd450b2009-09-21 23:43:11 +00004516 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004517 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4518 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004519 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004520
Eli Friedman47f77112008-08-22 00:56:42 +00004521 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004522 }
Eli Friedman47f77112008-08-22 00:56:42 +00004523
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004524 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004525 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004526#define TYPE(Class, Base)
4527#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004528#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004529#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4530#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4531#include "clang/AST/TypeNodes.def"
4532 assert(false && "Non-canonical and dependent types shouldn't get here");
4533 return QualType();
4534
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004535 case Type::LValueReference:
4536 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004537 case Type::MemberPointer:
4538 assert(false && "C++ should never be in mergeTypes");
4539 return QualType();
4540
John McCall8b07ec22010-05-15 11:32:37 +00004541 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004542 case Type::IncompleteArray:
4543 case Type::VariableArray:
4544 case Type::FunctionProto:
4545 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004546 assert(false && "Types are eliminated above");
4547 return QualType();
4548
Chris Lattnerfd652912008-01-14 05:45:46 +00004549 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004550 {
4551 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004552 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4553 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004554 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4555 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004556 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004557 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004558 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004559 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004560 return getPointerType(ResultType);
4561 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004562 case Type::BlockPointer:
4563 {
4564 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004565 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4566 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004567 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004568 if (ResultType.isNull()) return QualType();
4569 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4570 return LHS;
4571 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4572 return RHS;
4573 return getBlockPointerType(ResultType);
4574 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004575 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004576 {
4577 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4578 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4579 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4580 return QualType();
4581
4582 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4583 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4584 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4585 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004586 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4587 return LHS;
4588 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4589 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004590 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4591 ArrayType::ArraySizeModifier(), 0);
4592 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4593 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004594 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4595 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004596 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4597 return LHS;
4598 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4599 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004600 if (LVAT) {
4601 // FIXME: This isn't correct! But tricky to implement because
4602 // the array's size has to be the size of LHS, but the type
4603 // has to be different.
4604 return LHS;
4605 }
4606 if (RVAT) {
4607 // FIXME: This isn't correct! But tricky to implement because
4608 // the array's size has to be the size of RHS, but the type
4609 // has to be different.
4610 return RHS;
4611 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004612 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4613 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004614 return getIncompleteArrayType(ResultType,
4615 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004616 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004617 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004618 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004619 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004620 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004621 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004622 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004623 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004624 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004625 case Type::Complex:
4626 // Distinct complex types are incompatible.
4627 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004628 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004629 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004630 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4631 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004632 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004633 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004634 case Type::ObjCObject: {
4635 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004636 // FIXME: This should be type compatibility, e.g. whether
4637 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004638 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4639 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4640 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004641 return LHS;
4642
Eli Friedman47f77112008-08-22 00:56:42 +00004643 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004644 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004645 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004646 if (OfBlockPointer) {
4647 if (canAssignObjCInterfacesInBlockPointer(
4648 LHS->getAs<ObjCObjectPointerType>(),
4649 RHS->getAs<ObjCObjectPointerType>()))
4650 return LHS;
4651 return QualType();
4652 }
John McCall9dd450b2009-09-21 23:43:11 +00004653 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4654 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004655 return LHS;
4656
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004657 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004658 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004659 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004660
4661 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004662}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004663
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004664/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4665/// 'RHS' attributes and returns the merged version; including for function
4666/// return types.
4667QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4668 QualType LHSCan = getCanonicalType(LHS),
4669 RHSCan = getCanonicalType(RHS);
4670 // If two types are identical, they are compatible.
4671 if (LHSCan == RHSCan)
4672 return LHS;
4673 if (RHSCan->isFunctionType()) {
4674 if (!LHSCan->isFunctionType())
4675 return QualType();
4676 QualType OldReturnType =
4677 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4678 QualType NewReturnType =
4679 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4680 QualType ResReturnType =
4681 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4682 if (ResReturnType.isNull())
4683 return QualType();
4684 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4685 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4686 // In either case, use OldReturnType to build the new function type.
4687 const FunctionType *F = LHS->getAs<FunctionType>();
4688 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4689 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4690 QualType ResultType
4691 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4692 FPT->getNumArgs(), FPT->isVariadic(),
4693 FPT->getTypeQuals(),
4694 FPT->hasExceptionSpec(),
4695 FPT->hasAnyExceptionSpec(),
4696 FPT->getNumExceptions(),
4697 FPT->exception_begin(),
4698 Info);
4699 return ResultType;
4700 }
4701 }
4702 return QualType();
4703 }
4704
4705 // If the qualifiers are different, the types can still be merged.
4706 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4707 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4708 if (LQuals != RQuals) {
4709 // If any of these qualifiers are different, we have a type mismatch.
4710 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4711 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4712 return QualType();
4713
4714 // Exactly one GC qualifier difference is allowed: __strong is
4715 // okay if the other type has no GC qualifier but is an Objective
4716 // C object pointer (i.e. implicitly strong by default). We fix
4717 // this by pretending that the unqualified type was actually
4718 // qualified __strong.
4719 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4720 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4721 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4722
4723 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4724 return QualType();
4725
4726 if (GC_L == Qualifiers::Strong)
4727 return LHS;
4728 if (GC_R == Qualifiers::Strong)
4729 return RHS;
4730 return QualType();
4731 }
4732
4733 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4734 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4735 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4736 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4737 if (ResQT == LHSBaseQT)
4738 return LHS;
4739 if (ResQT == RHSBaseQT)
4740 return RHS;
4741 }
4742 return QualType();
4743}
4744
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004745//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004746// Integer Predicates
4747//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004748
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004749unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004750 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004751 return 1;
John McCall56774992009-12-09 09:09:27 +00004752 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004753 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004754 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004755 return (unsigned)getTypeSize(T);
4756}
4757
4758QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4759 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004760
4761 // Turn <4 x signed int> -> <4 x unsigned int>
4762 if (const VectorType *VTy = T->getAs<VectorType>())
4763 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004764 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004765
4766 // For enums, we return the unsigned version of the base type.
4767 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004768 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004769
4770 const BuiltinType *BTy = T->getAs<BuiltinType>();
4771 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004772 switch (BTy->getKind()) {
4773 case BuiltinType::Char_S:
4774 case BuiltinType::SChar:
4775 return UnsignedCharTy;
4776 case BuiltinType::Short:
4777 return UnsignedShortTy;
4778 case BuiltinType::Int:
4779 return UnsignedIntTy;
4780 case BuiltinType::Long:
4781 return UnsignedLongTy;
4782 case BuiltinType::LongLong:
4783 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004784 case BuiltinType::Int128:
4785 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004786 default:
4787 assert(0 && "Unexpected signed integer type");
4788 return QualType();
4789 }
4790}
4791
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004792ExternalASTSource::~ExternalASTSource() { }
4793
4794void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004795
4796
4797//===----------------------------------------------------------------------===//
4798// Builtin Type Computation
4799//===----------------------------------------------------------------------===//
4800
4801/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4802/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004803static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004804 ASTContext::GetBuiltinTypeError &Error,
4805 bool AllowTypeModifiers = true) {
4806 // Modifiers.
4807 int HowLong = 0;
4808 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004809
Chris Lattnerecd79c62009-06-14 00:45:47 +00004810 // Read the modifiers first.
4811 bool Done = false;
4812 while (!Done) {
4813 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004814 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004815 case 'S':
4816 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4817 assert(!Signed && "Can't use 'S' modifier multiple times!");
4818 Signed = true;
4819 break;
4820 case 'U':
4821 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4822 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4823 Unsigned = true;
4824 break;
4825 case 'L':
4826 assert(HowLong <= 2 && "Can't have LLLL modifier");
4827 ++HowLong;
4828 break;
4829 }
4830 }
4831
4832 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004833
Chris Lattnerecd79c62009-06-14 00:45:47 +00004834 // Read the base type.
4835 switch (*Str++) {
4836 default: assert(0 && "Unknown builtin type letter!");
4837 case 'v':
4838 assert(HowLong == 0 && !Signed && !Unsigned &&
4839 "Bad modifiers used with 'v'!");
4840 Type = Context.VoidTy;
4841 break;
4842 case 'f':
4843 assert(HowLong == 0 && !Signed && !Unsigned &&
4844 "Bad modifiers used with 'f'!");
4845 Type = Context.FloatTy;
4846 break;
4847 case 'd':
4848 assert(HowLong < 2 && !Signed && !Unsigned &&
4849 "Bad modifiers used with 'd'!");
4850 if (HowLong)
4851 Type = Context.LongDoubleTy;
4852 else
4853 Type = Context.DoubleTy;
4854 break;
4855 case 's':
4856 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4857 if (Unsigned)
4858 Type = Context.UnsignedShortTy;
4859 else
4860 Type = Context.ShortTy;
4861 break;
4862 case 'i':
4863 if (HowLong == 3)
4864 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4865 else if (HowLong == 2)
4866 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4867 else if (HowLong == 1)
4868 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4869 else
4870 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4871 break;
4872 case 'c':
4873 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4874 if (Signed)
4875 Type = Context.SignedCharTy;
4876 else if (Unsigned)
4877 Type = Context.UnsignedCharTy;
4878 else
4879 Type = Context.CharTy;
4880 break;
4881 case 'b': // boolean
4882 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4883 Type = Context.BoolTy;
4884 break;
4885 case 'z': // size_t.
4886 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4887 Type = Context.getSizeType();
4888 break;
4889 case 'F':
4890 Type = Context.getCFConstantStringType();
4891 break;
4892 case 'a':
4893 Type = Context.getBuiltinVaListType();
4894 assert(!Type.isNull() && "builtin va list type not initialized!");
4895 break;
4896 case 'A':
4897 // This is a "reference" to a va_list; however, what exactly
4898 // this means depends on how va_list is defined. There are two
4899 // different kinds of va_list: ones passed by value, and ones
4900 // passed by reference. An example of a by-value va_list is
4901 // x86, where va_list is a char*. An example of by-ref va_list
4902 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4903 // we want this argument to be a char*&; for x86-64, we want
4904 // it to be a __va_list_tag*.
4905 Type = Context.getBuiltinVaListType();
4906 assert(!Type.isNull() && "builtin va list type not initialized!");
4907 if (Type->isArrayType()) {
4908 Type = Context.getArrayDecayedType(Type);
4909 } else {
4910 Type = Context.getLValueReferenceType(Type);
4911 }
4912 break;
4913 case 'V': {
4914 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004915 unsigned NumElements = strtoul(Str, &End, 10);
4916 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004917
Chris Lattnerecd79c62009-06-14 00:45:47 +00004918 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004919
Chris Lattnerecd79c62009-06-14 00:45:47 +00004920 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004921 // FIXME: Don't know what to do about AltiVec.
4922 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004923 break;
4924 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004925 case 'X': {
4926 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4927 Type = Context.getComplexType(ElementType);
4928 break;
4929 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004930 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004931 Type = Context.getFILEType();
4932 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004933 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004934 return QualType();
4935 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004936 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004937 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004938 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004939 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004940 else
4941 Type = Context.getjmp_bufType();
4942
Mike Stump2adb4da2009-07-28 23:47:15 +00004943 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004944 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004945 return QualType();
4946 }
4947 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004948 }
Mike Stump11289f42009-09-09 15:08:12 +00004949
Chris Lattnerecd79c62009-06-14 00:45:47 +00004950 if (!AllowTypeModifiers)
4951 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004952
Chris Lattnerecd79c62009-06-14 00:45:47 +00004953 Done = false;
4954 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004955 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004956 default: Done = true; --Str; break;
4957 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004958 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004959 {
4960 // Both pointers and references can have their pointee types
4961 // qualified with an address space.
4962 char *End;
4963 unsigned AddrSpace = strtoul(Str, &End, 10);
4964 if (End != Str && AddrSpace != 0) {
4965 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4966 Str = End;
4967 }
4968 }
4969 if (c == '*')
4970 Type = Context.getPointerType(Type);
4971 else
4972 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004973 break;
4974 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4975 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00004976 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00004977 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00004978 case 'D':
4979 Type = Context.getVolatileType(Type);
4980 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004981 }
4982 }
Mike Stump11289f42009-09-09 15:08:12 +00004983
Chris Lattnerecd79c62009-06-14 00:45:47 +00004984 return Type;
4985}
4986
4987/// GetBuiltinType - Return the type for the specified builtin.
4988QualType ASTContext::GetBuiltinType(unsigned id,
4989 GetBuiltinTypeError &Error) {
4990 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00004991
Chris Lattnerecd79c62009-06-14 00:45:47 +00004992 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004993
Chris Lattnerecd79c62009-06-14 00:45:47 +00004994 Error = GE_None;
4995 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4996 if (Error != GE_None)
4997 return QualType();
4998 while (TypeStr[0] && TypeStr[0] != '.') {
4999 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5000 if (Error != GE_None)
5001 return QualType();
5002
5003 // Do array -> pointer decay. The builtin should use the decayed type.
5004 if (Ty->isArrayType())
5005 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005006
Chris Lattnerecd79c62009-06-14 00:45:47 +00005007 ArgTypes.push_back(Ty);
5008 }
5009
5010 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5011 "'.' should only occur at end of builtin type list!");
5012
5013 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5014 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5015 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005016
5017 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005018 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005019 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005020 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005021}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005022
5023QualType
5024ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5025 // Perform the usual unary conversions. We do this early so that
5026 // integral promotions to "int" can allow us to exit early, in the
5027 // lhs == rhs check. Also, for conversion purposes, we ignore any
5028 // qualifiers. For example, "const float" and "float" are
5029 // equivalent.
5030 if (lhs->isPromotableIntegerType())
5031 lhs = getPromotedIntegerType(lhs);
5032 else
5033 lhs = lhs.getUnqualifiedType();
5034 if (rhs->isPromotableIntegerType())
5035 rhs = getPromotedIntegerType(rhs);
5036 else
5037 rhs = rhs.getUnqualifiedType();
5038
5039 // If both types are identical, no conversion is needed.
5040 if (lhs == rhs)
5041 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005042
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005043 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5044 // The caller can deal with this (e.g. pointer + int).
5045 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5046 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005047
5048 // At this point, we have two different arithmetic types.
5049
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005050 // Handle complex types first (C99 6.3.1.8p1).
5051 if (lhs->isComplexType() || rhs->isComplexType()) {
5052 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005053 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005054 // convert the rhs to the lhs complex type.
5055 return lhs;
5056 }
Mike Stump11289f42009-09-09 15:08:12 +00005057 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005058 // convert the lhs to the rhs complex type.
5059 return rhs;
5060 }
5061 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005062 // When both operands are complex, the shorter operand is converted to the
5063 // type of the longer, and that is the type of the result. This corresponds
5064 // to what is done when combining two real floating-point operands.
5065 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005066 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005067 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005068 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005069 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005070 // "double _Complex" is promoted to "long double _Complex".
5071 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005072
5073 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005074 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005075 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005076 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005077 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005078 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5079 // domains match. This is a requirement for our implementation, C99
5080 // does not require this promotion.
5081 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5082 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5083 return rhs;
5084 } else { // handle "_Complex double, double".
5085 return lhs;
5086 }
5087 }
5088 return lhs; // The domain/size match exactly.
5089 }
5090 // Now handle "real" floating types (i.e. float, double, long double).
5091 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5092 // if we have an integer operand, the result is the real floating type.
5093 if (rhs->isIntegerType()) {
5094 // convert rhs to the lhs floating point type.
5095 return lhs;
5096 }
5097 if (rhs->isComplexIntegerType()) {
5098 // convert rhs to the complex floating point type.
5099 return getComplexType(lhs);
5100 }
5101 if (lhs->isIntegerType()) {
5102 // convert lhs to the rhs floating point type.
5103 return rhs;
5104 }
Mike Stump11289f42009-09-09 15:08:12 +00005105 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005106 // convert lhs to the complex floating point type.
5107 return getComplexType(rhs);
5108 }
5109 // We have two real floating types, float/complex combos were handled above.
5110 // Convert the smaller operand to the bigger result.
5111 int result = getFloatingTypeOrder(lhs, rhs);
5112 if (result > 0) // convert the rhs
5113 return lhs;
5114 assert(result < 0 && "illegal float comparison");
5115 return rhs; // convert the lhs
5116 }
5117 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5118 // Handle GCC complex int extension.
5119 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5120 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5121
5122 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005123 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005124 rhsComplexInt->getElementType()) >= 0)
5125 return lhs; // convert the rhs
5126 return rhs;
5127 } else if (lhsComplexInt && rhs->isIntegerType()) {
5128 // convert the rhs to the lhs complex type.
5129 return lhs;
5130 } else if (rhsComplexInt && lhs->isIntegerType()) {
5131 // convert the lhs to the rhs complex type.
5132 return rhs;
5133 }
5134 }
5135 // Finally, we have two differing integer types.
5136 // The rules for this case are in C99 6.3.1.8
5137 int compare = getIntegerTypeOrder(lhs, rhs);
5138 bool lhsSigned = lhs->isSignedIntegerType(),
5139 rhsSigned = rhs->isSignedIntegerType();
5140 QualType destType;
5141 if (lhsSigned == rhsSigned) {
5142 // Same signedness; use the higher-ranked type
5143 destType = compare >= 0 ? lhs : rhs;
5144 } else if (compare != (lhsSigned ? 1 : -1)) {
5145 // The unsigned type has greater than or equal rank to the
5146 // signed type, so use the unsigned type
5147 destType = lhsSigned ? rhs : lhs;
5148 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5149 // The two types are different widths; if we are here, that
5150 // means the signed type is larger than the unsigned type, so
5151 // use the signed type.
5152 destType = lhsSigned ? lhs : rhs;
5153 } else {
5154 // The signed type is higher-ranked than the unsigned type,
5155 // but isn't actually any bigger (like unsigned int and long
5156 // on most 32-bit systems). Use the unsigned type corresponding
5157 // to the signed type.
5158 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5159 }
5160 return destType;
5161}