blob: 4c935139568b1a282430326e62a2220656adc5ad [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner465fa322008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump11289f42009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump11289f42009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall9f57c292009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000056}
57
Chris Lattnerd5973eb2006-11-12 00:53:46 +000058ASTContext::~ASTContext() {
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000059 if (FreeMemory) {
60 // Deallocate all the types.
61 while (!Types.empty()) {
62 Types.back()->Destroy(*this);
63 Types.pop_back();
64 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000065
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000066 for (llvm::FoldingSet<ExtQuals>::iterator
67 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
68 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000069 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000070 }
71 }
72
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000073 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
74 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
75 // Increment in loop to prevent using deallocated memory.
76 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
77 delete R;
78 }
79
80 for (llvm::DenseMap<const ObjCContainerDecl*,
81 const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
83 // Increment in loop to prevent using deallocated memory.
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
Nuno Lopese013c7f2008-12-17 22:30:25 +000086 }
87
Douglas Gregorf21eb492009-03-26 23:50:42 +000088 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +000089 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +000091 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000092 NNS != NNSEnd; ) {
93 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +000094 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000095 }
Douglas Gregorf21eb492009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000101}
102
Mike Stump11289f42009-09-09 15:08:12 +0000103void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Chris Lattner4eb445d2007-01-26 01:27:23 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000111
Douglas Gregora30d0462009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000118
Chris Lattner4eb445d2007-01-26 01:27:23 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000122 }
123
Douglas Gregora30d0462009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000133
Douglas Gregora30d0462009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000140}
141
142
John McCall48f2d582009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000147}
148
Chris Lattner970e54e2006-11-12 00:37:36 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000151
Chris Lattner970e54e2006-11-12 00:37:36 +0000152 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000154
Chris Lattner970e54e2006-11-12 00:37:36 +0000155 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000156 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000157 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000162 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chris Lattner970e54e2006-11-12 00:37:36 +0000169 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000175
Chris Lattner970e54e2006-11-12 00:37:36 +0000176 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000180
Chris Lattnerf122cef2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner007cb022009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000189
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000209
Mike Stump11289f42009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner970e54e2006-11-12 00:37:36 +0000214 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218
Steve Naroff66e9f332007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000220
Steve Naroff1329fa02009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000225
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000230
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000232
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000238}
239
Douglas Gregor86d142a2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000247
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump11289f42009-09-09 15:08:12 +0000251void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000260}
261
John McCalle61f2ba2009-11-18 02:36:19 +0000262NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000263ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000265 = InstantiatedFromUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000267 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000268
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
John McCallb96ec562009-12-04 22:46:56 +0000273ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
274 assert((isa<UsingDecl>(Pattern) ||
275 isa<UnresolvedUsingValueDecl>(Pattern) ||
276 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277 "pattern decl is not a using decl");
278 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279 InstantiatedFromUsingDecl[Inst] = Pattern;
280}
281
282UsingShadowDecl *
283ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
284 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
285 = InstantiatedFromUsingShadowDecl.find(Inst);
286 if (Pos == InstantiatedFromUsingShadowDecl.end())
287 return 0;
288
289 return Pos->second;
290}
291
292void
293ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294 UsingShadowDecl *Pattern) {
295 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
296 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000297}
298
Anders Carlsson5da84842009-09-01 04:26:58 +0000299FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301 = InstantiatedFromUnnamedFieldDecl.find(Field);
302 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000304
Anders Carlsson5da84842009-09-01 04:26:58 +0000305 return Pos->second;
306}
307
308void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309 FieldDecl *Tmpl) {
310 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
311 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000314
Anders Carlsson5da84842009-09-01 04:26:58 +0000315 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316}
317
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000318namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000319 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000320 : std::binary_function<SourceRange, SourceRange, bool> {
321 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000322
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000323 public:
324 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000325
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000326 bool operator()(SourceRange X, SourceRange Y) {
327 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328 }
329 };
330}
331
332/// \brief Determine whether the given comment is a Doxygen-style comment.
333///
334/// \param Start the start of the comment text.
335///
336/// \param End the end of the comment text.
337///
338/// \param Member whether we want to check whether this is a member comment
339/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
340/// we only return true when we find a non-member comment.
Mike Stump11289f42009-09-09 15:08:12 +0000341static bool
342isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000343 bool Member = false) {
Mike Stump11289f42009-09-09 15:08:12 +0000344 const char *BufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000345 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
346 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
347 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000348
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000349 if (End - Start < 4)
350 return false;
351
352 assert(Start[0] == '/' && "Not a comment?");
353 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
354 return false;
355 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
356 return false;
357
358 return (Start[3] == '<') == Member;
359}
360
361/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump11289f42009-09-09 15:08:12 +0000362/// it has one.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000363const char *ASTContext::getCommentForDecl(const Decl *D) {
364 if (!D)
365 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000366
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000367 // Check whether we have cached a comment string for this declaration
368 // already.
Mike Stump11289f42009-09-09 15:08:12 +0000369 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000370 = DeclComments.find(D);
371 if (Pos != DeclComments.end())
372 return Pos->second.c_str();
373
Mike Stump11289f42009-09-09 15:08:12 +0000374 // If we have an external AST source and have not yet loaded comments from
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000375 // that source, do so now.
376 if (ExternalSource && !LoadedExternalComments) {
377 std::vector<SourceRange> LoadedComments;
378 ExternalSource->ReadComments(LoadedComments);
Mike Stump11289f42009-09-09 15:08:12 +0000379
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000380 if (!LoadedComments.empty())
381 Comments.insert(Comments.begin(), LoadedComments.begin(),
382 LoadedComments.end());
Mike Stump11289f42009-09-09 15:08:12 +0000383
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000384 LoadedExternalComments = true;
385 }
Mike Stump11289f42009-09-09 15:08:12 +0000386
387 // If there are no comments anywhere, we won't find anything.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000388 if (Comments.empty())
389 return 0;
390
391 // If the declaration doesn't map directly to a location in a file, we
392 // can't find the comment.
393 SourceLocation DeclStartLoc = D->getLocStart();
394 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
395 return 0;
396
397 // Find the comment that occurs just before this declaration.
398 std::vector<SourceRange>::iterator LastComment
Mike Stump11289f42009-09-09 15:08:12 +0000399 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000400 SourceRange(DeclStartLoc),
401 BeforeInTranslationUnit(&SourceMgr));
Mike Stump11289f42009-09-09 15:08:12 +0000402
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000403 // Decompose the location for the start of the declaration and find the
404 // beginning of the file buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000405 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000406 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000407 const char *FileBufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000408 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump11289f42009-09-09 15:08:12 +0000409
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000410 // First check whether we have a comment for a member.
411 if (LastComment != Comments.end() &&
412 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
413 isDoxygenComment(SourceMgr, *LastComment, true)) {
414 std::pair<FileID, unsigned> LastCommentEndDecomp
415 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
416 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump11289f42009-09-09 15:08:12 +0000418 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000419 LastCommentEndDecomp.second)) {
420 // The Doxygen member comment comes after the declaration starts and
421 // is on the same line and in the same file as the declaration. This
422 // is the comment we want.
423 std::string &Result = DeclComments[D];
Mike Stump11289f42009-09-09 15:08:12 +0000424 Result.append(FileBufferStart +
425 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000426 FileBufferStart + LastCommentEndDecomp.second + 1);
427 return Result.c_str();
428 }
429 }
Mike Stump11289f42009-09-09 15:08:12 +0000430
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000431 if (LastComment == Comments.begin())
432 return 0;
433 --LastComment;
434
435 // Decompose the end of the comment.
436 std::pair<FileID, unsigned> LastCommentEndDecomp
437 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000438
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000439 // If the comment and the declaration aren't in the same file, then they
440 // aren't related.
441 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
442 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000444 // Check that we actually have a Doxygen comment.
445 if (!isDoxygenComment(SourceMgr, *LastComment))
446 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000447
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000448 // Compute the starting line for the declaration and for the end of the
449 // comment (this is expensive).
Mike Stump11289f42009-09-09 15:08:12 +0000450 unsigned DeclStartLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000451 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452 unsigned CommentEndLine
Mike Stump11289f42009-09-09 15:08:12 +0000453 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000454 LastCommentEndDecomp.second);
Mike Stump11289f42009-09-09 15:08:12 +0000455
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000456 // If the comment does not end on the line prior to the declaration, then
457 // the comment is not associated with the declaration at all.
458 if (CommentEndLine + 1 != DeclStartLine)
459 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000460
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000461 // We have a comment, but there may be more comments on the previous lines.
462 // Keep looking so long as the comments are still Doxygen comments and are
463 // still adjacent.
Mike Stump11289f42009-09-09 15:08:12 +0000464 unsigned ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000465 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
466 std::vector<SourceRange>::iterator FirstComment = LastComment;
467 while (FirstComment != Comments.begin()) {
468 // Look at the previous comment
469 --FirstComment;
470 std::pair<FileID, unsigned> Decomp
471 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000472
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000473 // If this previous comment is in a different file, we're done.
474 if (Decomp.first != DeclStartDecomp.first) {
475 ++FirstComment;
476 break;
477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000479 // If this comment is not a Doxygen comment, we're done.
480 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
481 ++FirstComment;
482 break;
483 }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000485 // If the line number is not what we expected, we're done.
486 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
487 if (Line != ExpectedLine) {
488 ++FirstComment;
489 break;
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000492 // Set the next expected line number.
Mike Stump11289f42009-09-09 15:08:12 +0000493 ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000494 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495 }
Mike Stump11289f42009-09-09 15:08:12 +0000496
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000497 // The iterator range [FirstComment, LastComment] contains all of the
498 // BCPL comments that, together, are associated with this declaration.
499 // Form a single comment block string for this declaration that concatenates
500 // all of these comments.
501 std::string &Result = DeclComments[D];
502 while (FirstComment != LastComment) {
503 std::pair<FileID, unsigned> DecompStart
504 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
505 std::pair<FileID, unsigned> DecompEnd
506 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
507 Result.append(FileBufferStart + DecompStart.second,
508 FileBufferStart + DecompEnd.second + 1);
509 ++FirstComment;
510 }
Mike Stump11289f42009-09-09 15:08:12 +0000511
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000512 // Append the last comment line.
Mike Stump11289f42009-09-09 15:08:12 +0000513 Result.append(FileBufferStart +
514 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000515 FileBufferStart + LastCommentEndDecomp.second + 1);
516 return Result.c_str();
517}
518
Chris Lattner53cfe802007-07-18 17:52:12 +0000519//===----------------------------------------------------------------------===//
520// Type Sizing and Analysis
521//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000522
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000523/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
524/// scalar floating point type.
525const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000526 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000527 assert(BT && "Not a floating point type!");
528 switch (BT->getKind()) {
529 default: assert(0 && "Not a floating point type!");
530 case BuiltinType::Float: return Target.getFloatFormat();
531 case BuiltinType::Double: return Target.getDoubleFormat();
532 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
533 }
534}
535
Ken Dyck160146e2010-01-27 17:10:57 +0000536/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000537/// specified decl. Note that bitfields do not have a valid alignment, so
538/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000539/// If @p RefAsPointee, references are treated like their underlying type
540/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000541CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000542 unsigned Align = Target.getCharWidth();
543
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000544 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000545 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000546
Chris Lattner68061312009-01-24 21:53:27 +0000547 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000549 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000550 if (RefAsPointee)
551 T = RT->getPointeeType();
552 else
553 T = getPointerType(RT->getPointeeType());
554 }
555 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000557 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558 T = cast<ArrayType>(T)->getElementType();
559
560 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561 }
Chris Lattner68061312009-01-24 21:53:27 +0000562 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000563
Ken Dyck160146e2010-01-27 17:10:57 +0000564 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000565}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000566
Chris Lattner983a8bb2007-07-13 22:13:22 +0000567/// getTypeSize - Return the size of the specified type, in bits. This method
568/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000569///
570/// FIXME: Pointers into different addr spaces could have different sizes and
571/// alignment requirements: getPointerInfo should take an AddrSpace, this
572/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000573std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000574ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000575 uint64_t Width=0;
576 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000577 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000578#define TYPE(Class, Base)
579#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000580#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000583 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000584 break;
585
Chris Lattner355332d2007-07-13 22:27:08 +0000586 case Type::FunctionNoProto:
587 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000588 // GCC extension: alignof(function) = 32 bits
589 Width = 0;
590 Align = 32;
591 break;
592
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000593 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000594 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000595 Width = 0;
596 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597 break;
598
Steve Naroff5c131802007-08-30 01:06:46 +0000599 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000600 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000601
Chris Lattner37e05872008-03-05 18:54:05 +0000602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000603 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000604 Align = EltInfo.second;
605 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000606 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000607 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000608 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000609 const VectorType *VT = cast<VectorType>(T);
610 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
611 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000612 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000613 // If the alignment is not a power of 2, round up to the next power of 2.
614 // This happens for non-power-of-2 length vectors.
Chris Lattner63d2b362009-10-22 05:17:15 +0000615 if (VT->getNumElements() & (VT->getNumElements()-1)) {
616 Align = llvm::NextPowerOf2(Align);
617 Width = llvm::RoundUpToAlignment(Width, Align);
618 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000619 break;
620 }
Chris Lattner647fb222007-07-18 18:26:58 +0000621
Chris Lattner7570e9c2008-03-08 08:52:55 +0000622 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000623 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000624 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000625 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000626 // GCC extension: alignof(void) = 8 bits.
627 Width = 0;
628 Align = 8;
629 break;
630
Chris Lattner6a4f7452007-12-19 19:23:28 +0000631 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000632 Width = Target.getBoolWidth();
633 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000634 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000635 case BuiltinType::Char_S:
636 case BuiltinType::Char_U:
637 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000638 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000639 Width = Target.getCharWidth();
640 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000641 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000642 case BuiltinType::WChar:
643 Width = Target.getWCharWidth();
644 Align = Target.getWCharAlign();
645 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000646 case BuiltinType::Char16:
647 Width = Target.getChar16Width();
648 Align = Target.getChar16Align();
649 break;
650 case BuiltinType::Char32:
651 Width = Target.getChar32Width();
652 Align = Target.getChar32Align();
653 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000654 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000655 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000656 Width = Target.getShortWidth();
657 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000659 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000660 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000661 Width = Target.getIntWidth();
662 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000663 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000664 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000665 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000666 Width = Target.getLongWidth();
667 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000668 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000669 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000671 Width = Target.getLongLongWidth();
672 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000673 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000674 case BuiltinType::Int128:
675 case BuiltinType::UInt128:
676 Width = 128;
677 Align = 128; // int128_t is 128-bit aligned on all targets.
678 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000679 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000680 Width = Target.getFloatWidth();
681 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000682 break;
683 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000684 Width = Target.getDoubleWidth();
685 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000688 Width = Target.getLongDoubleWidth();
689 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000690 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000691 case BuiltinType::NullPtr:
692 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
693 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000694 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000695 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000696 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000697 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000698 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000699 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000700 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000701 case Type::BlockPointer: {
702 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
703 Width = Target.getPointerWidth(AS);
704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000707 case Type::LValueReference:
708 case Type::RValueReference: {
709 // alignof and sizeof should never enter this code path here, so we go
710 // the pointer route.
711 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
712 Width = Target.getPointerWidth(AS);
713 Align = Target.getPointerAlign(AS);
714 break;
715 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000716 case Type::Pointer: {
717 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000718 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000719 Align = Target.getPointerAlign(AS);
720 break;
721 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000722 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000723 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000724 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000725 getTypeInfo(getPointerDiffType());
726 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000727 if (Pointee->isFunctionType())
728 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000729 Align = PtrDiffInfo.second;
730 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000731 }
Chris Lattner647fb222007-07-18 18:26:58 +0000732 case Type::Complex: {
733 // Complex types have the same alignment as their elements, but twice the
734 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000735 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000736 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000737 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000738 Align = EltInfo.second;
739 break;
740 }
Devang Pateldbb72632008-06-04 21:54:36 +0000741 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000742 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000743 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
744 Width = Layout.getSize();
745 Align = Layout.getAlignment();
746 break;
747 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000748 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000749 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000750 const TagType *TT = cast<TagType>(T);
751
752 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000753 Width = 1;
754 Align = 1;
755 break;
756 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000758 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000759 return getTypeInfo(ET->getDecl()->getIntegerType());
760
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000761 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000762 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
763 Width = Layout.getSize();
764 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000765 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000766 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000767
Chris Lattner63d2b362009-10-22 05:17:15 +0000768 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000769 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
770 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000771
Chris Lattner63d2b362009-10-22 05:17:15 +0000772 case Type::Elaborated:
773 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
774 .getTypePtr());
John McCallfcc33b02009-09-05 00:15:47 +0000775
Douglas Gregoref462e62009-04-30 17:32:17 +0000776 case Type::Typedef: {
777 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000778 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000779 Align = std::max(Aligned->getMaxAlignment(),
780 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000781 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
782 } else
783 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000784 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000785 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000786
787 case Type::TypeOfExpr:
788 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
789 .getTypePtr());
790
791 case Type::TypeOf:
792 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
793
Anders Carlsson81df7b82009-06-24 19:06:50 +0000794 case Type::Decltype:
795 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
796 .getTypePtr());
797
Douglas Gregoref462e62009-04-30 17:32:17 +0000798 case Type::QualifiedName:
799 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000800
Douglas Gregoref462e62009-04-30 17:32:17 +0000801 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000802 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000803 "Cannot request the size of a dependent type");
804 // FIXME: this is likely to be wrong once we support template
805 // aliases, since a template alias could refer to a typedef that
806 // has an __aligned__ attribute on it.
807 return getTypeInfo(getCanonicalType(T));
808 }
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner53cfe802007-07-18 17:52:12 +0000810 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000811 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000812}
813
Ken Dyck8c89d592009-12-22 14:23:30 +0000814/// getTypeSizeInChars - Return the size of the specified type, in characters.
815/// This method does not work on incomplete types.
816CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000817 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000818}
819CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000820 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000821}
822
Ken Dycka6046ab2010-01-26 17:25:18 +0000823/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000824/// characters. This method does not work on incomplete types.
825CharUnits ASTContext::getTypeAlignInChars(QualType T) {
826 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
827}
828CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
829 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
830}
831
Chris Lattnera3402cd2009-01-27 18:08:34 +0000832/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
833/// type for the current target in bits. This can be different than the ABI
834/// alignment in cases where it is beneficial for performance to overalign
835/// a data type.
836unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
837 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000838
839 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000840 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000841 T = CT->getElementType().getTypePtr();
842 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
843 T->isSpecificBuiltinType(BuiltinType::LongLong))
844 return std::max(ABIAlign, (unsigned)getTypeSize(T));
845
Chris Lattnera3402cd2009-01-27 18:08:34 +0000846 return ABIAlign;
847}
848
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000849static void CollectLocalObjCIvars(ASTContext *Ctx,
850 const ObjCInterfaceDecl *OI,
851 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000852 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
853 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000854 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000855 if (!IVDecl->isInvalidDecl())
856 Fields.push_back(cast<FieldDecl>(IVDecl));
857 }
858}
859
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000860void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
861 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
862 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
863 CollectObjCIvars(SuperClass, Fields);
864 CollectLocalObjCIvars(this, OI, Fields);
865}
866
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000867/// ShallowCollectObjCIvars -
868/// Collect all ivars, including those synthesized, in the current class.
869///
870void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
871 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
872 bool CollectSynthesized) {
873 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
874 E = OI->ivar_end(); I != E; ++I) {
875 Ivars.push_back(*I);
876 }
877 if (CollectSynthesized)
878 CollectSynthesizedIvars(OI, Ivars);
879}
880
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000881void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
882 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000883 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
884 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000885 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
886 Ivars.push_back(Ivar);
Mike Stump11289f42009-09-09 15:08:12 +0000887
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000888 // Also look into nested protocols.
889 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
890 E = PD->protocol_end(); P != E; ++P)
891 CollectProtocolSynthesizedIvars(*P, Ivars);
892}
893
894/// CollectSynthesizedIvars -
895/// This routine collect synthesized ivars for the designated class.
896///
897void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
898 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000899 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
900 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000901 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
902 Ivars.push_back(Ivar);
903 }
904 // Also look into interface's protocol list for properties declared
905 // in the protocol and whose ivars are synthesized.
906 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
907 PE = OI->protocol_end(); P != PE; ++P) {
908 ObjCProtocolDecl *PD = (*P);
909 CollectProtocolSynthesizedIvars(PD, Ivars);
910 }
911}
912
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000913/// CollectInheritedProtocols - Collect all protocols in current class and
914/// those inherited by it.
915void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
916 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
917 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
918 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
919 PE = OI->protocol_end(); P != PE; ++P) {
920 ObjCProtocolDecl *Proto = (*P);
921 Protocols.push_back(Proto);
922 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
923 PE = Proto->protocol_end(); P != PE; ++P)
924 CollectInheritedProtocols(*P, Protocols);
925 }
926
927 // Categories of this Interface.
928 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
929 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
930 CollectInheritedProtocols(CDeclChain, Protocols);
931 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
932 while (SD) {
933 CollectInheritedProtocols(SD, Protocols);
934 SD = SD->getSuperClass();
935 }
936 return;
937 }
938 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
939 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
940 PE = OC->protocol_end(); P != PE; ++P) {
941 ObjCProtocolDecl *Proto = (*P);
942 Protocols.push_back(Proto);
943 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
944 PE = Proto->protocol_end(); P != PE; ++P)
945 CollectInheritedProtocols(*P, Protocols);
946 }
947 return;
948 }
949 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
950 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
951 PE = OP->protocol_end(); P != PE; ++P) {
952 ObjCProtocolDecl *Proto = (*P);
953 Protocols.push_back(Proto);
954 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
955 PE = Proto->protocol_end(); P != PE; ++P)
956 CollectInheritedProtocols(*P, Protocols);
957 }
958 return;
959 }
960}
961
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000962unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
963 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000964 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
965 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000966 if ((*I)->getPropertyIvarDecl())
967 ++count;
968
969 // Also look into nested protocols.
970 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
971 E = PD->protocol_end(); P != E; ++P)
972 count += CountProtocolSynthesizedIvars(*P);
973 return count;
974}
975
Mike Stump11289f42009-09-09 15:08:12 +0000976unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000977 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000978 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
979 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000980 if ((*I)->getPropertyIvarDecl())
981 ++count;
982 }
983 // Also look into interface's protocol list for properties declared
984 // in the protocol and whose ivars are synthesized.
985 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
986 PE = OI->protocol_end(); P != PE; ++P) {
987 ObjCProtocolDecl *PD = (*P);
988 count += CountProtocolSynthesizedIvars(PD);
989 }
990 return count;
991}
992
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000993/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
994ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
995 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
996 I = ObjCImpls.find(D);
997 if (I != ObjCImpls.end())
998 return cast<ObjCImplementationDecl>(I->second);
999 return 0;
1000}
1001/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1002ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1003 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1004 I = ObjCImpls.find(D);
1005 if (I != ObjCImpls.end())
1006 return cast<ObjCCategoryImplDecl>(I->second);
1007 return 0;
1008}
1009
1010/// \brief Set the implementation of ObjCInterfaceDecl.
1011void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1012 ObjCImplementationDecl *ImplD) {
1013 assert(IFaceD && ImplD && "Passed null params");
1014 ObjCImpls[IFaceD] = ImplD;
1015}
1016/// \brief Set the implementation of ObjCCategoryDecl.
1017void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1018 ObjCCategoryImplDecl *ImplD) {
1019 assert(CatD && ImplD && "Passed null params");
1020 ObjCImpls[CatD] = ImplD;
1021}
1022
John McCallbcd03502009-12-07 02:54:59 +00001023/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001024///
John McCallbcd03502009-12-07 02:54:59 +00001025/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001026/// the TypeLoc wrappers.
1027///
1028/// \param T the type that will be the basis for type source info. This type
1029/// should refer to how the declarator was written in source code, not to
1030/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001031TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001032 unsigned DataSize) {
1033 if (!DataSize)
1034 DataSize = TypeLoc::getFullDataSizeForType(T);
1035 else
1036 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001037 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001038
John McCallbcd03502009-12-07 02:54:59 +00001039 TypeSourceInfo *TInfo =
1040 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1041 new (TInfo) TypeSourceInfo(T);
1042 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001043}
1044
John McCallbcd03502009-12-07 02:54:59 +00001045TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001046 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001047 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001048 DI->getTypeLoc().initialize(L);
1049 return DI;
1050}
1051
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001052/// getInterfaceLayoutImpl - Get or compute information about the
1053/// layout of the given interface.
1054///
1055/// \param Impl - If given, also include the layout of the interface's
1056/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +00001057const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001058ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1059 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +00001060 assert(!D->isForwardDecl() && "Invalid interface decl!");
1061
Devang Pateldbb72632008-06-04 21:54:36 +00001062 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +00001063 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001064 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1065 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1066 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +00001067
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001068 // Add in synthesized ivar count if laying out an implementation.
1069 if (Impl) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001070 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001071 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001072 // entry. Note we can't cache this because we simply free all
1073 // entries later; however we shouldn't look up implementations
1074 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001075 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001076 return getObjCLayout(D, 0);
1077 }
1078
Mike Stump11289f42009-09-09 15:08:12 +00001079 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001080 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1081 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001082
Devang Pateldbb72632008-06-04 21:54:36 +00001083 return *NewEntry;
1084}
1085
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001086const ASTRecordLayout &
1087ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1088 return getObjCLayout(D, 0);
1089}
1090
1091const ASTRecordLayout &
1092ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1093 return getObjCLayout(D->getClassInterface(), D);
1094}
1095
Devang Patele11664a2007-11-01 19:11:01 +00001096/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +00001097/// specified record (struct/union/class), which indicates its size and field
1098/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +00001099const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek21475702008-09-05 17:16:31 +00001100 D = D->getDefinition(*this);
1101 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +00001102
Chris Lattner53cfe802007-07-18 17:52:12 +00001103 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +00001104 // Note that we can't save a reference to the entry because this function
1105 // is recursive.
1106 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +00001107 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +00001108
Mike Stump11289f42009-09-09 15:08:12 +00001109 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001110 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +00001111 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattner647fb222007-07-18 18:26:58 +00001113 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +00001114}
1115
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001116const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1117 RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1118 assert(RD && "Cannot get key function for forward declarations!");
1119
1120 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1121 if (!Entry)
1122 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1123 else
1124 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1125 "Key function changed!");
1126
1127 return Entry;
1128}
1129
Chris Lattner983a8bb2007-07-13 22:13:22 +00001130//===----------------------------------------------------------------------===//
1131// Type creation/memoization methods
1132//===----------------------------------------------------------------------===//
1133
John McCall8ccfcb52009-09-24 19:53:00 +00001134QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1135 unsigned Fast = Quals.getFastQualifiers();
1136 Quals.removeFastQualifiers();
1137
1138 // Check if we've already instantiated this type.
1139 llvm::FoldingSetNodeID ID;
1140 ExtQuals::Profile(ID, TypeNode, Quals);
1141 void *InsertPos = 0;
1142 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1143 assert(EQ->getQualifiers() == Quals);
1144 QualType T = QualType(EQ, Fast);
1145 return T;
1146 }
1147
John McCall90d1c2d2009-09-24 23:30:46 +00001148 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001149 ExtQualNodes.InsertNode(New, InsertPos);
1150 QualType T = QualType(New, Fast);
1151 return T;
1152}
1153
1154QualType ASTContext::getVolatileType(QualType T) {
1155 QualType CanT = getCanonicalType(T);
1156 if (CanT.isVolatileQualified()) return T;
1157
1158 QualifierCollector Quals;
1159 const Type *TypeNode = Quals.strip(T);
1160 Quals.addVolatile();
1161
1162 return getExtQualType(TypeNode, Quals);
1163}
1164
Fariborz Jahanianece85822009-02-17 18:27:45 +00001165QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001166 QualType CanT = getCanonicalType(T);
1167 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001168 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001169
John McCall8ccfcb52009-09-24 19:53:00 +00001170 // If we are composing extended qualifiers together, merge together
1171 // into one ExtQuals node.
1172 QualifierCollector Quals;
1173 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001174
John McCall8ccfcb52009-09-24 19:53:00 +00001175 // If this type already has an address space specified, it cannot get
1176 // another one.
1177 assert(!Quals.hasAddressSpace() &&
1178 "Type cannot be in multiple addr spaces!");
1179 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001180
John McCall8ccfcb52009-09-24 19:53:00 +00001181 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001182}
1183
Chris Lattnerd60183d2009-02-18 22:53:11 +00001184QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001185 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001186 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001187 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001188 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001189
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001190 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001191 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001192 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001193 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1194 return getPointerType(ResultType);
1195 }
1196 }
Mike Stump11289f42009-09-09 15:08:12 +00001197
John McCall8ccfcb52009-09-24 19:53:00 +00001198 // If we are composing extended qualifiers together, merge together
1199 // into one ExtQuals node.
1200 QualifierCollector Quals;
1201 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001202
John McCall8ccfcb52009-09-24 19:53:00 +00001203 // If this type already has an ObjCGC specified, it cannot get
1204 // another one.
1205 assert(!Quals.hasObjCGCAttr() &&
1206 "Type cannot have multiple ObjCGCs!");
1207 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001208
John McCall8ccfcb52009-09-24 19:53:00 +00001209 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001210}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001211
Douglas Gregor8c940862010-01-18 17:14:39 +00001212static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1213 bool AddNoReturn,
1214 CallingConv CallConv) {
John McCall8ccfcb52009-09-24 19:53:00 +00001215 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001216 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1217 QualType Pointee = Pointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001218 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1219 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001220 if (ResultType == Pointee)
1221 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001222
1223 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001224 } else if (const BlockPointerType *BlockPointer
1225 = T->getAs<BlockPointerType>()) {
1226 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001227 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1228 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001229 if (ResultType == Pointee)
1230 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001231
1232 ResultType = Context.getBlockPointerType(ResultType);
1233 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1234 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001235 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001236
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001237 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001238 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1239 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001240 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001241 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001242 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001243 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1244 FPT->getNumArgs(), FPT->isVariadic(),
1245 FPT->getTypeQuals(),
1246 FPT->hasExceptionSpec(),
1247 FPT->hasAnyExceptionSpec(),
1248 FPT->getNumExceptions(),
1249 FPT->exception_begin(),
1250 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001251 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001252 } else
1253 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001254
1255 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1256}
1257
1258QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1259 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1260}
1261
1262QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1263 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump8c5d7992009-07-25 21:26:53 +00001264}
1265
Chris Lattnerc6395932007-06-22 20:56:16 +00001266/// getComplexType - Return the uniqued reference to the type for a complex
1267/// number with the specified element type.
1268QualType ASTContext::getComplexType(QualType T) {
1269 // Unique pointers, to guarantee there is only one pointer of a particular
1270 // structure.
1271 llvm::FoldingSetNodeID ID;
1272 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001273
Chris Lattnerc6395932007-06-22 20:56:16 +00001274 void *InsertPos = 0;
1275 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1276 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Chris Lattnerc6395932007-06-22 20:56:16 +00001278 // If the pointee type isn't canonical, this won't be a canonical type either,
1279 // so fill in the canonical type field.
1280 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001281 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001282 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001283
Chris Lattnerc6395932007-06-22 20:56:16 +00001284 // Get the new insert position for the node we care about.
1285 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001286 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001287 }
John McCall90d1c2d2009-09-24 23:30:46 +00001288 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001289 Types.push_back(New);
1290 ComplexTypes.InsertNode(New, InsertPos);
1291 return QualType(New, 0);
1292}
1293
Chris Lattner970e54e2006-11-12 00:37:36 +00001294/// getPointerType - Return the uniqued reference to the type for a pointer to
1295/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001296QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001297 // Unique pointers, to guarantee there is only one pointer of a particular
1298 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001299 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001300 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattner67521df2007-01-27 01:29:36 +00001302 void *InsertPos = 0;
1303 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001304 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattner7ccecb92006-11-12 08:50:50 +00001306 // If the pointee type isn't canonical, this won't be a canonical type either,
1307 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001308 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001309 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001310 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattner67521df2007-01-27 01:29:36 +00001312 // Get the new insert position for the node we care about.
1313 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001314 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001315 }
John McCall90d1c2d2009-09-24 23:30:46 +00001316 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001317 Types.push_back(New);
1318 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001319 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001320}
1321
Mike Stump11289f42009-09-09 15:08:12 +00001322/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001323/// a pointer to the specified block.
1324QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001325 assert(T->isFunctionType() && "block of function types only");
1326 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001327 // structure.
1328 llvm::FoldingSetNodeID ID;
1329 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001330
Steve Naroffec33ed92008-08-27 16:04:49 +00001331 void *InsertPos = 0;
1332 if (BlockPointerType *PT =
1333 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1334 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001335
1336 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001337 // type either so fill in the canonical type field.
1338 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001339 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001340 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001341
Steve Naroffec33ed92008-08-27 16:04:49 +00001342 // Get the new insert position for the node we care about.
1343 BlockPointerType *NewIP =
1344 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001345 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001346 }
John McCall90d1c2d2009-09-24 23:30:46 +00001347 BlockPointerType *New
1348 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001349 Types.push_back(New);
1350 BlockPointerTypes.InsertNode(New, InsertPos);
1351 return QualType(New, 0);
1352}
1353
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001354/// getLValueReferenceType - Return the uniqued reference to the type for an
1355/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001356QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001357 // Unique pointers, to guarantee there is only one pointer of a particular
1358 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001359 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001360 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001361
1362 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001363 if (LValueReferenceType *RT =
1364 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001365 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001366
John McCallfc93cf92009-10-22 22:37:11 +00001367 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1368
Bill Wendling3708c182007-05-27 10:15:43 +00001369 // If the referencee type isn't canonical, this won't be a canonical type
1370 // either, so fill in the canonical type field.
1371 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001372 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1373 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1374 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001375
Bill Wendling3708c182007-05-27 10:15:43 +00001376 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001377 LValueReferenceType *NewIP =
1378 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001379 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001380 }
1381
John McCall90d1c2d2009-09-24 23:30:46 +00001382 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001383 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1384 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001385 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001386 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001387
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001388 return QualType(New, 0);
1389}
1390
1391/// getRValueReferenceType - Return the uniqued reference to the type for an
1392/// rvalue reference to the specified type.
1393QualType ASTContext::getRValueReferenceType(QualType T) {
1394 // Unique pointers, to guarantee there is only one pointer of a particular
1395 // structure.
1396 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001397 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001398
1399 void *InsertPos = 0;
1400 if (RValueReferenceType *RT =
1401 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1402 return QualType(RT, 0);
1403
John McCallfc93cf92009-10-22 22:37:11 +00001404 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1405
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001406 // If the referencee type isn't canonical, this won't be a canonical type
1407 // either, so fill in the canonical type field.
1408 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001409 if (InnerRef || !T.isCanonical()) {
1410 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1411 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001412
1413 // Get the new insert position for the node we care about.
1414 RValueReferenceType *NewIP =
1415 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1416 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1417 }
1418
John McCall90d1c2d2009-09-24 23:30:46 +00001419 RValueReferenceType *New
1420 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001421 Types.push_back(New);
1422 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001423 return QualType(New, 0);
1424}
1425
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001426/// getMemberPointerType - Return the uniqued reference to the type for a
1427/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001428QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001429 // Unique pointers, to guarantee there is only one pointer of a particular
1430 // structure.
1431 llvm::FoldingSetNodeID ID;
1432 MemberPointerType::Profile(ID, T, Cls);
1433
1434 void *InsertPos = 0;
1435 if (MemberPointerType *PT =
1436 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1437 return QualType(PT, 0);
1438
1439 // If the pointee or class type isn't canonical, this won't be a canonical
1440 // type either, so fill in the canonical type field.
1441 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001442 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001443 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1444
1445 // Get the new insert position for the node we care about.
1446 MemberPointerType *NewIP =
1447 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1448 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1449 }
John McCall90d1c2d2009-09-24 23:30:46 +00001450 MemberPointerType *New
1451 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001452 Types.push_back(New);
1453 MemberPointerTypes.InsertNode(New, InsertPos);
1454 return QualType(New, 0);
1455}
1456
Mike Stump11289f42009-09-09 15:08:12 +00001457/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001458/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001459QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001460 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001461 ArrayType::ArraySizeModifier ASM,
1462 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001463 assert((EltTy->isDependentType() ||
1464 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001465 "Constant array of VLAs is illegal!");
1466
Chris Lattnere2df3f92009-05-13 04:12:56 +00001467 // Convert the array size into a canonical width matching the pointer size for
1468 // the target.
1469 llvm::APInt ArySize(ArySizeIn);
1470 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001471
Chris Lattner23b7eb62007-06-15 23:05:46 +00001472 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001473 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Chris Lattner36f8e652007-01-27 08:31:04 +00001475 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001476 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001477 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001478 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Chris Lattner7ccecb92006-11-12 08:50:50 +00001480 // If the element type isn't canonical, this won't be a canonical type either,
1481 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001482 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001483 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001484 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001485 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001486 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001487 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001488 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001490 }
Mike Stump11289f42009-09-09 15:08:12 +00001491
John McCall90d1c2d2009-09-24 23:30:46 +00001492 ConstantArrayType *New = new(*this,TypeAlignment)
1493 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001494 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001495 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001496 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001497}
1498
Steve Naroffcadebd02007-08-30 18:14:25 +00001499/// getVariableArrayType - Returns a non-unique reference to the type for a
1500/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001501QualType ASTContext::getVariableArrayType(QualType EltTy,
1502 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001503 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001504 unsigned EltTypeQuals,
1505 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001506 // Since we don't unique expressions, it isn't possible to unique VLA's
1507 // that have an expression provided for their size.
1508
John McCall90d1c2d2009-09-24 23:30:46 +00001509 VariableArrayType *New = new(*this, TypeAlignment)
1510 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001511
1512 VariableArrayTypes.push_back(New);
1513 Types.push_back(New);
1514 return QualType(New, 0);
1515}
1516
Douglas Gregor4619e432008-12-05 23:32:09 +00001517/// getDependentSizedArrayType - Returns a non-unique reference to
1518/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001519/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001520QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1521 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001522 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001523 unsigned EltTypeQuals,
1524 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001525 assert((!NumElts || NumElts->isTypeDependent() ||
1526 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001527 "Size must be type- or value-dependent!");
1528
Douglas Gregorf3f95522009-07-31 00:23:35 +00001529 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001530 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001531 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001532
1533 if (NumElts) {
1534 // Dependently-sized array types that do not have a specified
1535 // number of elements will have their sizes deduced from an
1536 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001537 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1538 EltTypeQuals, NumElts);
1539
1540 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1541 }
1542
Douglas Gregorf3f95522009-07-31 00:23:35 +00001543 DependentSizedArrayType *New;
1544 if (Canon) {
1545 // We already have a canonical version of this array type; use it as
1546 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001547 New = new (*this, TypeAlignment)
1548 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1549 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001550 } else {
1551 QualType CanonEltTy = getCanonicalType(EltTy);
1552 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001553 New = new (*this, TypeAlignment)
1554 DependentSizedArrayType(*this, EltTy, QualType(),
1555 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001556
Douglas Gregorc42075a2010-02-04 18:10:26 +00001557 if (NumElts) {
1558 DependentSizedArrayType *CanonCheck
1559 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1560 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1561 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001562 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001563 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001564 } else {
1565 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1566 ASM, EltTypeQuals,
1567 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001568 New = new (*this, TypeAlignment)
1569 DependentSizedArrayType(*this, EltTy, Canon,
1570 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001571 }
1572 }
Mike Stump11289f42009-09-09 15:08:12 +00001573
Douglas Gregor4619e432008-12-05 23:32:09 +00001574 Types.push_back(New);
1575 return QualType(New, 0);
1576}
1577
Eli Friedmanbd258282008-02-15 18:16:39 +00001578QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1579 ArrayType::ArraySizeModifier ASM,
1580 unsigned EltTypeQuals) {
1581 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001582 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001583
1584 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001585 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001586 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1587 return QualType(ATP, 0);
1588
1589 // If the element type isn't canonical, this won't be a canonical type
1590 // either, so fill in the canonical type field.
1591 QualType Canonical;
1592
John McCallb692a092009-10-22 20:10:53 +00001593 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001594 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001595 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001596
1597 // Get the new insert position for the node we care about.
1598 IncompleteArrayType *NewIP =
1599 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001601 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001602
John McCall90d1c2d2009-09-24 23:30:46 +00001603 IncompleteArrayType *New = new (*this, TypeAlignment)
1604 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001605
1606 IncompleteArrayTypes.InsertNode(New, InsertPos);
1607 Types.push_back(New);
1608 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001609}
1610
Steve Naroff91fcddb2007-07-18 18:00:27 +00001611/// getVectorType - Return the unique reference to a vector type of
1612/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001613QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1614 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001615 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001616
Chris Lattner76a00cf2008-04-06 22:59:24 +00001617 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001618 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001619
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001620 // Check if we've already instantiated a vector of this type.
1621 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001622 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1623 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001624 void *InsertPos = 0;
1625 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1626 return QualType(VTP, 0);
1627
1628 // If the element type isn't canonical, this won't be a canonical type either,
1629 // so fill in the canonical type field.
1630 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001631 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1632 Canonical = getVectorType(getCanonicalType(vecType),
1633 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001635 // Get the new insert position for the node we care about.
1636 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001637 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001638 }
John McCall90d1c2d2009-09-24 23:30:46 +00001639 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001640 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001641 VectorTypes.InsertNode(New, InsertPos);
1642 Types.push_back(New);
1643 return QualType(New, 0);
1644}
1645
Nate Begemance4d7fc2008-04-18 23:10:10 +00001646/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001647/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001648QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001649 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattner76a00cf2008-04-06 22:59:24 +00001651 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001652 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001653
Steve Naroff91fcddb2007-07-18 18:00:27 +00001654 // Check if we've already instantiated a vector of this type.
1655 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001656 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001657 void *InsertPos = 0;
1658 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1659 return QualType(VTP, 0);
1660
1661 // If the element type isn't canonical, this won't be a canonical type either,
1662 // so fill in the canonical type field.
1663 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001664 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001665 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001666
Steve Naroff91fcddb2007-07-18 18:00:27 +00001667 // Get the new insert position for the node we care about.
1668 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001669 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001670 }
John McCall90d1c2d2009-09-24 23:30:46 +00001671 ExtVectorType *New = new (*this, TypeAlignment)
1672 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001673 VectorTypes.InsertNode(New, InsertPos);
1674 Types.push_back(New);
1675 return QualType(New, 0);
1676}
1677
Mike Stump11289f42009-09-09 15:08:12 +00001678QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001679 Expr *SizeExpr,
1680 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001681 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001682 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001683 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregor352169a2009-07-31 03:54:25 +00001685 void *InsertPos = 0;
1686 DependentSizedExtVectorType *Canon
1687 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1688 DependentSizedExtVectorType *New;
1689 if (Canon) {
1690 // We already have a canonical version of this array type; use it as
1691 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001692 New = new (*this, TypeAlignment)
1693 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1694 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001695 } else {
1696 QualType CanonVecTy = getCanonicalType(vecType);
1697 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001698 New = new (*this, TypeAlignment)
1699 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1700 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001701
1702 DependentSizedExtVectorType *CanonCheck
1703 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1704 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1705 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001706 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1707 } else {
1708 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1709 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001710 New = new (*this, TypeAlignment)
1711 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001712 }
1713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
Douglas Gregor758a8692009-06-17 21:51:59 +00001715 Types.push_back(New);
1716 return QualType(New, 0);
1717}
1718
Douglas Gregor8c940862010-01-18 17:14:39 +00001719static CallingConv getCanonicalCallingConv(CallingConv CC) {
1720 if (CC == CC_C)
1721 return CC_Default;
1722 return CC;
1723}
1724
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001725/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001726///
Douglas Gregor8c940862010-01-18 17:14:39 +00001727QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1728 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001729 // Unique functions, to guarantee there is only one function of a particular
1730 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001731 llvm::FoldingSetNodeID ID;
John McCallcddbad02010-02-04 05:44:44 +00001732 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Chris Lattner47955de2007-01-27 08:37:20 +00001734 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001735 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001736 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001737 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001738
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001739 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001740 if (!ResultTy.isCanonical() ||
1741 getCanonicalCallingConv(CallConv) != CallConv) {
1742 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
1743 getCanonicalCallingConv(CallConv));
Mike Stump11289f42009-09-09 15:08:12 +00001744
Chris Lattner47955de2007-01-27 08:37:20 +00001745 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001746 FunctionNoProtoType *NewIP =
1747 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001748 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001749 }
Mike Stump11289f42009-09-09 15:08:12 +00001750
John McCall90d1c2d2009-09-24 23:30:46 +00001751 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallcddbad02010-02-04 05:44:44 +00001752 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Chris Lattner47955de2007-01-27 08:37:20 +00001753 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001754 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001755 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001756}
1757
1758/// getFunctionType - Return a normal function type with a typed argument
1759/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001760QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001761 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001762 unsigned TypeQuals, bool hasExceptionSpec,
1763 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregor8c940862010-01-18 17:14:39 +00001764 const QualType *ExArray, bool NoReturn,
1765 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001766 // Unique functions, to guarantee there is only one function of a particular
1767 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001768 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001769 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001770 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallcddbad02010-02-04 05:44:44 +00001771 NumExs, ExArray, NoReturn, CallConv);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001772
1773 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001774 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001775 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001776 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001777
1778 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001779 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001780 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001781 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001782 isCanonical = false;
1783
1784 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001785 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001786 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001787 if (!isCanonical || getCanonicalCallingConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001788 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001789 CanonicalArgs.reserve(NumArgs);
1790 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001791 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001792
Chris Lattner76a00cf2008-04-06 22:59:24 +00001793 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001794 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001795 isVariadic, TypeQuals, false,
Douglas Gregor8c940862010-01-18 17:14:39 +00001796 false, 0, 0, NoReturn,
1797 getCanonicalCallingConv(CallConv));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001798
Chris Lattnerfd4de792007-01-27 01:15:32 +00001799 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001800 FunctionProtoType *NewIP =
1801 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001802 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001803 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001804
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001805 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001806 // for two variable size arrays (for parameter and exception types) at the
1807 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001808 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001809 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1810 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001811 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001812 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001813 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregor8c940862010-01-18 17:14:39 +00001814 ExArray, NumExs, Canonical, NoReturn, CallConv);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001815 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001816 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001817 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001818}
Chris Lattneref51c202006-11-10 07:17:23 +00001819
Douglas Gregor83a586e2008-04-13 21:07:44 +00001820/// getTypeDeclType - Return the unique reference to the type for the
1821/// specified type declaration.
Ted Kremenek21475702008-09-05 17:16:31 +00001822QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001823 assert(Decl && "Passed null for Decl param");
Douglas Gregor83a586e2008-04-13 21:07:44 +00001824 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001825
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001826 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001827 return getTypedefType(Typedef);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001828 else if (isa<TemplateTypeParmDecl>(Decl)) {
1829 assert(false && "Template type parameter types are always available.");
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001830 } else if (ObjCInterfaceDecl *ObjCInterface
1831 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001832 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001833
Douglas Gregor89ee6822009-02-28 01:32:25 +00001834 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek721e2392009-01-19 21:31:22 +00001835 if (PrevDecl)
1836 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff096bab72009-01-27 22:08:43 +00001837 else
John McCall90d1c2d2009-09-24 23:30:46 +00001838 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001839 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek721e2392009-01-19 21:31:22 +00001840 if (PrevDecl)
1841 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff096bab72009-01-27 22:08:43 +00001842 else
John McCall90d1c2d2009-09-24 23:30:46 +00001843 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCallb96ec562009-12-04 22:46:56 +00001844 } else if (UnresolvedUsingTypenameDecl *Using =
1845 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1846 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001847 } else
Douglas Gregor83a586e2008-04-13 21:07:44 +00001848 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001849
Ted Kremenek21475702008-09-05 17:16:31 +00001850 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001851 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001852}
1853
Chris Lattner32d920b2007-01-26 02:01:53 +00001854/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001855/// specified typename decl.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001856QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1857 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Chris Lattner76a00cf2008-04-06 22:59:24 +00001859 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001860 Decl->TypeForDecl = new(*this, TypeAlignment)
1861 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001862 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001863 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001864}
1865
John McCallcebee162009-10-18 09:09:24 +00001866/// \brief Retrieve a substitution-result type.
1867QualType
1868ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1869 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001870 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001871 && "replacement types must always be canonical");
1872
1873 llvm::FoldingSetNodeID ID;
1874 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1875 void *InsertPos = 0;
1876 SubstTemplateTypeParmType *SubstParm
1877 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1878
1879 if (!SubstParm) {
1880 SubstParm = new (*this, TypeAlignment)
1881 SubstTemplateTypeParmType(Parm, Replacement);
1882 Types.push_back(SubstParm);
1883 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1884 }
1885
1886 return QualType(SubstParm, 0);
1887}
1888
Douglas Gregoreff93e02009-02-05 23:33:38 +00001889/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001890/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001891/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001892QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001893 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00001894 IdentifierInfo *Name) {
1895 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001896 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001897 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001898 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001899 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1900
1901 if (TypeParm)
1902 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001903
Anders Carlsson90036dc2009-06-16 00:30:48 +00001904 if (Name) {
1905 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00001906 TypeParm = new (*this, TypeAlignment)
1907 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001908
1909 TemplateTypeParmType *TypeCheck
1910 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1911 assert(!TypeCheck && "Template type parameter canonical type broken");
1912 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001913 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001914 TypeParm = new (*this, TypeAlignment)
1915 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001916
1917 Types.push_back(TypeParm);
1918 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1919
1920 return QualType(TypeParm, 0);
1921}
1922
Mike Stump11289f42009-09-09 15:08:12 +00001923QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001924ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001925 const TemplateArgumentListInfo &Args,
John McCall0ad16662009-10-29 08:12:44 +00001926 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001927 unsigned NumArgs = Args.size();
1928
John McCall0ad16662009-10-29 08:12:44 +00001929 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1930 ArgVec.reserve(NumArgs);
1931 for (unsigned i = 0; i != NumArgs; ++i)
1932 ArgVec.push_back(Args[i].getArgument());
1933
1934 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1935}
1936
1937QualType
1938ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001939 const TemplateArgument *Args,
1940 unsigned NumArgs,
1941 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001942 if (!Canon.isNull())
1943 Canon = getCanonicalType(Canon);
1944 else {
1945 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001946 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1947 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1948 CanonArgs.reserve(NumArgs);
1949 for (unsigned I = 0; I != NumArgs; ++I)
1950 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1951
1952 // Determine whether this canonical template specialization type already
1953 // exists.
1954 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001955 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00001956 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001957
1958 void *InsertPos = 0;
1959 TemplateSpecializationType *Spec
1960 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001961
Douglas Gregora8e02e72009-07-28 23:00:59 +00001962 if (!Spec) {
1963 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001964 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001965 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001966 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001967 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001968 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001969 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001970 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001971 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Douglas Gregor15301382009-07-30 17:40:51 +00001974 if (Canon.isNull())
1975 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001976 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001977 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001978 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001979
Douglas Gregora8e02e72009-07-28 23:00:59 +00001980 // Allocate the (non-canonical) template specialization type, but don't
1981 // try to unique it: these types typically have location information that
1982 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001983 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001984 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001985 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001986 TemplateSpecializationType *Spec
1987 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001988 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregor8bf42052009-02-09 18:46:07 +00001990 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001991 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001992}
1993
Mike Stump11289f42009-09-09 15:08:12 +00001994QualType
Douglas Gregorf21eb492009-03-26 23:50:42 +00001995ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor52537682009-03-19 00:18:19 +00001996 QualType NamedType) {
1997 llvm::FoldingSetNodeID ID;
Douglas Gregorf21eb492009-03-26 23:50:42 +00001998 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001999
2000 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002001 QualifiedNameType *T
Douglas Gregor52537682009-03-19 00:18:19 +00002002 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2003 if (T)
2004 return QualType(T, 0);
2005
Douglas Gregorc42075a2010-02-04 18:10:26 +00002006 QualType Canon = NamedType;
2007 if (!Canon.isCanonical()) {
2008 Canon = getCanonicalType(NamedType);
2009 QualifiedNameType *CheckT
2010 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2011 assert(!CheckT && "Qualified name canonical type broken");
2012 (void)CheckT;
2013 }
2014
2015 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002016 Types.push_back(T);
2017 QualifiedNameTypes.InsertNode(T, InsertPos);
2018 return QualType(T, 0);
2019}
2020
Mike Stump11289f42009-09-09 15:08:12 +00002021QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor333489b2009-03-27 23:10:48 +00002022 const IdentifierInfo *Name,
2023 QualType Canon) {
2024 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2025
2026 if (Canon.isNull()) {
2027 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2028 if (CanonNNS != NNS)
2029 Canon = getTypenameType(CanonNNS, Name);
2030 }
2031
2032 llvm::FoldingSetNodeID ID;
2033 TypenameType::Profile(ID, NNS, Name);
2034
2035 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002036 TypenameType *T
Douglas Gregor333489b2009-03-27 23:10:48 +00002037 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2038 if (T)
2039 return QualType(T, 0);
2040
2041 T = new (*this) TypenameType(NNS, Name, Canon);
2042 Types.push_back(T);
2043 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002044 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002045}
2046
Mike Stump11289f42009-09-09 15:08:12 +00002047QualType
2048ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregordce2b622009-04-01 00:28:59 +00002049 const TemplateSpecializationType *TemplateId,
2050 QualType Canon) {
2051 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2052
Douglas Gregorc42075a2010-02-04 18:10:26 +00002053 llvm::FoldingSetNodeID ID;
2054 TypenameType::Profile(ID, NNS, TemplateId);
2055
2056 void *InsertPos = 0;
2057 TypenameType *T
2058 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2059 if (T)
2060 return QualType(T, 0);
2061
Douglas Gregordce2b622009-04-01 00:28:59 +00002062 if (Canon.isNull()) {
2063 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2064 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2065 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2066 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00002067 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00002068 assert(CanonTemplateId &&
2069 "Canonical type must also be a template specialization type");
2070 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2071 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00002072
2073 TypenameType *CheckT
2074 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2075 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00002076 }
2077
Douglas Gregordce2b622009-04-01 00:28:59 +00002078 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2079 Types.push_back(T);
2080 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002081 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002082}
2083
John McCallfcc33b02009-09-05 00:15:47 +00002084QualType
2085ASTContext::getElaboratedType(QualType UnderlyingType,
2086 ElaboratedType::TagKind Tag) {
2087 llvm::FoldingSetNodeID ID;
2088 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00002089
John McCallfcc33b02009-09-05 00:15:47 +00002090 void *InsertPos = 0;
2091 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2092 if (T)
2093 return QualType(T, 0);
2094
Douglas Gregorc42075a2010-02-04 18:10:26 +00002095 QualType Canon = UnderlyingType;
2096 if (!Canon.isCanonical()) {
2097 Canon = getCanonicalType(Canon);
2098 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2099 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2100 }
John McCallfcc33b02009-09-05 00:15:47 +00002101
2102 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2103 Types.push_back(T);
2104 ElaboratedTypes.InsertNode(T, InsertPos);
2105 return QualType(T, 0);
2106}
2107
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002108/// CmpProtocolNames - Comparison predicate for sorting protocols
2109/// alphabetically.
2110static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2111 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002112 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002113}
2114
John McCallfc93cf92009-10-22 22:37:11 +00002115static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2116 unsigned NumProtocols) {
2117 if (NumProtocols == 0) return true;
2118
2119 for (unsigned i = 1; i != NumProtocols; ++i)
2120 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2121 return false;
2122 return true;
2123}
2124
2125static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002126 unsigned &NumProtocols) {
2127 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002129 // Sort protocols, keyed by name.
2130 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2131
2132 // Remove duplicates.
2133 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2134 NumProtocols = ProtocolsEnd-Protocols;
2135}
2136
Steve Narofffb4330f2009-06-17 22:40:22 +00002137/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2138/// the given interface decl and the conforming protocol list.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002139QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump11289f42009-09-09 15:08:12 +00002140 ObjCProtocolDecl **Protocols,
Steve Narofffb4330f2009-06-17 22:40:22 +00002141 unsigned NumProtocols) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002142 llvm::FoldingSetNodeID ID;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002143 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002144
2145 void *InsertPos = 0;
2146 if (ObjCObjectPointerType *QT =
2147 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2148 return QualType(QT, 0);
2149
John McCallfc93cf92009-10-22 22:37:11 +00002150 // Sort the protocol list alphabetically to canonicalize it.
2151 QualType Canonical;
2152 if (!InterfaceT.isCanonical() ||
2153 !areSortedAndUniqued(Protocols, NumProtocols)) {
2154 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2155 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2156 unsigned UniqueCount = NumProtocols;
2157
2158 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2159 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2160
2161 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2162 &Sorted[0], UniqueCount);
2163 } else {
2164 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2165 Protocols, NumProtocols);
2166 }
2167
2168 // Regenerate InsertPos.
2169 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 }
2171
Steve Narofffb4330f2009-06-17 22:40:22 +00002172 // No Match;
John McCall90d1c2d2009-09-24 23:30:46 +00002173 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
Ted Kremenek819e8732010-01-21 19:22:34 +00002174 ObjCObjectPointerType(*this, Canonical, InterfaceT, Protocols,
2175 NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002176
Steve Narofffb4330f2009-06-17 22:40:22 +00002177 Types.push_back(QType);
2178 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2179 return QualType(QType, 0);
2180}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002181
Steve Naroffc277ad12009-07-18 15:33:26 +00002182/// getObjCInterfaceType - Return the unique reference to the type for the
2183/// specified ObjC interface decl. The list of protocols is optional.
2184QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002185 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002186 llvm::FoldingSetNodeID ID;
Steve Naroffc277ad12009-07-18 15:33:26 +00002187 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002189 void *InsertPos = 0;
Steve Naroffc277ad12009-07-18 15:33:26 +00002190 if (ObjCInterfaceType *QT =
2191 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002192 return QualType(QT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCallfc93cf92009-10-22 22:37:11 +00002194 // Sort the protocol list alphabetically to canonicalize it.
2195 QualType Canonical;
2196 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2197 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2198 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2199
2200 unsigned UniqueCount = NumProtocols;
2201 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2202
2203 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2204
2205 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2206 }
2207
John McCall90d1c2d2009-09-24 23:30:46 +00002208 ObjCInterfaceType *QType = new (*this, TypeAlignment)
Ted Kremenek819e8732010-01-21 19:22:34 +00002209 ObjCInterfaceType(*this, Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall90d1c2d2009-09-24 23:30:46 +00002210 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002211
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002212 Types.push_back(QType);
Steve Naroffc277ad12009-07-18 15:33:26 +00002213 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002214 return QualType(QType, 0);
2215}
2216
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002217/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2218/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002219/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002220/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002221/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002222QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002223 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002224 if (tofExpr->isTypeDependent()) {
2225 llvm::FoldingSetNodeID ID;
2226 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002227
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002228 void *InsertPos = 0;
2229 DependentTypeOfExprType *Canon
2230 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2231 if (Canon) {
2232 // We already have a "canonical" version of an identical, dependent
2233 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002234 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002235 QualType((TypeOfExprType*)Canon, 0));
2236 }
2237 else {
2238 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002239 Canon
2240 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002241 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2242 toe = Canon;
2243 }
2244 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002245 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002246 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002247 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002248 Types.push_back(toe);
2249 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002250}
2251
Steve Naroffa773cd52007-08-01 18:02:17 +00002252/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2253/// TypeOfType AST's. The only motivation to unique these nodes would be
2254/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002255/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002256/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002257QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002258 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002259 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002260 Types.push_back(tot);
2261 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002262}
2263
Anders Carlssonad6bd352009-06-24 21:24:56 +00002264/// getDecltypeForExpr - Given an expr, will return the decltype for that
2265/// expression, according to the rules in C++0x [dcl.type.simple]p4
2266static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002267 if (e->isTypeDependent())
2268 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002269
Anders Carlssonad6bd352009-06-24 21:24:56 +00002270 // If e is an id expression or a class member access, decltype(e) is defined
2271 // as the type of the entity named by e.
2272 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2273 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2274 return VD->getType();
2275 }
2276 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2277 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2278 return FD->getType();
2279 }
2280 // If e is a function call or an invocation of an overloaded operator,
2281 // (parentheses around e are ignored), decltype(e) is defined as the
2282 // return type of that function.
2283 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2284 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Anders Carlssonad6bd352009-06-24 21:24:56 +00002286 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002287
2288 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002289 // defined as T&, otherwise decltype(e) is defined as T.
2290 if (e->isLvalue(Context) == Expr::LV_Valid)
2291 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002292
Anders Carlssonad6bd352009-06-24 21:24:56 +00002293 return T;
2294}
2295
Anders Carlsson81df7b82009-06-24 19:06:50 +00002296/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2297/// DecltypeType AST's. The only motivation to unique these nodes would be
2298/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002299/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002300/// on canonical type's (which are always unique).
2301QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002302 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002303 if (e->isTypeDependent()) {
2304 llvm::FoldingSetNodeID ID;
2305 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002306
Douglas Gregora21f6c32009-07-30 23:36:40 +00002307 void *InsertPos = 0;
2308 DependentDecltypeType *Canon
2309 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2310 if (Canon) {
2311 // We already have a "canonical" version of an equivalent, dependent
2312 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002313 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002314 QualType((DecltypeType*)Canon, 0));
2315 }
2316 else {
2317 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002318 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002319 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2320 dt = Canon;
2321 }
2322 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002323 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002324 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002325 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002326 Types.push_back(dt);
2327 return QualType(dt, 0);
2328}
2329
Chris Lattnerfb072462007-01-23 05:45:31 +00002330/// getTagDeclType - Return the unique reference to the type for the
2331/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002332QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002333 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002334 // FIXME: What is the design on getTagDeclType when it requires casting
2335 // away const? mutable?
2336 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002337}
2338
Mike Stump11289f42009-09-09 15:08:12 +00002339/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2340/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2341/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002342CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002343 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002344}
Chris Lattnerfb072462007-01-23 05:45:31 +00002345
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002346/// getSignedWCharType - Return the type of "signed wchar_t".
2347/// Used when in C++, as a GCC extension.
2348QualType ASTContext::getSignedWCharType() const {
2349 // FIXME: derive from "Target" ?
2350 return WCharTy;
2351}
2352
2353/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2354/// Used when in C++, as a GCC extension.
2355QualType ASTContext::getUnsignedWCharType() const {
2356 // FIXME: derive from "Target" ?
2357 return UnsignedIntTy;
2358}
2359
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002360/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2361/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2362QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002363 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002364}
2365
Chris Lattnera21ad802008-04-02 05:18:44 +00002366//===----------------------------------------------------------------------===//
2367// Type Operators
2368//===----------------------------------------------------------------------===//
2369
John McCallfc93cf92009-10-22 22:37:11 +00002370CanQualType ASTContext::getCanonicalParamType(QualType T) {
2371 // Push qualifiers into arrays, and then discard any remaining
2372 // qualifiers.
2373 T = getCanonicalType(T);
2374 const Type *Ty = T.getTypePtr();
2375
2376 QualType Result;
2377 if (isa<ArrayType>(Ty)) {
2378 Result = getArrayDecayedType(QualType(Ty,0));
2379 } else if (isa<FunctionType>(Ty)) {
2380 Result = getPointerType(QualType(Ty, 0));
2381 } else {
2382 Result = QualType(Ty, 0);
2383 }
2384
2385 return CanQualType::CreateUnsafe(Result);
2386}
2387
Chris Lattnered0d0792008-04-06 22:41:35 +00002388/// getCanonicalType - Return the canonical (structural) type corresponding to
2389/// the specified potentially non-canonical type. The non-canonical version
2390/// of a type may have many "decorated" versions of types. Decorators can
2391/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2392/// to be free of any of these, allowing two canonical types to be compared
2393/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002394CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002395 QualifierCollector Quals;
2396 const Type *Ptr = Quals.strip(T);
2397 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002398
John McCall8ccfcb52009-09-24 19:53:00 +00002399 // The canonical internal type will be the canonical type *except*
2400 // that we push type qualifiers down through array types.
2401
2402 // If there are no new qualifiers to push down, stop here.
2403 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002404 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002405
John McCall8ccfcb52009-09-24 19:53:00 +00002406 // If the type qualifiers are on an array type, get the canonical
2407 // type of the array with the qualifiers applied to the element
2408 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002409 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2410 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002411 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002412
Chris Lattner7adf0762008-08-04 07:31:14 +00002413 // Get the canonical version of the element with the extra qualifiers on it.
2414 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002415 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002416 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002417
Chris Lattner7adf0762008-08-04 07:31:14 +00002418 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002419 return CanQualType::CreateUnsafe(
2420 getConstantArrayType(NewEltTy, CAT->getSize(),
2421 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002422 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002423 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002424 return CanQualType::CreateUnsafe(
2425 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002426 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregor4619e432008-12-05 23:32:09 +00002428 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002429 return CanQualType::CreateUnsafe(
2430 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002431 DSAT->getSizeExpr() ?
2432 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002433 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002434 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002435 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002436
Chris Lattner7adf0762008-08-04 07:31:14 +00002437 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002438 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002439 VAT->getSizeExpr() ?
2440 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002441 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002442 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002443 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002444}
2445
Chandler Carruth607f38e2009-12-29 07:16:59 +00002446QualType ASTContext::getUnqualifiedArrayType(QualType T,
2447 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002448 Quals = T.getQualifiers();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002449 if (!isa<ArrayType>(T)) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002450 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002451 }
2452
Chandler Carruth607f38e2009-12-29 07:16:59 +00002453 const ArrayType *AT = cast<ArrayType>(T);
2454 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002455 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002456 if (Elt == UnqualElt)
2457 return T;
2458
2459 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2460 return getConstantArrayType(UnqualElt, CAT->getSize(),
2461 CAT->getSizeModifier(), 0);
2462 }
2463
2464 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2465 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2466 }
2467
2468 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2469 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2470 DSAT->getSizeModifier(), 0,
2471 SourceRange());
2472}
2473
John McCall847e2a12009-11-24 18:42:40 +00002474DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2475 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2476 return TD->getDeclName();
2477
2478 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2479 if (DTN->isIdentifier()) {
2480 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2481 } else {
2482 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2483 }
2484 }
2485
John McCalld28ae272009-12-02 08:04:21 +00002486 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2487 assert(Storage);
2488 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002489}
2490
Douglas Gregor6bc50582009-05-07 06:41:52 +00002491TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2492 // If this template name refers to a template, the canonical
2493 // template name merely stores the template itself.
2494 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002495 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002496
John McCalld28ae272009-12-02 08:04:21 +00002497 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002498
Douglas Gregor6bc50582009-05-07 06:41:52 +00002499 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2500 assert(DTN && "Non-dependent template names must refer to template decls.");
2501 return DTN->CanonicalTemplateName;
2502}
2503
Douglas Gregoradee3e32009-11-11 23:06:43 +00002504bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2505 X = getCanonicalTemplateName(X);
2506 Y = getCanonicalTemplateName(Y);
2507 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2508}
2509
Mike Stump11289f42009-09-09 15:08:12 +00002510TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002511ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2512 switch (Arg.getKind()) {
2513 case TemplateArgument::Null:
2514 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregora8e02e72009-07-28 23:00:59 +00002516 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002517 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002518
Douglas Gregora8e02e72009-07-28 23:00:59 +00002519 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002520 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002521
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002522 case TemplateArgument::Template:
2523 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2524
Douglas Gregora8e02e72009-07-28 23:00:59 +00002525 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002526 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002527 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002528
Douglas Gregora8e02e72009-07-28 23:00:59 +00002529 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002530 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregora8e02e72009-07-28 23:00:59 +00002532 case TemplateArgument::Pack: {
2533 // FIXME: Allocate in ASTContext
2534 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2535 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002536 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002537 AEnd = Arg.pack_end();
2538 A != AEnd; (void)++A, ++Idx)
2539 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregora8e02e72009-07-28 23:00:59 +00002541 TemplateArgument Result;
2542 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2543 return Result;
2544 }
2545 }
2546
2547 // Silence GCC warning
2548 assert(false && "Unhandled template argument kind");
2549 return TemplateArgument();
2550}
2551
Douglas Gregor333489b2009-03-27 23:10:48 +00002552NestedNameSpecifier *
2553ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002554 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002555 return 0;
2556
2557 switch (NNS->getKind()) {
2558 case NestedNameSpecifier::Identifier:
2559 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002560 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002561 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2562 NNS->getAsIdentifier());
2563
2564 case NestedNameSpecifier::Namespace:
2565 // A namespace is canonical; build a nested-name-specifier with
2566 // this namespace and no prefix.
2567 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2568
2569 case NestedNameSpecifier::TypeSpec:
2570 case NestedNameSpecifier::TypeSpecWithTemplate: {
2571 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002572 return NestedNameSpecifier::Create(*this, 0,
2573 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002574 T.getTypePtr());
2575 }
2576
2577 case NestedNameSpecifier::Global:
2578 // The global specifier is canonical and unique.
2579 return NNS;
2580 }
2581
2582 // Required to silence a GCC warning
2583 return 0;
2584}
2585
Chris Lattner7adf0762008-08-04 07:31:14 +00002586
2587const ArrayType *ASTContext::getAsArrayType(QualType T) {
2588 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002589 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002590 // Handle the common positive case fast.
2591 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2592 return AT;
2593 }
Mike Stump11289f42009-09-09 15:08:12 +00002594
John McCall8ccfcb52009-09-24 19:53:00 +00002595 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002596 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002597 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002598 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002599
John McCall8ccfcb52009-09-24 19:53:00 +00002600 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002601 // implements C99 6.7.3p8: "If the specification of an array type includes
2602 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002603
Chris Lattner7adf0762008-08-04 07:31:14 +00002604 // If we get here, we either have type qualifiers on the type, or we have
2605 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002606 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002607
John McCall8ccfcb52009-09-24 19:53:00 +00002608 QualifierCollector Qs;
2609 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002610
Chris Lattner7adf0762008-08-04 07:31:14 +00002611 // If we have a simple case, just return now.
2612 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002613 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002614 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002615
Chris Lattner7adf0762008-08-04 07:31:14 +00002616 // Otherwise, we have an array and we have qualifiers on it. Push the
2617 // qualifiers into the array element type and return a new array type.
2618 // Get the canonical version of the element with the extra qualifiers on it.
2619 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002620 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002621
Chris Lattner7adf0762008-08-04 07:31:14 +00002622 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2623 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2624 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002625 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002626 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2627 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2628 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002629 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002630
Mike Stump11289f42009-09-09 15:08:12 +00002631 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002632 = dyn_cast<DependentSizedArrayType>(ATy))
2633 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002634 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002635 DSAT->getSizeExpr() ?
2636 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002637 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002638 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002639 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002640
Chris Lattner7adf0762008-08-04 07:31:14 +00002641 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002642 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002643 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002644 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002645 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002646 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002647 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002648}
2649
2650
Chris Lattnera21ad802008-04-02 05:18:44 +00002651/// getArrayDecayedType - Return the properly qualified result of decaying the
2652/// specified array type to a pointer. This operation is non-trivial when
2653/// handling typedefs etc. The canonical type of "T" must be an array type,
2654/// this returns a pointer to a properly qualified element of the array.
2655///
2656/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2657QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002658 // Get the element type with 'getAsArrayType' so that we don't lose any
2659 // typedefs in the element type of the array. This also handles propagation
2660 // of type qualifiers from the array type into the element type if present
2661 // (C99 6.7.3p8).
2662 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2663 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002664
Chris Lattner7adf0762008-08-04 07:31:14 +00002665 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002666
2667 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002668 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002669}
2670
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002671QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002672 QualifierCollector Qs;
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002673 while (true) {
John McCall8ccfcb52009-09-24 19:53:00 +00002674 const Type *UT = Qs.strip(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002675 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2676 QT = AT->getElementType();
Mike Stumpea086c72009-07-25 23:24:03 +00002677 } else {
John McCall8ccfcb52009-09-24 19:53:00 +00002678 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002679 }
2680 }
2681}
2682
Anders Carlsson4bf82142009-09-25 01:23:32 +00002683QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2684 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002685
Anders Carlsson4bf82142009-09-25 01:23:32 +00002686 if (const ArrayType *AT = getAsArrayType(ElemTy))
2687 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Anders Carlssone0808df2008-12-21 03:44:36 +00002689 return ElemTy;
2690}
2691
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002692/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002693uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002694ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2695 uint64_t ElementCount = 1;
2696 do {
2697 ElementCount *= CA->getSize().getZExtValue();
2698 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2699 } while (CA);
2700 return ElementCount;
2701}
2702
Steve Naroff0af91202007-04-27 21:51:21 +00002703/// getFloatingRank - Return a relative rank for floating point types.
2704/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002705static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002706 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002707 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002708
John McCall9dd450b2009-09-21 23:43:11 +00002709 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2710 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002711 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002712 case BuiltinType::Float: return FloatRank;
2713 case BuiltinType::Double: return DoubleRank;
2714 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002715 }
2716}
2717
Mike Stump11289f42009-09-09 15:08:12 +00002718/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2719/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002720/// 'typeDomain' is a real floating point or complex type.
2721/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002722QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2723 QualType Domain) const {
2724 FloatingRank EltRank = getFloatingRank(Size);
2725 if (Domain->isComplexType()) {
2726 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002727 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002728 case FloatRank: return FloatComplexTy;
2729 case DoubleRank: return DoubleComplexTy;
2730 case LongDoubleRank: return LongDoubleComplexTy;
2731 }
Steve Naroff0af91202007-04-27 21:51:21 +00002732 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002733
2734 assert(Domain->isRealFloatingType() && "Unknown domain!");
2735 switch (EltRank) {
2736 default: assert(0 && "getFloatingRank(): illegal value for rank");
2737 case FloatRank: return FloatTy;
2738 case DoubleRank: return DoubleTy;
2739 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002740 }
Steve Naroffe4718892007-04-27 18:30:00 +00002741}
2742
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002743/// getFloatingTypeOrder - Compare the rank of the two specified floating
2744/// point types, ignoring the domain of the type (i.e. 'double' ==
2745/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002746/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002747int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2748 FloatingRank LHSR = getFloatingRank(LHS);
2749 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002750
Chris Lattnerb90739d2008-04-06 23:38:49 +00002751 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002752 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002753 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002754 return 1;
2755 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002756}
2757
Chris Lattner76a00cf2008-04-06 22:59:24 +00002758/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2759/// routine will assert if passed a built-in type that isn't an integer or enum,
2760/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002761unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002762 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002763 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002764 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002765
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002766 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2767 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2768
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002769 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2770 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2771
2772 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2773 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2774
Chris Lattner76a00cf2008-04-06 22:59:24 +00002775 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002776 default: assert(0 && "getIntegerRank(): not a built-in integer");
2777 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002778 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002779 case BuiltinType::Char_S:
2780 case BuiltinType::Char_U:
2781 case BuiltinType::SChar:
2782 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002783 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002784 case BuiltinType::Short:
2785 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002786 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002787 case BuiltinType::Int:
2788 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002789 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002790 case BuiltinType::Long:
2791 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002792 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002793 case BuiltinType::LongLong:
2794 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002795 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002796 case BuiltinType::Int128:
2797 case BuiltinType::UInt128:
2798 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002799 }
2800}
2801
Eli Friedman629ffb92009-08-20 04:21:42 +00002802/// \brief Whether this is a promotable bitfield reference according
2803/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2804///
2805/// \returns the type this bit-field will promote to, or NULL if no
2806/// promotion occurs.
2807QualType ASTContext::isPromotableBitField(Expr *E) {
2808 FieldDecl *Field = E->getBitField();
2809 if (!Field)
2810 return QualType();
2811
2812 QualType FT = Field->getType();
2813
2814 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2815 uint64_t BitWidth = BitWidthAP.getZExtValue();
2816 uint64_t IntSize = getTypeSize(IntTy);
2817 // GCC extension compatibility: if the bit-field size is less than or equal
2818 // to the size of int, it gets promoted no matter what its type is.
2819 // For instance, unsigned long bf : 4 gets promoted to signed int.
2820 if (BitWidth < IntSize)
2821 return IntTy;
2822
2823 if (BitWidth == IntSize)
2824 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2825
2826 // Types bigger than int are not subject to promotions, and therefore act
2827 // like the base type.
2828 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2829 // is ridiculous.
2830 return QualType();
2831}
2832
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002833/// getPromotedIntegerType - Returns the type that Promotable will
2834/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2835/// integer type.
2836QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2837 assert(!Promotable.isNull());
2838 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002839 if (const EnumType *ET = Promotable->getAs<EnumType>())
2840 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002841 if (Promotable->isSignedIntegerType())
2842 return IntTy;
2843 uint64_t PromotableSize = getTypeSize(Promotable);
2844 uint64_t IntSize = getTypeSize(IntTy);
2845 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2846 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2847}
2848
Mike Stump11289f42009-09-09 15:08:12 +00002849/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002850/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002851/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002852int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002853 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2854 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002855 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002856
Chris Lattner76a00cf2008-04-06 22:59:24 +00002857 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2858 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002859
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002860 unsigned LHSRank = getIntegerRank(LHSC);
2861 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002862
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002863 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2864 if (LHSRank == RHSRank) return 0;
2865 return LHSRank > RHSRank ? 1 : -1;
2866 }
Mike Stump11289f42009-09-09 15:08:12 +00002867
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002868 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2869 if (LHSUnsigned) {
2870 // If the unsigned [LHS] type is larger, return it.
2871 if (LHSRank >= RHSRank)
2872 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002873
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002874 // If the signed type can represent all values of the unsigned type, it
2875 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002876 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002877 return -1;
2878 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002879
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002880 // If the unsigned [RHS] type is larger, return it.
2881 if (RHSRank >= LHSRank)
2882 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002883
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002884 // If the signed type can represent all values of the unsigned type, it
2885 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002886 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002887 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002888}
Anders Carlsson98f07902007-08-17 05:31:46 +00002889
Anders Carlsson6d417272009-11-14 21:45:58 +00002890static RecordDecl *
2891CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2892 SourceLocation L, IdentifierInfo *Id) {
2893 if (Ctx.getLangOptions().CPlusPlus)
2894 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2895 else
2896 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2897}
2898
Mike Stump11289f42009-09-09 15:08:12 +00002899// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002900QualType ASTContext::getCFConstantStringType() {
2901 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002902 CFConstantStringTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00002903 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2904 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002905 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002906
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002907 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002908
Anders Carlsson98f07902007-08-17 05:31:46 +00002909 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002910 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002911 // int flags;
2912 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002913 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002914 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002915 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002916 FieldTypes[3] = LongTy;
2917
Anders Carlsson98f07902007-08-17 05:31:46 +00002918 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002919 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002920 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002921 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002922 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002923 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002924 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002925 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002926 }
2927
2928 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson98f07902007-08-17 05:31:46 +00002929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Anders Carlsson98f07902007-08-17 05:31:46 +00002931 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002932}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002933
Douglas Gregor512b0772009-04-23 22:29:11 +00002934void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002935 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002936 assert(Rec && "Invalid CFConstantStringType");
2937 CFConstantStringTypeDecl = Rec->getDecl();
2938}
2939
Mike Stump11289f42009-09-09 15:08:12 +00002940QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002941 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00002942 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00002943 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2944 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00002945 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002946
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002947 QualType FieldTypes[] = {
2948 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00002949 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002950 getPointerType(UnsignedLongTy),
2951 getConstantArrayType(UnsignedLongTy,
2952 llvm::APInt(32, 5), ArrayType::Normal, 0)
2953 };
Mike Stump11289f42009-09-09 15:08:12 +00002954
Douglas Gregor91f84212008-12-11 16:49:14 +00002955 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002956 FieldDecl *Field = FieldDecl::Create(*this,
2957 ObjCFastEnumerationStateTypeDecl,
2958 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002959 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002960 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002961 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002962 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002963 }
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregor91f84212008-12-11 16:49:14 +00002965 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002966 }
Mike Stump11289f42009-09-09 15:08:12 +00002967
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002968 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2969}
2970
Mike Stumpd0153282009-10-20 02:12:22 +00002971QualType ASTContext::getBlockDescriptorType() {
2972 if (BlockDescriptorType)
2973 return getTagDeclType(BlockDescriptorType);
2974
2975 RecordDecl *T;
2976 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00002977 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2978 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00002979 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002980
2981 QualType FieldTypes[] = {
2982 UnsignedLongTy,
2983 UnsignedLongTy,
2984 };
2985
2986 const char *FieldNames[] = {
2987 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002988 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00002989 };
2990
2991 for (size_t i = 0; i < 2; ++i) {
2992 FieldDecl *Field = FieldDecl::Create(*this,
2993 T,
2994 SourceLocation(),
2995 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002996 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00002997 /*BitWidth=*/0,
2998 /*Mutable=*/false);
2999 T->addDecl(Field);
3000 }
3001
3002 T->completeDefinition(*this);
3003
3004 BlockDescriptorType = T;
3005
3006 return getTagDeclType(BlockDescriptorType);
3007}
3008
3009void ASTContext::setBlockDescriptorType(QualType T) {
3010 const RecordType *Rec = T->getAs<RecordType>();
3011 assert(Rec && "Invalid BlockDescriptorType");
3012 BlockDescriptorType = Rec->getDecl();
3013}
3014
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003015QualType ASTContext::getBlockDescriptorExtendedType() {
3016 if (BlockDescriptorExtendedType)
3017 return getTagDeclType(BlockDescriptorExtendedType);
3018
3019 RecordDecl *T;
3020 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003021 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3022 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003023 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003024
3025 QualType FieldTypes[] = {
3026 UnsignedLongTy,
3027 UnsignedLongTy,
3028 getPointerType(VoidPtrTy),
3029 getPointerType(VoidPtrTy)
3030 };
3031
3032 const char *FieldNames[] = {
3033 "reserved",
3034 "Size",
3035 "CopyFuncPtr",
3036 "DestroyFuncPtr"
3037 };
3038
3039 for (size_t i = 0; i < 4; ++i) {
3040 FieldDecl *Field = FieldDecl::Create(*this,
3041 T,
3042 SourceLocation(),
3043 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003044 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003045 /*BitWidth=*/0,
3046 /*Mutable=*/false);
3047 T->addDecl(Field);
3048 }
3049
3050 T->completeDefinition(*this);
3051
3052 BlockDescriptorExtendedType = T;
3053
3054 return getTagDeclType(BlockDescriptorExtendedType);
3055}
3056
3057void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3058 const RecordType *Rec = T->getAs<RecordType>();
3059 assert(Rec && "Invalid BlockDescriptorType");
3060 BlockDescriptorExtendedType = Rec->getDecl();
3061}
3062
Mike Stump94967902009-10-21 18:16:27 +00003063bool ASTContext::BlockRequiresCopying(QualType Ty) {
3064 if (Ty->isBlockPointerType())
3065 return true;
3066 if (isObjCNSObjectType(Ty))
3067 return true;
3068 if (Ty->isObjCObjectPointerType())
3069 return true;
3070 return false;
3071}
3072
3073QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3074 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003075 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003076 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003077 // unsigned int __flags;
3078 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003079 // void *__copy_helper; // as needed
3080 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003081 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003082 // } *
3083
Mike Stump94967902009-10-21 18:16:27 +00003084 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3085
3086 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003087 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003088 llvm::SmallString<36> Name;
3089 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3090 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003091 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003092 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3093 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003094 T->startDefinition();
3095 QualType Int32Ty = IntTy;
3096 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3097 QualType FieldTypes[] = {
3098 getPointerType(VoidPtrTy),
3099 getPointerType(getTagDeclType(T)),
3100 Int32Ty,
3101 Int32Ty,
3102 getPointerType(VoidPtrTy),
3103 getPointerType(VoidPtrTy),
3104 Ty
3105 };
3106
3107 const char *FieldNames[] = {
3108 "__isa",
3109 "__forwarding",
3110 "__flags",
3111 "__size",
3112 "__copy_helper",
3113 "__destroy_helper",
3114 DeclName,
3115 };
3116
3117 for (size_t i = 0; i < 7; ++i) {
3118 if (!HasCopyAndDispose && i >=4 && i <= 5)
3119 continue;
3120 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3121 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003122 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003123 /*BitWidth=*/0, /*Mutable=*/false);
3124 T->addDecl(Field);
3125 }
3126
3127 T->completeDefinition(*this);
3128
3129 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003130}
3131
3132
3133QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003134 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003135 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003136 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003137 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003138 llvm::SmallString<36> Name;
3139 llvm::raw_svector_ostream(Name) << "__block_literal_"
3140 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003141 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003142 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3143 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003144 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003145 QualType FieldTypes[] = {
3146 getPointerType(VoidPtrTy),
3147 IntTy,
3148 IntTy,
3149 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003150 (BlockHasCopyDispose ?
3151 getPointerType(getBlockDescriptorExtendedType()) :
3152 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003153 };
3154
3155 const char *FieldNames[] = {
3156 "__isa",
3157 "__flags",
3158 "__reserved",
3159 "__FuncPtr",
3160 "__descriptor"
3161 };
3162
3163 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003164 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003165 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003166 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003167 /*BitWidth=*/0, /*Mutable=*/false);
3168 T->addDecl(Field);
3169 }
3170
3171 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3172 const Expr *E = BlockDeclRefDecls[i];
3173 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3174 clang::IdentifierInfo *Name = 0;
3175 if (BDRE) {
3176 const ValueDecl *D = BDRE->getDecl();
3177 Name = &Idents.get(D->getName());
3178 }
3179 QualType FieldType = E->getType();
3180
3181 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003182 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3183 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003184
3185 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003186 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003187 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpd0153282009-10-20 02:12:22 +00003188 T->addDecl(Field);
3189 }
3190
3191 T->completeDefinition(*this);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003192
3193 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003194}
3195
Douglas Gregor512b0772009-04-23 22:29:11 +00003196void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003197 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003198 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3199 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3200}
3201
Anders Carlsson18acd442007-10-29 06:33:42 +00003202// This returns true if a type has been typedefed to BOOL:
3203// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003204static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003205 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003206 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3207 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003208
Anders Carlssond8499822007-10-29 05:01:08 +00003209 return false;
3210}
3211
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003212/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003213/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003214CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003215 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003216
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003217 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003218 if (sz.isPositive() && type->isIntegralType())
3219 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003220 // Treat arrays as pointers, since that's how they're passed in.
3221 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003222 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003223 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003224}
3225
3226static inline
3227std::string charUnitsToString(const CharUnits &CU) {
3228 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003229}
3230
David Chisnall950a9512009-11-17 19:33:30 +00003231/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3232/// declaration.
3233void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3234 std::string& S) {
3235 const BlockDecl *Decl = Expr->getBlockDecl();
3236 QualType BlockTy =
3237 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3238 // Encode result type.
3239 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3240 // Compute size of all parameters.
3241 // Start with computing size of a pointer in number of bytes.
3242 // FIXME: There might(should) be a better way of doing this computation!
3243 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003244 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3245 CharUnits ParmOffset = PtrSize;
David Chisnall950a9512009-11-17 19:33:30 +00003246 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3247 E = Decl->param_end(); PI != E; ++PI) {
3248 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003249 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003250 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003251 ParmOffset += sz;
3252 }
3253 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003254 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003255 // Block pointer and offset.
3256 S += "@?0";
3257 ParmOffset = PtrSize;
3258
3259 // Argument types.
3260 ParmOffset = PtrSize;
3261 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3262 Decl->param_end(); PI != E; ++PI) {
3263 ParmVarDecl *PVDecl = *PI;
3264 QualType PType = PVDecl->getOriginalType();
3265 if (const ArrayType *AT =
3266 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3267 // Use array's original type only if it has known number of
3268 // elements.
3269 if (!isa<ConstantArrayType>(AT))
3270 PType = PVDecl->getType();
3271 } else if (PType->isFunctionType())
3272 PType = PVDecl->getType();
3273 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003274 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003275 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003276 }
3277}
3278
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003279/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003280/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003281void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003282 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003283 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003284 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003285 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003286 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003287 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003288 // Compute size of all parameters.
3289 // Start with computing size of a pointer in number of bytes.
3290 // FIXME: There might(should) be a better way of doing this computation!
3291 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003292 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003293 // The first two arguments (self and _cmd) are pointers; account for
3294 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003295 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003296 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3297 E = Decl->param_end(); PI != E; ++PI) {
3298 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003299 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003300 assert (sz.isPositive() &&
3301 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003302 ParmOffset += sz;
3303 }
Ken Dyck40775002010-01-11 17:06:35 +00003304 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003305 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003306 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003308 // Argument types.
3309 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003310 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3311 E = Decl->param_end(); PI != E; ++PI) {
3312 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003313 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003314 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003315 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3316 // Use array's original type only if it has known number of
3317 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003318 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003319 PType = PVDecl->getType();
3320 } else if (PType->isFunctionType())
3321 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003322 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003323 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003324 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003325 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003326 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003327 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003328 }
3329}
3330
Daniel Dunbar4932b362008-08-28 04:38:10 +00003331/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003332/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003333/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3334/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003335/// Property attributes are stored as a comma-delimited C string. The simple
3336/// attributes readonly and bycopy are encoded as single characters. The
3337/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3338/// encoded as single characters, followed by an identifier. Property types
3339/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003340/// these attributes are defined by the following enumeration:
3341/// @code
3342/// enum PropertyAttributes {
3343/// kPropertyReadOnly = 'R', // property is read-only.
3344/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3345/// kPropertyByref = '&', // property is a reference to the value last assigned
3346/// kPropertyDynamic = 'D', // property is dynamic
3347/// kPropertyGetter = 'G', // followed by getter selector name
3348/// kPropertySetter = 'S', // followed by setter selector name
3349/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3350/// kPropertyType = 't' // followed by old-style type encoding.
3351/// kPropertyWeak = 'W' // 'weak' property
3352/// kPropertyStrong = 'P' // property GC'able
3353/// kPropertyNonAtomic = 'N' // property non-atomic
3354/// };
3355/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003356void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003357 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003358 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003359 // Collect information from the property implementation decl(s).
3360 bool Dynamic = false;
3361 ObjCPropertyImplDecl *SynthesizePID = 0;
3362
3363 // FIXME: Duplicated code due to poor abstraction.
3364 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003365 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003366 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3367 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003368 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003369 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003370 ObjCPropertyImplDecl *PID = *i;
3371 if (PID->getPropertyDecl() == PD) {
3372 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3373 Dynamic = true;
3374 } else {
3375 SynthesizePID = PID;
3376 }
3377 }
3378 }
3379 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003380 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003381 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003382 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003383 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003384 ObjCPropertyImplDecl *PID = *i;
3385 if (PID->getPropertyDecl() == PD) {
3386 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3387 Dynamic = true;
3388 } else {
3389 SynthesizePID = PID;
3390 }
3391 }
Mike Stump11289f42009-09-09 15:08:12 +00003392 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003393 }
3394 }
3395
3396 // FIXME: This is not very efficient.
3397 S = "T";
3398
3399 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003400 // GCC has some special rules regarding encoding of properties which
3401 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003402 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003403 true /* outermost type */,
3404 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003405
3406 if (PD->isReadOnly()) {
3407 S += ",R";
3408 } else {
3409 switch (PD->getSetterKind()) {
3410 case ObjCPropertyDecl::Assign: break;
3411 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003412 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003413 }
3414 }
3415
3416 // It really isn't clear at all what this means, since properties
3417 // are "dynamic by default".
3418 if (Dynamic)
3419 S += ",D";
3420
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003421 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3422 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003423
Daniel Dunbar4932b362008-08-28 04:38:10 +00003424 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3425 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003426 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003427 }
3428
3429 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3430 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003431 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003432 }
3433
3434 if (SynthesizePID) {
3435 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3436 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003437 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003438 }
3439
3440 // FIXME: OBJCGC: weak & strong
3441}
3442
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003443/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003444/// Another legacy compatibility encoding: 32-bit longs are encoded as
3445/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003446/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3447///
3448void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003449 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003450 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003451 if (BT->getKind() == BuiltinType::ULong &&
3452 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003453 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003454 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003455 if (BT->getKind() == BuiltinType::Long &&
3456 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003457 PointeeTy = IntTy;
3458 }
3459 }
3460}
3461
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003462void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003463 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003464 // We follow the behavior of gcc, expanding structures which are
3465 // directly pointed to, and expanding embedded structures. Note that
3466 // these rules are sufficient to prevent recursive encoding of the
3467 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003468 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003469 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003470}
3471
Mike Stump11289f42009-09-09 15:08:12 +00003472static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003473 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003474 const Expr *E = FD->getBitWidth();
3475 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3476 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003477 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003478 S += 'b';
3479 S += llvm::utostr(N);
3480}
3481
Daniel Dunbar07d07852009-10-18 21:17:35 +00003482// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003483void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3484 bool ExpandPointedToStructures,
3485 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003486 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003487 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003488 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003489 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003490 if (FD && FD->isBitField())
3491 return EncodeBitField(this, S, FD);
3492 char encoding;
3493 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003494 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003495 case BuiltinType::Void: encoding = 'v'; break;
3496 case BuiltinType::Bool: encoding = 'B'; break;
3497 case BuiltinType::Char_U:
3498 case BuiltinType::UChar: encoding = 'C'; break;
3499 case BuiltinType::UShort: encoding = 'S'; break;
3500 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003501 case BuiltinType::ULong:
3502 encoding =
3503 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003504 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003505 case BuiltinType::UInt128: encoding = 'T'; break;
3506 case BuiltinType::ULongLong: encoding = 'Q'; break;
3507 case BuiltinType::Char_S:
3508 case BuiltinType::SChar: encoding = 'c'; break;
3509 case BuiltinType::Short: encoding = 's'; break;
3510 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003511 case BuiltinType::Long:
3512 encoding =
3513 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003514 break;
3515 case BuiltinType::LongLong: encoding = 'q'; break;
3516 case BuiltinType::Int128: encoding = 't'; break;
3517 case BuiltinType::Float: encoding = 'f'; break;
3518 case BuiltinType::Double: encoding = 'd'; break;
3519 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003520 }
Mike Stump11289f42009-09-09 15:08:12 +00003521
Chris Lattnere7cabb92009-07-13 00:10:46 +00003522 S += encoding;
3523 return;
3524 }
Mike Stump11289f42009-09-09 15:08:12 +00003525
John McCall9dd450b2009-09-21 23:43:11 +00003526 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003527 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003528 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003529 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003530 return;
3531 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003532
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003533 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003534 if (PT->isObjCSelType()) {
3535 S += ':';
3536 return;
3537 }
Anders Carlssond8499822007-10-29 05:01:08 +00003538 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003539
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003540 bool isReadOnly = false;
3541 // For historical/compatibility reasons, the read-only qualifier of the
3542 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3543 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003544 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003545 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003546 if (OutermostType && T.isConstQualified()) {
3547 isReadOnly = true;
3548 S += 'r';
3549 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003550 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003551 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003552 while (P->getAs<PointerType>())
3553 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003554 if (P.isConstQualified()) {
3555 isReadOnly = true;
3556 S += 'r';
3557 }
3558 }
3559 if (isReadOnly) {
3560 // Another legacy compatibility encoding. Some ObjC qualifier and type
3561 // combinations need to be rearranged.
3562 // Rewrite "in const" from "nr" to "rn"
3563 const char * s = S.c_str();
3564 int len = S.length();
3565 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3566 std::string replace = "rn";
3567 S.replace(S.end()-2, S.end(), replace);
3568 }
3569 }
Mike Stump11289f42009-09-09 15:08:12 +00003570
Anders Carlssond8499822007-10-29 05:01:08 +00003571 if (PointeeTy->isCharType()) {
3572 // char pointer types should be encoded as '*' unless it is a
3573 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003574 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003575 S += '*';
3576 return;
3577 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003578 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003579 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3580 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3581 S += '#';
3582 return;
3583 }
3584 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3585 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3586 S += '@';
3587 return;
3588 }
3589 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003590 }
Anders Carlssond8499822007-10-29 05:01:08 +00003591 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003592 getLegacyIntegralTypeEncoding(PointeeTy);
3593
Mike Stump11289f42009-09-09 15:08:12 +00003594 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003595 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003596 return;
3597 }
Mike Stump11289f42009-09-09 15:08:12 +00003598
Chris Lattnere7cabb92009-07-13 00:10:46 +00003599 if (const ArrayType *AT =
3600 // Ignore type qualifiers etc.
3601 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003602 if (isa<IncompleteArrayType>(AT)) {
3603 // Incomplete arrays are encoded as a pointer to the array element.
3604 S += '^';
3605
Mike Stump11289f42009-09-09 15:08:12 +00003606 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003607 false, ExpandStructures, FD);
3608 } else {
3609 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003610
Anders Carlssond05f44b2009-02-22 01:38:57 +00003611 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3612 S += llvm::utostr(CAT->getSize().getZExtValue());
3613 else {
3614 //Variable length arrays are encoded as a regular array with 0 elements.
3615 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3616 S += '0';
3617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
3619 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003620 false, ExpandStructures, FD);
3621 S += ']';
3622 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003623 return;
3624 }
Mike Stump11289f42009-09-09 15:08:12 +00003625
John McCall9dd450b2009-09-21 23:43:11 +00003626 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003627 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003628 return;
3629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003631 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003632 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003633 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003634 // Anonymous structures print as '?'
3635 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3636 S += II->getName();
3637 } else {
3638 S += '?';
3639 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003640 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003641 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003642 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3643 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003644 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003645 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003646 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003647 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003648 S += '"';
3649 }
Mike Stump11289f42009-09-09 15:08:12 +00003650
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003651 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003652 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003653 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003654 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003655 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003656 QualType qt = Field->getType();
3657 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003658 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003659 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003660 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003661 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003662 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003663 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003664 return;
3665 }
Mike Stump11289f42009-09-09 15:08:12 +00003666
Chris Lattnere7cabb92009-07-13 00:10:46 +00003667 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003668 if (FD && FD->isBitField())
3669 EncodeBitField(this, S, FD);
3670 else
3671 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003672 return;
3673 }
Mike Stump11289f42009-09-09 15:08:12 +00003674
Chris Lattnere7cabb92009-07-13 00:10:46 +00003675 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003676 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003677 return;
3678 }
Mike Stump11289f42009-09-09 15:08:12 +00003679
John McCall8ccfcb52009-09-24 19:53:00 +00003680 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003681 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003682 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003683 S += '{';
3684 const IdentifierInfo *II = OI->getIdentifier();
3685 S += II->getName();
3686 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003687 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003688 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003689 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003690 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003691 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003692 RecFields[i]);
3693 else
Mike Stump11289f42009-09-09 15:08:12 +00003694 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003695 FD);
3696 }
3697 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003698 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003699 }
Mike Stump11289f42009-09-09 15:08:12 +00003700
John McCall9dd450b2009-09-21 23:43:11 +00003701 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003702 if (OPT->isObjCIdType()) {
3703 S += '@';
3704 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003705 }
Mike Stump11289f42009-09-09 15:08:12 +00003706
Steve Narofff0c86112009-10-28 22:03:49 +00003707 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3708 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3709 // Since this is a binary compatibility issue, need to consult with runtime
3710 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003711 S += '#';
3712 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003713 }
Mike Stump11289f42009-09-09 15:08:12 +00003714
Chris Lattnere7cabb92009-07-13 00:10:46 +00003715 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003716 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003717 ExpandPointedToStructures,
3718 ExpandStructures, FD);
3719 if (FD || EncodingProperty) {
3720 // Note that we do extended encoding of protocol qualifer list
3721 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003722 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003723 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3724 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003725 S += '<';
3726 S += (*I)->getNameAsString();
3727 S += '>';
3728 }
3729 S += '"';
3730 }
3731 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003732 }
Mike Stump11289f42009-09-09 15:08:12 +00003733
Chris Lattnere7cabb92009-07-13 00:10:46 +00003734 QualType PointeeTy = OPT->getPointeeType();
3735 if (!EncodingProperty &&
3736 isa<TypedefType>(PointeeTy.getTypePtr())) {
3737 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003738 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003739 // {...};
3740 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003741 getObjCEncodingForTypeImpl(PointeeTy, S,
3742 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003743 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003744 return;
3745 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003746
3747 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003748 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003749 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003750 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003751 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3752 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003753 S += '<';
3754 S += (*I)->getNameAsString();
3755 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003756 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003757 S += '"';
3758 }
3759 return;
3760 }
Mike Stump11289f42009-09-09 15:08:12 +00003761
Chris Lattnere7cabb92009-07-13 00:10:46 +00003762 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003763}
3764
Mike Stump11289f42009-09-09 15:08:12 +00003765void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003766 std::string& S) const {
3767 if (QT & Decl::OBJC_TQ_In)
3768 S += 'n';
3769 if (QT & Decl::OBJC_TQ_Inout)
3770 S += 'N';
3771 if (QT & Decl::OBJC_TQ_Out)
3772 S += 'o';
3773 if (QT & Decl::OBJC_TQ_Bycopy)
3774 S += 'O';
3775 if (QT & Decl::OBJC_TQ_Byref)
3776 S += 'R';
3777 if (QT & Decl::OBJC_TQ_Oneway)
3778 S += 'V';
3779}
3780
Chris Lattnere7cabb92009-07-13 00:10:46 +00003781void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003782 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003783
Anders Carlsson87c149b2007-10-11 01:00:40 +00003784 BuiltinVaListType = T;
3785}
3786
Chris Lattnere7cabb92009-07-13 00:10:46 +00003787void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003788 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003789}
3790
Chris Lattnere7cabb92009-07-13 00:10:46 +00003791void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003792 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003793}
3794
Chris Lattnere7cabb92009-07-13 00:10:46 +00003795void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003796 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003797}
3798
Chris Lattnere7cabb92009-07-13 00:10:46 +00003799void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003800 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003801}
3802
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003803void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003804 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003805 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003806
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003807 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003808}
3809
John McCalld28ae272009-12-02 08:04:21 +00003810/// \brief Retrieve the template name that corresponds to a non-empty
3811/// lookup.
John McCallad371252010-01-20 00:46:10 +00003812TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3813 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003814 unsigned size = End - Begin;
3815 assert(size > 1 && "set is not overloaded!");
3816
3817 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3818 size * sizeof(FunctionTemplateDecl*));
3819 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3820
3821 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003822 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003823 NamedDecl *D = *I;
3824 assert(isa<FunctionTemplateDecl>(D) ||
3825 (isa<UsingShadowDecl>(D) &&
3826 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3827 *Storage++ = D;
3828 }
3829
3830 return TemplateName(OT);
3831}
3832
Douglas Gregordc572a32009-03-30 22:58:21 +00003833/// \brief Retrieve the template name that represents a qualified
3834/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003835TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003836 bool TemplateKeyword,
3837 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003838 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003839 llvm::FoldingSetNodeID ID;
3840 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3841
3842 void *InsertPos = 0;
3843 QualifiedTemplateName *QTN =
3844 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3845 if (!QTN) {
3846 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3847 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3848 }
3849
3850 return TemplateName(QTN);
3851}
3852
3853/// \brief Retrieve the template name that represents a dependent
3854/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003855TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003856 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003857 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003858 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003859
3860 llvm::FoldingSetNodeID ID;
3861 DependentTemplateName::Profile(ID, NNS, Name);
3862
3863 void *InsertPos = 0;
3864 DependentTemplateName *QTN =
3865 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3866
3867 if (QTN)
3868 return TemplateName(QTN);
3869
3870 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3871 if (CanonNNS == NNS) {
3872 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3873 } else {
3874 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3875 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003876 DependentTemplateName *CheckQTN =
3877 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3878 assert(!CheckQTN && "Dependent type name canonicalization broken");
3879 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00003880 }
3881
3882 DependentTemplateNames.InsertNode(QTN, InsertPos);
3883 return TemplateName(QTN);
3884}
3885
Douglas Gregor71395fa2009-11-04 00:56:37 +00003886/// \brief Retrieve the template name that represents a dependent
3887/// template name such as \c MetaFun::template operator+.
3888TemplateName
3889ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3890 OverloadedOperatorKind Operator) {
3891 assert((!NNS || NNS->isDependent()) &&
3892 "Nested name specifier must be dependent");
3893
3894 llvm::FoldingSetNodeID ID;
3895 DependentTemplateName::Profile(ID, NNS, Operator);
3896
3897 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003898 DependentTemplateName *QTN
3899 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00003900
3901 if (QTN)
3902 return TemplateName(QTN);
3903
3904 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3905 if (CanonNNS == NNS) {
3906 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3907 } else {
3908 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3909 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003910
3911 DependentTemplateName *CheckQTN
3912 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3913 assert(!CheckQTN && "Dependent template name canonicalization broken");
3914 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00003915 }
3916
3917 DependentTemplateNames.InsertNode(QTN, InsertPos);
3918 return TemplateName(QTN);
3919}
3920
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003921/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00003922/// TargetInfo, produce the corresponding type. The unsigned @p Type
3923/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00003924CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003925 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00003926 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003927 case TargetInfo::SignedShort: return ShortTy;
3928 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3929 case TargetInfo::SignedInt: return IntTy;
3930 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3931 case TargetInfo::SignedLong: return LongTy;
3932 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3933 case TargetInfo::SignedLongLong: return LongLongTy;
3934 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3935 }
3936
3937 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00003938 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003939}
Ted Kremenek77c51b22008-07-24 23:58:27 +00003940
3941//===----------------------------------------------------------------------===//
3942// Type Predicates.
3943//===----------------------------------------------------------------------===//
3944
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003945/// isObjCNSObjectType - Return true if this is an NSObject object using
3946/// NSObject attribute on a c-style pointer type.
3947/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00003948/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003949///
3950bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3951 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3952 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003953 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003954 return true;
3955 }
Mike Stump11289f42009-09-09 15:08:12 +00003956 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003957}
3958
Fariborz Jahanian96207692009-02-18 21:49:28 +00003959/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3960/// garbage collection attribute.
3961///
John McCall8ccfcb52009-09-24 19:53:00 +00003962Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3963 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003964 if (getLangOptions().ObjC1 &&
3965 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00003966 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00003967 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00003968 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003969 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00003970 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00003971 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003972 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003973 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003974 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003975 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00003976 // Non-pointers have none gc'able attribute regardless of the attribute
3977 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00003978 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003979 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003980 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00003981 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003982}
3983
Chris Lattner49af6a42008-04-07 06:51:04 +00003984//===----------------------------------------------------------------------===//
3985// Type Compatibility Testing
3986//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00003987
Mike Stump11289f42009-09-09 15:08:12 +00003988/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00003989/// compatible.
3990static bool areCompatVectorTypes(const VectorType *LHS,
3991 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00003992 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00003993 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00003994 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00003995}
3996
Steve Naroff8e6aee52009-07-23 01:01:38 +00003997//===----------------------------------------------------------------------===//
3998// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3999//===----------------------------------------------------------------------===//
4000
4001/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4002/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004003bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4004 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004005 if (lProto == rProto)
4006 return true;
4007 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4008 E = rProto->protocol_end(); PI != E; ++PI)
4009 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4010 return true;
4011 return false;
4012}
4013
Steve Naroff8e6aee52009-07-23 01:01:38 +00004014/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4015/// return true if lhs's protocols conform to rhs's protocol; false
4016/// otherwise.
4017bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4018 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4019 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4020 return false;
4021}
4022
4023/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4024/// ObjCQualifiedIDType.
4025bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4026 bool compare) {
4027 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004028 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004029 lhs->isObjCIdType() || lhs->isObjCClassType())
4030 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004031 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004032 rhs->isObjCIdType() || rhs->isObjCClassType())
4033 return true;
4034
4035 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004036 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004037
Steve Naroff8e6aee52009-07-23 01:01:38 +00004038 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004039
Steve Naroff8e6aee52009-07-23 01:01:38 +00004040 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004041 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004042 // make sure we check the class hierarchy.
4043 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4044 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4045 E = lhsQID->qual_end(); I != E; ++I) {
4046 // when comparing an id<P> on lhs with a static type on rhs,
4047 // see if static class implements all of id's protocols, directly or
4048 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004049 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004050 return false;
4051 }
4052 }
4053 // If there are no qualifiers and no interface, we have an 'id'.
4054 return true;
4055 }
Mike Stump11289f42009-09-09 15:08:12 +00004056 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004057 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4058 E = lhsQID->qual_end(); I != E; ++I) {
4059 ObjCProtocolDecl *lhsProto = *I;
4060 bool match = false;
4061
4062 // when comparing an id<P> on lhs with a static type on rhs,
4063 // see if static class implements all of id's protocols, directly or
4064 // through its super class and categories.
4065 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4066 E = rhsOPT->qual_end(); J != E; ++J) {
4067 ObjCProtocolDecl *rhsProto = *J;
4068 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4069 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4070 match = true;
4071 break;
4072 }
4073 }
Mike Stump11289f42009-09-09 15:08:12 +00004074 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004075 // make sure we check the class hierarchy.
4076 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4077 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4078 E = lhsQID->qual_end(); I != E; ++I) {
4079 // when comparing an id<P> on lhs with a static type on rhs,
4080 // see if static class implements all of id's protocols, directly or
4081 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004082 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004083 match = true;
4084 break;
4085 }
4086 }
4087 }
4088 if (!match)
4089 return false;
4090 }
Mike Stump11289f42009-09-09 15:08:12 +00004091
Steve Naroff8e6aee52009-07-23 01:01:38 +00004092 return true;
4093 }
Mike Stump11289f42009-09-09 15:08:12 +00004094
Steve Naroff8e6aee52009-07-23 01:01:38 +00004095 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4096 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4097
Mike Stump11289f42009-09-09 15:08:12 +00004098 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004099 lhs->getAsObjCInterfacePointerType()) {
4100 if (lhsOPT->qual_empty()) {
4101 bool match = false;
4102 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4103 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4104 E = rhsQID->qual_end(); I != E; ++I) {
4105 // when comparing an id<P> on lhs with a static type on rhs,
4106 // see if static class implements all of id's protocols, directly or
4107 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004108 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004109 match = true;
4110 break;
4111 }
4112 }
4113 if (!match)
4114 return false;
4115 }
4116 return true;
4117 }
Mike Stump11289f42009-09-09 15:08:12 +00004118 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004119 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4120 E = lhsOPT->qual_end(); I != E; ++I) {
4121 ObjCProtocolDecl *lhsProto = *I;
4122 bool match = false;
4123
4124 // when comparing an id<P> on lhs with a static type on rhs,
4125 // see if static class implements all of id's protocols, directly or
4126 // through its super class and categories.
4127 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4128 E = rhsQID->qual_end(); J != E; ++J) {
4129 ObjCProtocolDecl *rhsProto = *J;
4130 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4131 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4132 match = true;
4133 break;
4134 }
4135 }
4136 if (!match)
4137 return false;
4138 }
4139 return true;
4140 }
4141 return false;
4142}
4143
Eli Friedman47f77112008-08-22 00:56:42 +00004144/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004145/// compatible for assignment from RHS to LHS. This handles validation of any
4146/// protocol qualifiers on the LHS or RHS.
4147///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004148bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4149 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004150 // If either type represents the built-in 'id' or 'Class' types, return true.
4151 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004152 return true;
4153
Steve Naroff8e6aee52009-07-23 01:01:38 +00004154 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00004155 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4156 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004157 false);
4158
Steve Naroff7cae42b2009-07-10 23:34:53 +00004159 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4160 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff8e6aee52009-07-23 01:01:38 +00004161 if (LHS && RHS) // We have 2 user-defined types.
4162 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroff8e6aee52009-07-23 01:01:38 +00004164 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004165}
4166
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004167/// getIntersectionOfProtocols - This routine finds the intersection of set
4168/// of protocols inherited from two distinct objective-c pointer objects.
4169/// It is used to build composite qualifier list of the composite type of
4170/// the conditional expression involving two objective-c pointer objects.
4171static
4172void getIntersectionOfProtocols(ASTContext &Context,
4173 const ObjCObjectPointerType *LHSOPT,
4174 const ObjCObjectPointerType *RHSOPT,
4175 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4176
4177 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4178 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4179
4180 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4181 unsigned LHSNumProtocols = LHS->getNumProtocols();
4182 if (LHSNumProtocols > 0)
4183 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4184 else {
4185 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4186 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4187 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4188 LHSInheritedProtocols.end());
4189 }
4190
4191 unsigned RHSNumProtocols = RHS->getNumProtocols();
4192 if (RHSNumProtocols > 0) {
4193 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4194 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4195 if (InheritedProtocolSet.count(RHSProtocols[i]))
4196 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4197 }
4198 else {
4199 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4200 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4201 // FIXME. This may cause duplication of protocols in the list, but should
4202 // be harmless.
4203 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4204 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4205 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4206 }
4207}
4208
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004209/// areCommonBaseCompatible - Returns common base class of the two classes if
4210/// one found. Note that this is O'2 algorithm. But it will be called as the
4211/// last type comparison in a ?-exp of ObjC pointer types before a
4212/// warning is issued. So, its invokation is extremely rare.
4213QualType ASTContext::areCommonBaseCompatible(
4214 const ObjCObjectPointerType *LHSOPT,
4215 const ObjCObjectPointerType *RHSOPT) {
4216 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4217 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4218 if (!LHS || !RHS)
4219 return QualType();
4220
4221 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4222 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4223 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004224 if (canAssignObjCInterfaces(LHS, RHS)) {
4225 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4226 getIntersectionOfProtocols(*this,
4227 LHSOPT, RHSOPT, IntersectionOfProtocols);
4228 if (IntersectionOfProtocols.empty())
4229 LHSTy = getObjCObjectPointerType(LHSTy);
4230 else
4231 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4232 IntersectionOfProtocols.size());
4233 return LHSTy;
4234 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004235 }
4236
4237 return QualType();
4238}
4239
Eli Friedman47f77112008-08-22 00:56:42 +00004240bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4241 const ObjCInterfaceType *RHS) {
Chris Lattner49af6a42008-04-07 06:51:04 +00004242 // Verify that the base decls are compatible: the RHS must be a subclass of
4243 // the LHS.
4244 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4245 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004246
Chris Lattner49af6a42008-04-07 06:51:04 +00004247 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4248 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004249 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004250 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004251
Chris Lattner49af6a42008-04-07 06:51:04 +00004252 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4253 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004254 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004255 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004256
Steve Naroffc277ad12009-07-18 15:33:26 +00004257 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4258 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004259 LHSPI != LHSPE; LHSPI++) {
4260 bool RHSImplementsProtocol = false;
4261
4262 // If the RHS doesn't implement the protocol on the left, the types
4263 // are incompatible.
Steve Naroffc277ad12009-07-18 15:33:26 +00004264 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004265 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004266 RHSPI != RHSPE; RHSPI++) {
4267 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004268 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004269 break;
4270 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004271 }
4272 // FIXME: For better diagnostics, consider passing back the protocol name.
4273 if (!RHSImplementsProtocol)
4274 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004275 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004276 // The RHS implements all protocols listed on the LHS.
4277 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004278}
4279
Steve Naroffb7605152009-02-12 17:52:19 +00004280bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4281 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004282 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4283 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004284
Steve Naroff7cae42b2009-07-10 23:34:53 +00004285 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004286 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004287
4288 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4289 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004290}
4291
Mike Stump11289f42009-09-09 15:08:12 +00004292/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004293/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004294/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004295/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004296bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004297 if (getLangOptions().CPlusPlus)
4298 return hasSameType(LHS, RHS);
4299
Eli Friedman47f77112008-08-22 00:56:42 +00004300 return !mergeTypes(LHS, RHS).isNull();
4301}
4302
Douglas Gregor8c940862010-01-18 17:14:39 +00004303static bool isSameCallingConvention(CallingConv lcc, CallingConv rcc) {
4304 return (getCanonicalCallingConv(lcc) == getCanonicalCallingConv(rcc));
4305}
4306
Eli Friedman47f77112008-08-22 00:56:42 +00004307QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall9dd450b2009-09-21 23:43:11 +00004308 const FunctionType *lbase = lhs->getAs<FunctionType>();
4309 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004310 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4311 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004312 bool allLTypes = true;
4313 bool allRTypes = true;
4314
4315 // Check return type
4316 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4317 if (retType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004318 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4319 allLTypes = false;
4320 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4321 allRTypes = false;
Mike Stumpea086c72009-07-25 23:24:03 +00004322 // FIXME: double check this
Mike Stump8c5d7992009-07-25 21:26:53 +00004323 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4324 if (NoReturn != lbase->getNoReturnAttr())
4325 allLTypes = false;
4326 if (NoReturn != rbase->getNoReturnAttr())
4327 allRTypes = false;
Douglas Gregor8c940862010-01-18 17:14:39 +00004328 CallingConv lcc = lbase->getCallConv();
4329 CallingConv rcc = rbase->getCallConv();
4330 // Compatible functions must have compatible calling conventions
4331 if (!isSameCallingConvention(lcc, rcc))
4332 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004333
Eli Friedman47f77112008-08-22 00:56:42 +00004334 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004335 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4336 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004337 unsigned lproto_nargs = lproto->getNumArgs();
4338 unsigned rproto_nargs = rproto->getNumArgs();
4339
4340 // Compatible functions must have the same number of arguments
4341 if (lproto_nargs != rproto_nargs)
4342 return QualType();
4343
4344 // Variadic and non-variadic functions aren't compatible
4345 if (lproto->isVariadic() != rproto->isVariadic())
4346 return QualType();
4347
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004348 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4349 return QualType();
4350
Eli Friedman47f77112008-08-22 00:56:42 +00004351 // Check argument compatibility
4352 llvm::SmallVector<QualType, 10> types;
4353 for (unsigned i = 0; i < lproto_nargs; i++) {
4354 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4355 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4356 QualType argtype = mergeTypes(largtype, rargtype);
4357 if (argtype.isNull()) return QualType();
4358 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004359 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4360 allLTypes = false;
4361 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4362 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004363 }
4364 if (allLTypes) return lhs;
4365 if (allRTypes) return rhs;
4366 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004367 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor8c940862010-01-18 17:14:39 +00004368 NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004369 }
4370
4371 if (lproto) allRTypes = false;
4372 if (rproto) allLTypes = false;
4373
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004374 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004375 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004376 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004377 if (proto->isVariadic()) return QualType();
4378 // Check that the types are compatible with the types that
4379 // would result from default argument promotions (C99 6.7.5.3p15).
4380 // The only types actually affected are promotable integer
4381 // types and floats, which would be passed as a different
4382 // type depending on whether the prototype is visible.
4383 unsigned proto_nargs = proto->getNumArgs();
4384 for (unsigned i = 0; i < proto_nargs; ++i) {
4385 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004386
4387 // Look at the promotion type of enum types, since that is the type used
4388 // to pass enum values.
4389 if (const EnumType *Enum = argTy->getAs<EnumType>())
4390 argTy = Enum->getDecl()->getPromotionType();
4391
Eli Friedman47f77112008-08-22 00:56:42 +00004392 if (argTy->isPromotableIntegerType() ||
4393 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4394 return QualType();
4395 }
4396
4397 if (allLTypes) return lhs;
4398 if (allRTypes) return rhs;
4399 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004400 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregor8c940862010-01-18 17:14:39 +00004401 proto->getTypeQuals(), NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004402 }
4403
4404 if (allLTypes) return lhs;
4405 if (allRTypes) return rhs;
Douglas Gregor8c940862010-01-18 17:14:39 +00004406 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004407}
4408
4409QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004410 // C++ [expr]: If an expression initially has the type "reference to T", the
4411 // type is adjusted to "T" prior to any further analysis, the expression
4412 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004413 // expression is an lvalue unless the reference is an rvalue reference and
4414 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004415 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4416 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4417
Eli Friedman47f77112008-08-22 00:56:42 +00004418 QualType LHSCan = getCanonicalType(LHS),
4419 RHSCan = getCanonicalType(RHS);
4420
4421 // If two types are identical, they are compatible.
4422 if (LHSCan == RHSCan)
4423 return LHS;
4424
John McCall8ccfcb52009-09-24 19:53:00 +00004425 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004426 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4427 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004428 if (LQuals != RQuals) {
4429 // If any of these qualifiers are different, we have a type
4430 // mismatch.
4431 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4432 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4433 return QualType();
4434
4435 // Exactly one GC qualifier difference is allowed: __strong is
4436 // okay if the other type has no GC qualifier but is an Objective
4437 // C object pointer (i.e. implicitly strong by default). We fix
4438 // this by pretending that the unqualified type was actually
4439 // qualified __strong.
4440 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4441 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4442 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4443
4444 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4445 return QualType();
4446
4447 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4448 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4449 }
4450 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4451 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4452 }
Eli Friedman47f77112008-08-22 00:56:42 +00004453 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004454 }
4455
4456 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004457
Eli Friedmandcca6332009-06-01 01:22:52 +00004458 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4459 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004460
Chris Lattnerfd652912008-01-14 05:45:46 +00004461 // We want to consider the two function types to be the same for these
4462 // comparisons, just force one to the other.
4463 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4464 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004465
4466 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004467 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4468 LHSClass = Type::ConstantArray;
4469 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4470 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004471
Nate Begemance4d7fc2008-04-18 23:10:10 +00004472 // Canonicalize ExtVector -> Vector.
4473 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4474 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004475
Chris Lattner95554662008-04-07 05:43:21 +00004476 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004477 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004478 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004479 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004480 // Compatibility is based on the underlying type, not the promotion
4481 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004482 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004483 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4484 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004485 }
John McCall9dd450b2009-09-21 23:43:11 +00004486 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004487 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4488 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004489 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004490
Eli Friedman47f77112008-08-22 00:56:42 +00004491 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004492 }
Eli Friedman47f77112008-08-22 00:56:42 +00004493
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004494 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004495 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004496#define TYPE(Class, Base)
4497#define ABSTRACT_TYPE(Class, Base)
4498#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4499#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4500#include "clang/AST/TypeNodes.def"
4501 assert(false && "Non-canonical and dependent types shouldn't get here");
4502 return QualType();
4503
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004504 case Type::LValueReference:
4505 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004506 case Type::MemberPointer:
4507 assert(false && "C++ should never be in mergeTypes");
4508 return QualType();
4509
4510 case Type::IncompleteArray:
4511 case Type::VariableArray:
4512 case Type::FunctionProto:
4513 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004514 assert(false && "Types are eliminated above");
4515 return QualType();
4516
Chris Lattnerfd652912008-01-14 05:45:46 +00004517 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004518 {
4519 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004520 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4521 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004522 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4523 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004524 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004525 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004526 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004527 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004528 return getPointerType(ResultType);
4529 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004530 case Type::BlockPointer:
4531 {
4532 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004533 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4534 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroff68e167d2008-12-10 17:49:55 +00004535 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4536 if (ResultType.isNull()) return QualType();
4537 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4538 return LHS;
4539 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4540 return RHS;
4541 return getBlockPointerType(ResultType);
4542 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004543 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004544 {
4545 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4546 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4547 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4548 return QualType();
4549
4550 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4551 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4552 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4553 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004554 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4555 return LHS;
4556 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4557 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004558 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4559 ArrayType::ArraySizeModifier(), 0);
4560 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4561 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004562 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4563 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004564 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4565 return LHS;
4566 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4567 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004568 if (LVAT) {
4569 // FIXME: This isn't correct! But tricky to implement because
4570 // the array's size has to be the size of LHS, but the type
4571 // has to be different.
4572 return LHS;
4573 }
4574 if (RVAT) {
4575 // FIXME: This isn't correct! But tricky to implement because
4576 // the array's size has to be the size of RHS, but the type
4577 // has to be different.
4578 return RHS;
4579 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004580 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4581 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004582 return getIncompleteArrayType(ResultType,
4583 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004584 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004585 case Type::FunctionNoProto:
Eli Friedman47f77112008-08-22 00:56:42 +00004586 return mergeFunctionTypes(LHS, RHS);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004587 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004588 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004589 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004590 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004591 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004592 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004593 case Type::Complex:
4594 // Distinct complex types are incompatible.
4595 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004596 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004597 // FIXME: The merged type should be an ExtVector!
John McCall9dd450b2009-09-21 23:43:11 +00004598 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004599 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004600 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004601 case Type::ObjCInterface: {
Steve Naroff7a7814c2009-02-21 16:18:07 +00004602 // Check if the interfaces are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004603 // FIXME: This should be type compatibility, e.g. whether
4604 // "LHS x; RHS x;" at global scope is legal.
John McCall9dd450b2009-09-21 23:43:11 +00004605 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4606 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff7a7814c2009-02-21 16:18:07 +00004607 if (LHSIface && RHSIface &&
4608 canAssignObjCInterfaces(LHSIface, RHSIface))
4609 return LHS;
4610
Eli Friedman47f77112008-08-22 00:56:42 +00004611 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004612 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004613 case Type::ObjCObjectPointer: {
John McCall9dd450b2009-09-21 23:43:11 +00004614 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4615 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004616 return LHS;
4617
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004618 return QualType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004619 }
Douglas Gregordc572a32009-03-30 22:58:21 +00004620 case Type::TemplateSpecialization:
4621 assert(false && "Dependent types have no size");
4622 break;
Steve Naroff32e44c02007-10-15 20:41:53 +00004623 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004624
4625 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004626}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004627
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004628//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004629// Integer Predicates
4630//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004631
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004632unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004633 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004634 return 1;
John McCall56774992009-12-09 09:09:27 +00004635 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004636 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004637 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004638 return (unsigned)getTypeSize(T);
4639}
4640
4641QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4642 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004643
4644 // Turn <4 x signed int> -> <4 x unsigned int>
4645 if (const VectorType *VTy = T->getAs<VectorType>())
4646 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004647 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004648
4649 // For enums, we return the unsigned version of the base type.
4650 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004651 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004652
4653 const BuiltinType *BTy = T->getAs<BuiltinType>();
4654 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004655 switch (BTy->getKind()) {
4656 case BuiltinType::Char_S:
4657 case BuiltinType::SChar:
4658 return UnsignedCharTy;
4659 case BuiltinType::Short:
4660 return UnsignedShortTy;
4661 case BuiltinType::Int:
4662 return UnsignedIntTy;
4663 case BuiltinType::Long:
4664 return UnsignedLongTy;
4665 case BuiltinType::LongLong:
4666 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004667 case BuiltinType::Int128:
4668 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004669 default:
4670 assert(0 && "Unexpected signed integer type");
4671 return QualType();
4672 }
4673}
4674
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004675ExternalASTSource::~ExternalASTSource() { }
4676
4677void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004678
4679
4680//===----------------------------------------------------------------------===//
4681// Builtin Type Computation
4682//===----------------------------------------------------------------------===//
4683
4684/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4685/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004686static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004687 ASTContext::GetBuiltinTypeError &Error,
4688 bool AllowTypeModifiers = true) {
4689 // Modifiers.
4690 int HowLong = 0;
4691 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004692
Chris Lattnerecd79c62009-06-14 00:45:47 +00004693 // Read the modifiers first.
4694 bool Done = false;
4695 while (!Done) {
4696 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004697 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004698 case 'S':
4699 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4700 assert(!Signed && "Can't use 'S' modifier multiple times!");
4701 Signed = true;
4702 break;
4703 case 'U':
4704 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4705 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4706 Unsigned = true;
4707 break;
4708 case 'L':
4709 assert(HowLong <= 2 && "Can't have LLLL modifier");
4710 ++HowLong;
4711 break;
4712 }
4713 }
4714
4715 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Chris Lattnerecd79c62009-06-14 00:45:47 +00004717 // Read the base type.
4718 switch (*Str++) {
4719 default: assert(0 && "Unknown builtin type letter!");
4720 case 'v':
4721 assert(HowLong == 0 && !Signed && !Unsigned &&
4722 "Bad modifiers used with 'v'!");
4723 Type = Context.VoidTy;
4724 break;
4725 case 'f':
4726 assert(HowLong == 0 && !Signed && !Unsigned &&
4727 "Bad modifiers used with 'f'!");
4728 Type = Context.FloatTy;
4729 break;
4730 case 'd':
4731 assert(HowLong < 2 && !Signed && !Unsigned &&
4732 "Bad modifiers used with 'd'!");
4733 if (HowLong)
4734 Type = Context.LongDoubleTy;
4735 else
4736 Type = Context.DoubleTy;
4737 break;
4738 case 's':
4739 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4740 if (Unsigned)
4741 Type = Context.UnsignedShortTy;
4742 else
4743 Type = Context.ShortTy;
4744 break;
4745 case 'i':
4746 if (HowLong == 3)
4747 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4748 else if (HowLong == 2)
4749 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4750 else if (HowLong == 1)
4751 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4752 else
4753 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4754 break;
4755 case 'c':
4756 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4757 if (Signed)
4758 Type = Context.SignedCharTy;
4759 else if (Unsigned)
4760 Type = Context.UnsignedCharTy;
4761 else
4762 Type = Context.CharTy;
4763 break;
4764 case 'b': // boolean
4765 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4766 Type = Context.BoolTy;
4767 break;
4768 case 'z': // size_t.
4769 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4770 Type = Context.getSizeType();
4771 break;
4772 case 'F':
4773 Type = Context.getCFConstantStringType();
4774 break;
4775 case 'a':
4776 Type = Context.getBuiltinVaListType();
4777 assert(!Type.isNull() && "builtin va list type not initialized!");
4778 break;
4779 case 'A':
4780 // This is a "reference" to a va_list; however, what exactly
4781 // this means depends on how va_list is defined. There are two
4782 // different kinds of va_list: ones passed by value, and ones
4783 // passed by reference. An example of a by-value va_list is
4784 // x86, where va_list is a char*. An example of by-ref va_list
4785 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4786 // we want this argument to be a char*&; for x86-64, we want
4787 // it to be a __va_list_tag*.
4788 Type = Context.getBuiltinVaListType();
4789 assert(!Type.isNull() && "builtin va list type not initialized!");
4790 if (Type->isArrayType()) {
4791 Type = Context.getArrayDecayedType(Type);
4792 } else {
4793 Type = Context.getLValueReferenceType(Type);
4794 }
4795 break;
4796 case 'V': {
4797 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004798 unsigned NumElements = strtoul(Str, &End, 10);
4799 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004800
Chris Lattnerecd79c62009-06-14 00:45:47 +00004801 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004802
Chris Lattnerecd79c62009-06-14 00:45:47 +00004803 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004804 // FIXME: Don't know what to do about AltiVec.
4805 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004806 break;
4807 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004808 case 'X': {
4809 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4810 Type = Context.getComplexType(ElementType);
4811 break;
4812 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004813 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004814 Type = Context.getFILEType();
4815 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004816 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004817 return QualType();
4818 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004819 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004820 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004821 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004822 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004823 else
4824 Type = Context.getjmp_bufType();
4825
Mike Stump2adb4da2009-07-28 23:47:15 +00004826 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004827 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004828 return QualType();
4829 }
4830 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004831 }
Mike Stump11289f42009-09-09 15:08:12 +00004832
Chris Lattnerecd79c62009-06-14 00:45:47 +00004833 if (!AllowTypeModifiers)
4834 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004835
Chris Lattnerecd79c62009-06-14 00:45:47 +00004836 Done = false;
4837 while (!Done) {
4838 switch (*Str++) {
4839 default: Done = true; --Str; break;
4840 case '*':
4841 Type = Context.getPointerType(Type);
4842 break;
4843 case '&':
4844 Type = Context.getLValueReferenceType(Type);
4845 break;
4846 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4847 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00004848 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00004849 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00004850 case 'D':
4851 Type = Context.getVolatileType(Type);
4852 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004853 }
4854 }
Mike Stump11289f42009-09-09 15:08:12 +00004855
Chris Lattnerecd79c62009-06-14 00:45:47 +00004856 return Type;
4857}
4858
4859/// GetBuiltinType - Return the type for the specified builtin.
4860QualType ASTContext::GetBuiltinType(unsigned id,
4861 GetBuiltinTypeError &Error) {
4862 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00004863
Chris Lattnerecd79c62009-06-14 00:45:47 +00004864 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004865
Chris Lattnerecd79c62009-06-14 00:45:47 +00004866 Error = GE_None;
4867 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4868 if (Error != GE_None)
4869 return QualType();
4870 while (TypeStr[0] && TypeStr[0] != '.') {
4871 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4872 if (Error != GE_None)
4873 return QualType();
4874
4875 // Do array -> pointer decay. The builtin should use the decayed type.
4876 if (Ty->isArrayType())
4877 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004878
Chris Lattnerecd79c62009-06-14 00:45:47 +00004879 ArgTypes.push_back(Ty);
4880 }
4881
4882 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4883 "'.' should only occur at end of builtin type list!");
4884
4885 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4886 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4887 return getFunctionNoProtoType(ResType);
4888 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4889 TypeStr[0] == '.', 0);
4890}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004891
4892QualType
4893ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4894 // Perform the usual unary conversions. We do this early so that
4895 // integral promotions to "int" can allow us to exit early, in the
4896 // lhs == rhs check. Also, for conversion purposes, we ignore any
4897 // qualifiers. For example, "const float" and "float" are
4898 // equivalent.
4899 if (lhs->isPromotableIntegerType())
4900 lhs = getPromotedIntegerType(lhs);
4901 else
4902 lhs = lhs.getUnqualifiedType();
4903 if (rhs->isPromotableIntegerType())
4904 rhs = getPromotedIntegerType(rhs);
4905 else
4906 rhs = rhs.getUnqualifiedType();
4907
4908 // If both types are identical, no conversion is needed.
4909 if (lhs == rhs)
4910 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00004911
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004912 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4913 // The caller can deal with this (e.g. pointer + int).
4914 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4915 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00004916
4917 // At this point, we have two different arithmetic types.
4918
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004919 // Handle complex types first (C99 6.3.1.8p1).
4920 if (lhs->isComplexType() || rhs->isComplexType()) {
4921 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00004922 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004923 // convert the rhs to the lhs complex type.
4924 return lhs;
4925 }
Mike Stump11289f42009-09-09 15:08:12 +00004926 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004927 // convert the lhs to the rhs complex type.
4928 return rhs;
4929 }
4930 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00004931 // When both operands are complex, the shorter operand is converted to the
4932 // type of the longer, and that is the type of the result. This corresponds
4933 // to what is done when combining two real floating-point operands.
4934 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004935 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00004936 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004937 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00004938 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004939 // "double _Complex" is promoted to "long double _Complex".
4940 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00004941
4942 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004943 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00004944 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004945 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00004946 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004947 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4948 // domains match. This is a requirement for our implementation, C99
4949 // does not require this promotion.
4950 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4951 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4952 return rhs;
4953 } else { // handle "_Complex double, double".
4954 return lhs;
4955 }
4956 }
4957 return lhs; // The domain/size match exactly.
4958 }
4959 // Now handle "real" floating types (i.e. float, double, long double).
4960 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4961 // if we have an integer operand, the result is the real floating type.
4962 if (rhs->isIntegerType()) {
4963 // convert rhs to the lhs floating point type.
4964 return lhs;
4965 }
4966 if (rhs->isComplexIntegerType()) {
4967 // convert rhs to the complex floating point type.
4968 return getComplexType(lhs);
4969 }
4970 if (lhs->isIntegerType()) {
4971 // convert lhs to the rhs floating point type.
4972 return rhs;
4973 }
Mike Stump11289f42009-09-09 15:08:12 +00004974 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004975 // convert lhs to the complex floating point type.
4976 return getComplexType(rhs);
4977 }
4978 // We have two real floating types, float/complex combos were handled above.
4979 // Convert the smaller operand to the bigger result.
4980 int result = getFloatingTypeOrder(lhs, rhs);
4981 if (result > 0) // convert the rhs
4982 return lhs;
4983 assert(result < 0 && "illegal float comparison");
4984 return rhs; // convert the lhs
4985 }
4986 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4987 // Handle GCC complex int extension.
4988 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4989 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4990
4991 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00004992 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004993 rhsComplexInt->getElementType()) >= 0)
4994 return lhs; // convert the rhs
4995 return rhs;
4996 } else if (lhsComplexInt && rhs->isIntegerType()) {
4997 // convert the rhs to the lhs complex type.
4998 return lhs;
4999 } else if (rhsComplexInt && lhs->isIntegerType()) {
5000 // convert the lhs to the rhs complex type.
5001 return rhs;
5002 }
5003 }
5004 // Finally, we have two differing integer types.
5005 // The rules for this case are in C99 6.3.1.8
5006 int compare = getIntegerTypeOrder(lhs, rhs);
5007 bool lhsSigned = lhs->isSignedIntegerType(),
5008 rhsSigned = rhs->isSignedIntegerType();
5009 QualType destType;
5010 if (lhsSigned == rhsSigned) {
5011 // Same signedness; use the higher-ranked type
5012 destType = compare >= 0 ? lhs : rhs;
5013 } else if (compare != (lhsSigned ? 1 : -1)) {
5014 // The unsigned type has greater than or equal rank to the
5015 // signed type, so use the unsigned type
5016 destType = lhsSigned ? rhs : lhs;
5017 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5018 // The two types are different widths; if we are here, that
5019 // means the signed type is larger than the unsigned type, so
5020 // use the signed type.
5021 destType = lhsSigned ? lhs : rhs;
5022 } else {
5023 // The signed type is higher-ranked than the unsigned type,
5024 // but isn't actually any bigger (like unsigned int and long
5025 // on most 32-bit systems). Use the unsigned type corresponding
5026 // to the signed type.
5027 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5028 }
5029 return destType;
5030}