blob: cc96a5dc0e25d7ce50fedbe385d94441a3abb31a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000025#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000026#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000027#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000028#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000029#include "RecordLayoutBuilder.h"
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
33enum FloatingRank {
34 FloatRank, DoubleRank, LongDoubleRank
35};
36
Chris Lattner61710852008-10-05 17:34:18 +000037ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000038 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000039 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000040 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000041 bool FreeMem, unsigned size_reserve) :
42 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000043 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000044 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
45 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000046 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000047 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000048 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000049 ObjCIdRedefinitionType = QualType();
50 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000051 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000052 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000053 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000054 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000055}
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057ASTContext::~ASTContext() {
58 // Deallocate all the types.
59 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000060 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000061 Types.pop_back();
62 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000063
Nuno Lopesb74668e2008-12-17 22:30:25 +000064 {
John McCall0953e762009-09-24 19:53:00 +000065 llvm::FoldingSet<ExtQuals>::iterator
66 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
67 while (I != E)
68 Deallocate(&*I++);
69 }
70
71 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000072 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
73 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
74 while (I != E) {
75 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
76 delete R;
77 }
78 }
79
80 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000081 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000083 while (I != E) {
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
86 }
87 }
88
Douglas Gregorab452ba2009-03-26 23:50:42 +000089 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000090 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
91 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000092 NNSEnd = NestedNameSpecifiers.end();
93 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 /* Increment in loop */)
95 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-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 Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 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 Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 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 Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-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 Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-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 Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-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 Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000263ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000265 = InstantiatedFromUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
John McCalled976492009-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 Carlsson0d8df782009-08-29 19:37:28 +0000297}
298
Anders Carlssond8b285f2009-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 Stump1eb44332009-09-09 15:08:12 +0000304
Anders Carlssond8b285f2009-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 Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316}
317
Douglas Gregor2e222532009-07-02 17:08:52 +0000318namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 : std::binary_function<SourceRange, SourceRange, bool> {
321 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Douglas Gregor2e222532009-07-02 17:08:52 +0000323 public:
324 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000341static bool
342isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000343 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const char *BufferStart
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000362/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000363const char *ASTContext::getCommentForDecl(const Decl *D) {
364 if (!D)
365 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Douglas Gregor2e222532009-07-02 17:08:52 +0000367 // Check whether we have cached a comment string for this declaration
368 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000369 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000370 = DeclComments.find(D);
371 if (Pos != DeclComments.end())
372 return Pos->second.c_str();
373
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 if (!LoadedComments.empty())
381 Comments.insert(Comments.begin(), LoadedComments.begin(),
382 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 LoadedExternalComments = true;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
387 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000399 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000400 SourceRange(DeclStartLoc),
401 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000405 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000406 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000407 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000418 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000424 Result.append(FileBufferStart +
425 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000426 FileBufferStart + LastCommentEndDecomp.second + 1);
427 return Result.c_str();
428 }
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor2e222532009-07-02 17:08:52 +0000444 // Check that we actually have a Doxygen comment.
445 if (!isDoxygenComment(SourceMgr, *LastComment))
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000450 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000453 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000460
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000464 unsigned ExpectedLine
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000493 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Douglas Gregor2e222532009-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 Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor2e222532009-07-02 17:08:52 +0000512 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 Result.append(FileBufferStart +
514 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 FileBufferStart + LastCommentEndDecomp.second + 1);
516 return Result.c_str();
517}
518
Chris Lattner464175b2007-07-18 17:52:12 +0000519//===----------------------------------------------------------------------===//
520// Type Sizing and Analysis
521//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000522
Chris Lattnerb7cfe882008-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 McCall183700f2009-09-21 23:43:11 +0000526 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-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
Mike Stump196efbf2009-09-22 02:43:44 +0000536/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-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 Redl5d484e82009-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).
541unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000542 unsigned Align = Target.getCharWidth();
543
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000544 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000545 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546
Chris Lattneraf707ab2009-01-24 21:53:27 +0000547 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000549 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-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 Carlsson4cc2cfd2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-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 Lattneraf707ab2009-01-24 21:53:27 +0000562 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000563
564 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000565}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000566
Chris Lattnera7674d82007-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 McCall0953e762009-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 Lattnerd2d2a112007-07-14 01:29:45 +0000573std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000574ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000575 uint64_t Width=0;
576 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000577 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000578#define TYPE(Class, Base)
579#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000580#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000583 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000584 break;
585
Chris Lattner692233e2007-07-13 22:27:08 +0000586 case Type::FunctionNoProto:
587 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000588 // GCC extension: alignof(function) = 32 bits
589 Width = 0;
590 Align = 32;
591 break;
592
Douglas Gregor72564e72009-02-26 23:50:07 +0000593 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000594 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000595 Width = 0;
596 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597 break;
598
Steve Narofffb22d962007-08-30 01:06:46 +0000599 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000600 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner98be4942008-03-05 18:54:05 +0000602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000603 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000604 Align = EltInfo.second;
605 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000606 }
Nate Begeman213541a2008-04-18 23:10:10 +0000607 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000608 case Type::Vector: {
Chris Lattner9fcfe922009-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 Friedman4bd998b2008-05-30 09:31:38 +0000612 Align = Width;
Nate Begeman6fe7c8a2009-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 Lattner9fcfe922009-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 Lattner030d8842007-07-19 22:06:24 +0000619 break;
620 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000621
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000623 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000624 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000625 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000626 // GCC extension: alignof(void) = 8 bits.
627 Width = 0;
628 Align = 8;
629 break;
630
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getBoolWidth();
633 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::Char_S:
636 case BuiltinType::Char_U:
637 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getCharWidth();
640 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000642 case BuiltinType::WChar:
643 Width = Target.getWCharWidth();
644 Align = Target.getWCharAlign();
645 break;
Alisdair Meredithf5c209d2009-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 Lattner692233e2007-07-13 22:27:08 +0000654 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getShortWidth();
657 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000659 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000660 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000661 Width = Target.getIntWidth();
662 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000664 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000666 Width = Target.getLongWidth();
667 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000669 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000671 Width = Target.getLongLongWidth();
672 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 break;
Chris Lattnerec16cb92009-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 Lattner6f62c2a2007-12-19 19:23:28 +0000679 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000680 Width = Target.getFloatWidth();
681 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 break;
683 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000684 Width = Target.getDoubleWidth();
685 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 Width = Target.getLongDoubleWidth();
689 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
Sebastian Redl6e8ed162009-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 Redl1590d9c2009-05-27 19:34:06 +0000694 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000695 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000696 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000697 case Type::FixedWidthInt:
698 // FIXME: This isn't precisely correct; the width/alignment should depend
699 // on the available types for the target
700 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000701 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000702 Align = Width;
703 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000704 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000705 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000706 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000708 case Type::BlockPointer: {
709 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
710 Width = Target.getPointerWidth(AS);
711 Align = Target.getPointerAlign(AS);
712 break;
713 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000714 case Type::LValueReference:
715 case Type::RValueReference: {
716 // alignof and sizeof should never enter this code path here, so we go
717 // the pointer route.
718 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
719 Width = Target.getPointerWidth(AS);
720 Align = Target.getPointerAlign(AS);
721 break;
722 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 case Type::Pointer: {
724 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000725 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000726 Align = Target.getPointerAlign(AS);
727 break;
728 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000729 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000730 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000731 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000732 getTypeInfo(getPointerDiffType());
733 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000734 if (Pointee->isFunctionType())
735 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000736 Align = PtrDiffInfo.second;
737 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000738 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000739 case Type::Complex: {
740 // Complex types have the same alignment as their elements, but twice the
741 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000742 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000743 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000744 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000745 Align = EltInfo.second;
746 break;
747 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000748 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000749 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000750 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
751 Width = Layout.getSize();
752 Align = Layout.getAlignment();
753 break;
754 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000755 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000756 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000757 const TagType *TT = cast<TagType>(T);
758
759 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000760 Width = 1;
761 Align = 1;
762 break;
763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Daniel Dunbar1d751182008-11-08 05:48:37 +0000765 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000766 return getTypeInfo(ET->getDecl()->getIntegerType());
767
Daniel Dunbar1d751182008-11-08 05:48:37 +0000768 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000769 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
770 Width = Layout.getSize();
771 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000772 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000773 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000774
Chris Lattner9fcfe922009-10-22 05:17:15 +0000775 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000776 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
777 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000778
Chris Lattner9fcfe922009-10-22 05:17:15 +0000779 case Type::Elaborated:
780 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
781 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000782
Douglas Gregor18857642009-04-30 17:32:17 +0000783 case Type::Typedef: {
784 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000785 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000786 Align = std::max(Aligned->getMaxAlignment(),
787 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000788 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
789 } else
790 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000791 break;
Chris Lattner71763312008-04-06 22:05:18 +0000792 }
Douglas Gregor18857642009-04-30 17:32:17 +0000793
794 case Type::TypeOfExpr:
795 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
796 .getTypePtr());
797
798 case Type::TypeOf:
799 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
800
Anders Carlsson395b4752009-06-24 19:06:50 +0000801 case Type::Decltype:
802 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
803 .getTypePtr());
804
Douglas Gregor18857642009-04-30 17:32:17 +0000805 case Type::QualifiedName:
806 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Douglas Gregor18857642009-04-30 17:32:17 +0000808 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000809 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000810 "Cannot request the size of a dependent type");
811 // FIXME: this is likely to be wrong once we support template
812 // aliases, since a template alias could refer to a typedef that
813 // has an __aligned__ attribute on it.
814 return getTypeInfo(getCanonicalType(T));
815 }
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Chris Lattner464175b2007-07-18 17:52:12 +0000817 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000818 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000819}
820
Chris Lattner34ebde42009-01-27 18:08:34 +0000821/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
822/// type for the current target in bits. This can be different than the ABI
823/// alignment in cases where it is beneficial for performance to overalign
824/// a data type.
825unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
826 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000827
828 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000829 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000830 T = CT->getElementType().getTypePtr();
831 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
832 T->isSpecificBuiltinType(BuiltinType::LongLong))
833 return std::max(ABIAlign, (unsigned)getTypeSize(T));
834
Chris Lattner34ebde42009-01-27 18:08:34 +0000835 return ABIAlign;
836}
837
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000838static void CollectLocalObjCIvars(ASTContext *Ctx,
839 const ObjCInterfaceDecl *OI,
840 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000841 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
842 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000843 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000844 if (!IVDecl->isInvalidDecl())
845 Fields.push_back(cast<FieldDecl>(IVDecl));
846 }
847}
848
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000849void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
850 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
851 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
852 CollectObjCIvars(SuperClass, Fields);
853 CollectLocalObjCIvars(this, OI, Fields);
854}
855
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000856/// ShallowCollectObjCIvars -
857/// Collect all ivars, including those synthesized, in the current class.
858///
859void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
860 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
861 bool CollectSynthesized) {
862 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
863 E = OI->ivar_end(); I != E; ++I) {
864 Ivars.push_back(*I);
865 }
866 if (CollectSynthesized)
867 CollectSynthesizedIvars(OI, Ivars);
868}
869
Fariborz Jahanian98200742009-05-12 18:14:29 +0000870void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
871 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000872 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
873 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000874 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
875 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Fariborz Jahanian98200742009-05-12 18:14:29 +0000877 // Also look into nested protocols.
878 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
879 E = PD->protocol_end(); P != E; ++P)
880 CollectProtocolSynthesizedIvars(*P, Ivars);
881}
882
883/// CollectSynthesizedIvars -
884/// This routine collect synthesized ivars for the designated class.
885///
886void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
887 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000888 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
889 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000890 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
891 Ivars.push_back(Ivar);
892 }
893 // Also look into interface's protocol list for properties declared
894 // in the protocol and whose ivars are synthesized.
895 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
896 PE = OI->protocol_end(); P != PE; ++P) {
897 ObjCProtocolDecl *PD = (*P);
898 CollectProtocolSynthesizedIvars(PD, Ivars);
899 }
900}
901
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000902/// CollectInheritedProtocols - Collect all protocols in current class and
903/// those inherited by it.
904void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
905 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
906 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
907 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
908 PE = OI->protocol_end(); P != PE; ++P) {
909 ObjCProtocolDecl *Proto = (*P);
910 Protocols.push_back(Proto);
911 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
912 PE = Proto->protocol_end(); P != PE; ++P)
913 CollectInheritedProtocols(*P, Protocols);
914 }
915
916 // Categories of this Interface.
917 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
918 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
919 CollectInheritedProtocols(CDeclChain, Protocols);
920 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
921 while (SD) {
922 CollectInheritedProtocols(SD, Protocols);
923 SD = SD->getSuperClass();
924 }
925 return;
926 }
927 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
928 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
929 PE = OC->protocol_end(); P != PE; ++P) {
930 ObjCProtocolDecl *Proto = (*P);
931 Protocols.push_back(Proto);
932 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
933 PE = Proto->protocol_end(); P != PE; ++P)
934 CollectInheritedProtocols(*P, Protocols);
935 }
936 return;
937 }
938 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
939 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
940 PE = OP->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}
950
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000951unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
952 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000953 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
954 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000955 if ((*I)->getPropertyIvarDecl())
956 ++count;
957
958 // Also look into nested protocols.
959 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
960 E = PD->protocol_end(); P != E; ++P)
961 count += CountProtocolSynthesizedIvars(*P);
962 return count;
963}
964
Mike Stump1eb44332009-09-09 15:08:12 +0000965unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000966 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000967 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
968 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000969 if ((*I)->getPropertyIvarDecl())
970 ++count;
971 }
972 // Also look into interface's protocol list for properties declared
973 // in the protocol and whose ivars are synthesized.
974 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
975 PE = OI->protocol_end(); P != PE; ++P) {
976 ObjCProtocolDecl *PD = (*P);
977 count += CountProtocolSynthesizedIvars(PD);
978 }
979 return count;
980}
981
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000982/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
983ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
984 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
985 I = ObjCImpls.find(D);
986 if (I != ObjCImpls.end())
987 return cast<ObjCImplementationDecl>(I->second);
988 return 0;
989}
990/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
991ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
992 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
993 I = ObjCImpls.find(D);
994 if (I != ObjCImpls.end())
995 return cast<ObjCCategoryImplDecl>(I->second);
996 return 0;
997}
998
999/// \brief Set the implementation of ObjCInterfaceDecl.
1000void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1001 ObjCImplementationDecl *ImplD) {
1002 assert(IFaceD && ImplD && "Passed null params");
1003 ObjCImpls[IFaceD] = ImplD;
1004}
1005/// \brief Set the implementation of ObjCCategoryDecl.
1006void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1007 ObjCCategoryImplDecl *ImplD) {
1008 assert(CatD && ImplD && "Passed null params");
1009 ObjCImpls[CatD] = ImplD;
1010}
1011
John McCalla93c9342009-12-07 02:54:59 +00001012/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001013///
John McCalla93c9342009-12-07 02:54:59 +00001014/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001015/// the TypeLoc wrappers.
1016///
1017/// \param T the type that will be the basis for type source info. This type
1018/// should refer to how the declarator was written in source code, not to
1019/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001020TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001021 unsigned DataSize) {
1022 if (!DataSize)
1023 DataSize = TypeLoc::getFullDataSizeForType(T);
1024 else
1025 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001026 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001027
John McCalla93c9342009-12-07 02:54:59 +00001028 TypeSourceInfo *TInfo =
1029 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1030 new (TInfo) TypeSourceInfo(T);
1031 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001032}
1033
John McCalla93c9342009-12-07 02:54:59 +00001034TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001035 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001036 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001037 DI->getTypeLoc().initialize(L);
1038 return DI;
1039}
1040
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001041/// getInterfaceLayoutImpl - Get or compute information about the
1042/// layout of the given interface.
1043///
1044/// \param Impl - If given, also include the layout of the interface's
1045/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001046const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001047ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1048 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001049 assert(!D->isForwardDecl() && "Invalid interface decl!");
1050
Devang Patel44a3dde2008-06-04 21:54:36 +00001051 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001052 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001053 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1054 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1055 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001056
Daniel Dunbar453addb2009-05-03 11:16:44 +00001057 // Add in synthesized ivar count if laying out an implementation.
1058 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001059 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001060 unsigned SynthCount = CountSynthesizedIvars(D);
1061 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001062 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001063 // entry. Note we can't cache this because we simply free all
1064 // entries later; however we shouldn't look up implementations
1065 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001066 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001067 return getObjCLayout(D, 0);
1068 }
1069
Mike Stump1eb44332009-09-09 15:08:12 +00001070 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001071 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1072 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Devang Patel44a3dde2008-06-04 21:54:36 +00001074 return *NewEntry;
1075}
1076
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001077const ASTRecordLayout &
1078ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1079 return getObjCLayout(D, 0);
1080}
1081
1082const ASTRecordLayout &
1083ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1084 return getObjCLayout(D->getClassInterface(), D);
1085}
1086
Devang Patel88a981b2007-11-01 19:11:01 +00001087/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001088/// specified record (struct/union/class), which indicates its size and field
1089/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001090const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001091 D = D->getDefinition(*this);
1092 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001093
Chris Lattner464175b2007-07-18 17:52:12 +00001094 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001095 // Note that we can't save a reference to the entry because this function
1096 // is recursive.
1097 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001098 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001099
Mike Stump1eb44332009-09-09 15:08:12 +00001100 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001101 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001102 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Chris Lattner5d2a6302007-07-18 18:26:58 +00001104 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001105}
1106
Chris Lattnera7674d82007-07-13 22:13:22 +00001107//===----------------------------------------------------------------------===//
1108// Type creation/memoization methods
1109//===----------------------------------------------------------------------===//
1110
John McCall0953e762009-09-24 19:53:00 +00001111QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1112 unsigned Fast = Quals.getFastQualifiers();
1113 Quals.removeFastQualifiers();
1114
1115 // Check if we've already instantiated this type.
1116 llvm::FoldingSetNodeID ID;
1117 ExtQuals::Profile(ID, TypeNode, Quals);
1118 void *InsertPos = 0;
1119 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1120 assert(EQ->getQualifiers() == Quals);
1121 QualType T = QualType(EQ, Fast);
1122 return T;
1123 }
1124
John McCall6b304a02009-09-24 23:30:46 +00001125 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001126 ExtQualNodes.InsertNode(New, InsertPos);
1127 QualType T = QualType(New, Fast);
1128 return T;
1129}
1130
1131QualType ASTContext::getVolatileType(QualType T) {
1132 QualType CanT = getCanonicalType(T);
1133 if (CanT.isVolatileQualified()) return T;
1134
1135 QualifierCollector Quals;
1136 const Type *TypeNode = Quals.strip(T);
1137 Quals.addVolatile();
1138
1139 return getExtQualType(TypeNode, Quals);
1140}
1141
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001142QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001143 QualType CanT = getCanonicalType(T);
1144 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001145 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001146
John McCall0953e762009-09-24 19:53:00 +00001147 // If we are composing extended qualifiers together, merge together
1148 // into one ExtQuals node.
1149 QualifierCollector Quals;
1150 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001151
John McCall0953e762009-09-24 19:53:00 +00001152 // If this type already has an address space specified, it cannot get
1153 // another one.
1154 assert(!Quals.hasAddressSpace() &&
1155 "Type cannot be in multiple addr spaces!");
1156 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001157
John McCall0953e762009-09-24 19:53:00 +00001158 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001159}
1160
Chris Lattnerb7d25532009-02-18 22:53:11 +00001161QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001162 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001163 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001164 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001165 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001167 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001168 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001169 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001170 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1171 return getPointerType(ResultType);
1172 }
1173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174
John McCall0953e762009-09-24 19:53:00 +00001175 // If we are composing extended qualifiers together, merge together
1176 // into one ExtQuals node.
1177 QualifierCollector Quals;
1178 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
John McCall0953e762009-09-24 19:53:00 +00001180 // If this type already has an ObjCGC specified, it cannot get
1181 // another one.
1182 assert(!Quals.hasObjCGCAttr() &&
1183 "Type cannot have multiple ObjCGCs!");
1184 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001185
John McCall0953e762009-09-24 19:53:00 +00001186 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001187}
Chris Lattnera7674d82007-07-13 22:13:22 +00001188
Mike Stump24556362009-07-25 21:26:53 +00001189QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001190 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001191 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001192 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001193 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001194 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001195 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001196 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001197 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001198 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001199 } else {
1200 assert (T->isFunctionType()
1201 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001203 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1204 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001205 } else {
1206 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1207 ResultType
1208 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1209 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1210 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1211 F->getNumExceptions(), F->exception_begin(), true);
1212 }
Mike Stump24556362009-07-25 21:26:53 +00001213 }
John McCall0953e762009-09-24 19:53:00 +00001214
Douglas Gregora4923eb2009-11-16 21:35:15 +00001215 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001216}
1217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218/// getComplexType - Return the uniqued reference to the type for a complex
1219/// number with the specified element type.
1220QualType ASTContext::getComplexType(QualType T) {
1221 // Unique pointers, to guarantee there is only one pointer of a particular
1222 // structure.
1223 llvm::FoldingSetNodeID ID;
1224 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 void *InsertPos = 0;
1227 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1228 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 // If the pointee type isn't canonical, this won't be a canonical type either,
1231 // so fill in the canonical type field.
1232 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001233 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001234 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 // Get the new insert position for the node we care about.
1237 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001238 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 }
John McCall6b304a02009-09-24 23:30:46 +00001240 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 Types.push_back(New);
1242 ComplexTypes.InsertNode(New, InsertPos);
1243 return QualType(New, 0);
1244}
1245
Eli Friedmanf98aba32009-02-13 02:31:07 +00001246QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1247 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1248 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1249 FixedWidthIntType *&Entry = Map[Width];
1250 if (!Entry)
1251 Entry = new FixedWidthIntType(Width, Signed);
1252 return QualType(Entry, 0);
1253}
Reid Spencer5f016e22007-07-11 17:01:13 +00001254
1255/// getPointerType - Return the uniqued reference to the type for a pointer to
1256/// the specified type.
1257QualType ASTContext::getPointerType(QualType T) {
1258 // Unique pointers, to guarantee there is only one pointer of a particular
1259 // structure.
1260 llvm::FoldingSetNodeID ID;
1261 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 void *InsertPos = 0;
1264 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1265 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 // If the pointee type isn't canonical, this won't be a canonical type either,
1268 // so fill in the canonical type field.
1269 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001270 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001271 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // Get the new insert position for the node we care about.
1274 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001275 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 }
John McCall6b304a02009-09-24 23:30:46 +00001277 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 Types.push_back(New);
1279 PointerTypes.InsertNode(New, InsertPos);
1280 return QualType(New, 0);
1281}
1282
Mike Stump1eb44332009-09-09 15:08:12 +00001283/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001284/// a pointer to the specified block.
1285QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001286 assert(T->isFunctionType() && "block of function types only");
1287 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001288 // structure.
1289 llvm::FoldingSetNodeID ID;
1290 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Steve Naroff5618bd42008-08-27 16:04:49 +00001292 void *InsertPos = 0;
1293 if (BlockPointerType *PT =
1294 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1295 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
1297 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001298 // type either so fill in the canonical type field.
1299 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001300 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001301 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Steve Naroff5618bd42008-08-27 16:04:49 +00001303 // Get the new insert position for the node we care about.
1304 BlockPointerType *NewIP =
1305 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001306 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001307 }
John McCall6b304a02009-09-24 23:30:46 +00001308 BlockPointerType *New
1309 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001310 Types.push_back(New);
1311 BlockPointerTypes.InsertNode(New, InsertPos);
1312 return QualType(New, 0);
1313}
1314
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315/// getLValueReferenceType - Return the uniqued reference to the type for an
1316/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001317QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // Unique pointers, to guarantee there is only one pointer of a particular
1319 // structure.
1320 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001321 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001322
1323 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001324 if (LValueReferenceType *RT =
1325 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001327
John McCall54e14c42009-10-22 22:37:11 +00001328 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1329
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 // If the referencee type isn't canonical, this won't be a canonical type
1331 // either, so fill in the canonical type field.
1332 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001333 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1334 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1335 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001338 LValueReferenceType *NewIP =
1339 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001340 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 }
1342
John McCall6b304a02009-09-24 23:30:46 +00001343 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001344 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1345 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001347 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001348
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001349 return QualType(New, 0);
1350}
1351
1352/// getRValueReferenceType - Return the uniqued reference to the type for an
1353/// rvalue reference to the specified type.
1354QualType ASTContext::getRValueReferenceType(QualType T) {
1355 // Unique pointers, to guarantee there is only one pointer of a particular
1356 // structure.
1357 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001358 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001359
1360 void *InsertPos = 0;
1361 if (RValueReferenceType *RT =
1362 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1363 return QualType(RT, 0);
1364
John McCall54e14c42009-10-22 22:37:11 +00001365 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1366
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001367 // If the referencee type isn't canonical, this won't be a canonical type
1368 // either, so fill in the canonical type field.
1369 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001370 if (InnerRef || !T.isCanonical()) {
1371 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1372 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001373
1374 // Get the new insert position for the node we care about.
1375 RValueReferenceType *NewIP =
1376 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1377 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1378 }
1379
John McCall6b304a02009-09-24 23:30:46 +00001380 RValueReferenceType *New
1381 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001382 Types.push_back(New);
1383 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 return QualType(New, 0);
1385}
1386
Sebastian Redlf30208a2009-01-24 21:16:55 +00001387/// getMemberPointerType - Return the uniqued reference to the type for a
1388/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001389QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001390 // Unique pointers, to guarantee there is only one pointer of a particular
1391 // structure.
1392 llvm::FoldingSetNodeID ID;
1393 MemberPointerType::Profile(ID, T, Cls);
1394
1395 void *InsertPos = 0;
1396 if (MemberPointerType *PT =
1397 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1398 return QualType(PT, 0);
1399
1400 // If the pointee or class type isn't canonical, this won't be a canonical
1401 // type either, so fill in the canonical type field.
1402 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001403 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001404 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1405
1406 // Get the new insert position for the node we care about.
1407 MemberPointerType *NewIP =
1408 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1409 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1410 }
John McCall6b304a02009-09-24 23:30:46 +00001411 MemberPointerType *New
1412 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001413 Types.push_back(New);
1414 MemberPointerTypes.InsertNode(New, InsertPos);
1415 return QualType(New, 0);
1416}
1417
Mike Stump1eb44332009-09-09 15:08:12 +00001418/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001419/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001420QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001421 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001422 ArrayType::ArraySizeModifier ASM,
1423 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001424 assert((EltTy->isDependentType() ||
1425 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001426 "Constant array of VLAs is illegal!");
1427
Chris Lattner38aeec72009-05-13 04:12:56 +00001428 // Convert the array size into a canonical width matching the pointer size for
1429 // the target.
1430 llvm::APInt ArySize(ArySizeIn);
1431 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001434 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001437 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001438 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 // If the element type isn't canonical, this won't be a canonical type either,
1442 // so fill in the canonical type field.
1443 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001444 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001445 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001446 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001448 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001449 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001450 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
John McCall6b304a02009-09-24 23:30:46 +00001453 ConstantArrayType *New = new(*this,TypeAlignment)
1454 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001455 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 Types.push_back(New);
1457 return QualType(New, 0);
1458}
1459
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001460/// getVariableArrayType - Returns a non-unique reference to the type for a
1461/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001462QualType ASTContext::getVariableArrayType(QualType EltTy,
1463 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001464 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001465 unsigned EltTypeQuals,
1466 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001467 // Since we don't unique expressions, it isn't possible to unique VLA's
1468 // that have an expression provided for their size.
1469
John McCall6b304a02009-09-24 23:30:46 +00001470 VariableArrayType *New = new(*this, TypeAlignment)
1471 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001472
1473 VariableArrayTypes.push_back(New);
1474 Types.push_back(New);
1475 return QualType(New, 0);
1476}
1477
Douglas Gregor898574e2008-12-05 23:32:09 +00001478/// getDependentSizedArrayType - Returns a non-unique reference to
1479/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001480/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001481QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1482 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001483 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001484 unsigned EltTypeQuals,
1485 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001486 assert((!NumElts || NumElts->isTypeDependent() ||
1487 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001488 "Size must be type- or value-dependent!");
1489
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001490 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001491 DependentSizedArrayType *Canon = 0;
1492
1493 if (NumElts) {
1494 // Dependently-sized array types that do not have a specified
1495 // number of elements will have their sizes deduced from an
1496 // initializer.
1497 llvm::FoldingSetNodeID ID;
1498 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1499 EltTypeQuals, NumElts);
1500
1501 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1502 }
1503
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001504 DependentSizedArrayType *New;
1505 if (Canon) {
1506 // We already have a canonical version of this array type; use it as
1507 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001508 New = new (*this, TypeAlignment)
1509 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1510 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001511 } else {
1512 QualType CanonEltTy = getCanonicalType(EltTy);
1513 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001514 New = new (*this, TypeAlignment)
1515 DependentSizedArrayType(*this, EltTy, QualType(),
1516 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001517
1518 if (NumElts)
1519 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001520 } else {
1521 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1522 ASM, EltTypeQuals,
1523 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001524 New = new (*this, TypeAlignment)
1525 DependentSizedArrayType(*this, EltTy, Canon,
1526 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001527 }
1528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Douglas Gregor898574e2008-12-05 23:32:09 +00001530 Types.push_back(New);
1531 return QualType(New, 0);
1532}
1533
Eli Friedmanc5773c42008-02-15 18:16:39 +00001534QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1535 ArrayType::ArraySizeModifier ASM,
1536 unsigned EltTypeQuals) {
1537 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001538 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001539
1540 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001541 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001542 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1543 return QualType(ATP, 0);
1544
1545 // If the element type isn't canonical, this won't be a canonical type
1546 // either, so fill in the canonical type field.
1547 QualType Canonical;
1548
John McCall467b27b2009-10-22 20:10:53 +00001549 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001550 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001551 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001552
1553 // Get the new insert position for the node we care about.
1554 IncompleteArrayType *NewIP =
1555 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001556 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001557 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001558
John McCall6b304a02009-09-24 23:30:46 +00001559 IncompleteArrayType *New = new (*this, TypeAlignment)
1560 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001561
1562 IncompleteArrayTypes.InsertNode(New, InsertPos);
1563 Types.push_back(New);
1564 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001565}
1566
Steve Naroff73322922007-07-18 18:00:27 +00001567/// getVectorType - Return the unique reference to a vector type of
1568/// the specified element type and size. VectorType must be a built-in type.
1569QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Chris Lattnerf52ab252008-04-06 22:59:24 +00001572 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001573 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 // Check if we've already instantiated a vector of this type.
1576 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001577 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 void *InsertPos = 0;
1579 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1580 return QualType(VTP, 0);
1581
1582 // If the element type isn't canonical, this won't be a canonical type either,
1583 // so fill in the canonical type field.
1584 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001585 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001586 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 // Get the new insert position for the node we care about.
1589 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001590 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 }
John McCall6b304a02009-09-24 23:30:46 +00001592 VectorType *New = new (*this, TypeAlignment)
1593 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 VectorTypes.InsertNode(New, InsertPos);
1595 Types.push_back(New);
1596 return QualType(New, 0);
1597}
1598
Nate Begeman213541a2008-04-18 23:10:10 +00001599/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001600/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001601QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001602 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Chris Lattnerf52ab252008-04-06 22:59:24 +00001604 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001605 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Steve Naroff73322922007-07-18 18:00:27 +00001607 // Check if we've already instantiated a vector of this type.
1608 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001609 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001610 void *InsertPos = 0;
1611 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1612 return QualType(VTP, 0);
1613
1614 // If the element type isn't canonical, this won't be a canonical type either,
1615 // so fill in the canonical type field.
1616 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001617 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001618 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Steve Naroff73322922007-07-18 18:00:27 +00001620 // Get the new insert position for the node we care about.
1621 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001622 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001623 }
John McCall6b304a02009-09-24 23:30:46 +00001624 ExtVectorType *New = new (*this, TypeAlignment)
1625 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001626 VectorTypes.InsertNode(New, InsertPos);
1627 Types.push_back(New);
1628 return QualType(New, 0);
1629}
1630
Mike Stump1eb44332009-09-09 15:08:12 +00001631QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001632 Expr *SizeExpr,
1633 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001634 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001635 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001636 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001638 void *InsertPos = 0;
1639 DependentSizedExtVectorType *Canon
1640 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1641 DependentSizedExtVectorType *New;
1642 if (Canon) {
1643 // We already have a canonical version of this array type; use it as
1644 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001645 New = new (*this, TypeAlignment)
1646 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1647 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001648 } else {
1649 QualType CanonVecTy = getCanonicalType(vecType);
1650 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001651 New = new (*this, TypeAlignment)
1652 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1653 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001654 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1655 } else {
1656 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1657 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001658 New = new (*this, TypeAlignment)
1659 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001660 }
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001663 Types.push_back(New);
1664 return QualType(New, 0);
1665}
1666
Douglas Gregor72564e72009-02-26 23:50:07 +00001667/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001668///
Mike Stump24556362009-07-25 21:26:53 +00001669QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // Unique functions, to guarantee there is only one function of a particular
1671 // structure.
1672 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001673 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001676 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001677 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001681 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001682 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001685 FunctionNoProtoType *NewIP =
1686 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001687 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
John McCall6b304a02009-09-24 23:30:46 +00001690 FunctionNoProtoType *New = new (*this, TypeAlignment)
1691 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001693 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 return QualType(New, 0);
1695}
1696
1697/// getFunctionType - Return a normal function type with a typed argument
1698/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001699QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001700 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001701 unsigned TypeQuals, bool hasExceptionSpec,
1702 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001703 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // Unique functions, to guarantee there is only one function of a particular
1705 // structure.
1706 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001707 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001708 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001709 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001710
1711 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001712 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001713 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001715
1716 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001717 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001719 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 isCanonical = false;
1721
1722 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001723 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 QualType Canonical;
1725 if (!isCanonical) {
1726 llvm::SmallVector<QualType, 16> CanonicalArgs;
1727 CanonicalArgs.reserve(NumArgs);
1728 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001729 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001730
Chris Lattnerf52ab252008-04-06 22:59:24 +00001731 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001732 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001733 isVariadic, TypeQuals, false,
1734 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001735
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001737 FunctionProtoType *NewIP =
1738 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001739 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001741
Douglas Gregor72564e72009-02-26 23:50:07 +00001742 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001743 // for two variable size arrays (for parameter and exception types) at the
1744 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001745 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001746 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1747 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001748 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001749 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001750 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001751 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001753 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 return QualType(FTP, 0);
1755}
1756
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001757/// getTypeDeclType - Return the unique reference to the type for the
1758/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001759QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001760 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001761 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001763 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001764 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001765 else if (isa<TemplateTypeParmDecl>(Decl)) {
1766 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001767 } else if (ObjCInterfaceDecl *ObjCInterface
1768 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001769 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001770
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001771 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001772 if (PrevDecl)
1773 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001774 else
John McCall6b304a02009-09-24 23:30:46 +00001775 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001776 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001777 if (PrevDecl)
1778 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001779 else
John McCall6b304a02009-09-24 23:30:46 +00001780 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001781 } else if (UnresolvedUsingTypenameDecl *Using =
1782 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1783 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001784 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001785 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001786
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001787 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001788 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001789}
1790
Reid Spencer5f016e22007-07-11 17:01:13 +00001791/// getTypedefType - Return the unique reference to the type for the
1792/// specified typename decl.
1793QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1794 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Chris Lattnerf52ab252008-04-06 22:59:24 +00001796 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001797 Decl->TypeForDecl = new(*this, TypeAlignment)
1798 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 Types.push_back(Decl->TypeForDecl);
1800 return QualType(Decl->TypeForDecl, 0);
1801}
1802
John McCall49a832b2009-10-18 09:09:24 +00001803/// \brief Retrieve a substitution-result type.
1804QualType
1805ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1806 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001807 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001808 && "replacement types must always be canonical");
1809
1810 llvm::FoldingSetNodeID ID;
1811 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1812 void *InsertPos = 0;
1813 SubstTemplateTypeParmType *SubstParm
1814 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1815
1816 if (!SubstParm) {
1817 SubstParm = new (*this, TypeAlignment)
1818 SubstTemplateTypeParmType(Parm, Replacement);
1819 Types.push_back(SubstParm);
1820 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1821 }
1822
1823 return QualType(SubstParm, 0);
1824}
1825
Douglas Gregorfab9d672009-02-05 23:33:38 +00001826/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001827/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001828/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001829QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001830 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001831 IdentifierInfo *Name) {
1832 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001833 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001834 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001835 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001836 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1837
1838 if (TypeParm)
1839 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001841 if (Name) {
1842 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001843 TypeParm = new (*this, TypeAlignment)
1844 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001845 } else
John McCall6b304a02009-09-24 23:30:46 +00001846 TypeParm = new (*this, TypeAlignment)
1847 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001848
1849 Types.push_back(TypeParm);
1850 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1851
1852 return QualType(TypeParm, 0);
1853}
1854
Mike Stump1eb44332009-09-09 15:08:12 +00001855QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001856ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001857 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001858 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001859 unsigned NumArgs = Args.size();
1860
John McCall833ca992009-10-29 08:12:44 +00001861 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1862 ArgVec.reserve(NumArgs);
1863 for (unsigned i = 0; i != NumArgs; ++i)
1864 ArgVec.push_back(Args[i].getArgument());
1865
1866 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1867}
1868
1869QualType
1870ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001871 const TemplateArgument *Args,
1872 unsigned NumArgs,
1873 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001874 if (!Canon.isNull())
1875 Canon = getCanonicalType(Canon);
1876 else {
1877 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001878 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1879 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1880 CanonArgs.reserve(NumArgs);
1881 for (unsigned I = 0; I != NumArgs; ++I)
1882 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1883
1884 // Determine whether this canonical template specialization type already
1885 // exists.
1886 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001887 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001888 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001889
1890 void *InsertPos = 0;
1891 TemplateSpecializationType *Spec
1892 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Douglas Gregor1275ae02009-07-28 23:00:59 +00001894 if (!Spec) {
1895 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001896 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001897 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001898 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001899 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001900 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001901 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001902 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001903 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001904 }
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregorb88e8882009-07-30 17:40:51 +00001906 if (Canon.isNull())
1907 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001908 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001909 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001910 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001911
Douglas Gregor1275ae02009-07-28 23:00:59 +00001912 // Allocate the (non-canonical) template specialization type, but don't
1913 // try to unique it: these types typically have location information that
1914 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001915 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001916 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001917 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001918 TemplateSpecializationType *Spec
1919 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001920 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Douglas Gregor55f6b142009-02-09 18:46:07 +00001922 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001923 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001924}
1925
Mike Stump1eb44332009-09-09 15:08:12 +00001926QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001927ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001928 QualType NamedType) {
1929 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001930 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001931
1932 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001933 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001934 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1935 if (T)
1936 return QualType(T, 0);
1937
Mike Stump1eb44332009-09-09 15:08:12 +00001938 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001939 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001940 Types.push_back(T);
1941 QualifiedNameTypes.InsertNode(T, InsertPos);
1942 return QualType(T, 0);
1943}
1944
Mike Stump1eb44332009-09-09 15:08:12 +00001945QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001946 const IdentifierInfo *Name,
1947 QualType Canon) {
1948 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1949
1950 if (Canon.isNull()) {
1951 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1952 if (CanonNNS != NNS)
1953 Canon = getTypenameType(CanonNNS, Name);
1954 }
1955
1956 llvm::FoldingSetNodeID ID;
1957 TypenameType::Profile(ID, NNS, Name);
1958
1959 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001960 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001961 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1962 if (T)
1963 return QualType(T, 0);
1964
1965 T = new (*this) TypenameType(NNS, Name, Canon);
1966 Types.push_back(T);
1967 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001968 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001969}
1970
Mike Stump1eb44332009-09-09 15:08:12 +00001971QualType
1972ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001973 const TemplateSpecializationType *TemplateId,
1974 QualType Canon) {
1975 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1976
1977 if (Canon.isNull()) {
1978 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1979 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1980 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1981 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001982 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001983 assert(CanonTemplateId &&
1984 "Canonical type must also be a template specialization type");
1985 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1986 }
1987 }
1988
1989 llvm::FoldingSetNodeID ID;
1990 TypenameType::Profile(ID, NNS, TemplateId);
1991
1992 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001993 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001994 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1995 if (T)
1996 return QualType(T, 0);
1997
1998 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1999 Types.push_back(T);
2000 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002001 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002002}
2003
John McCall7da24312009-09-05 00:15:47 +00002004QualType
2005ASTContext::getElaboratedType(QualType UnderlyingType,
2006 ElaboratedType::TagKind Tag) {
2007 llvm::FoldingSetNodeID ID;
2008 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCall7da24312009-09-05 00:15:47 +00002010 void *InsertPos = 0;
2011 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2012 if (T)
2013 return QualType(T, 0);
2014
2015 QualType Canon = getCanonicalType(UnderlyingType);
2016
2017 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2018 Types.push_back(T);
2019 ElaboratedTypes.InsertNode(T, InsertPos);
2020 return QualType(T, 0);
2021}
2022
Chris Lattner88cb27a2008-04-07 04:56:42 +00002023/// CmpProtocolNames - Comparison predicate for sorting protocols
2024/// alphabetically.
2025static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2026 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002027 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002028}
2029
John McCall54e14c42009-10-22 22:37:11 +00002030static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2031 unsigned NumProtocols) {
2032 if (NumProtocols == 0) return true;
2033
2034 for (unsigned i = 1; i != NumProtocols; ++i)
2035 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2036 return false;
2037 return true;
2038}
2039
2040static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002041 unsigned &NumProtocols) {
2042 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Chris Lattner88cb27a2008-04-07 04:56:42 +00002044 // Sort protocols, keyed by name.
2045 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2046
2047 // Remove duplicates.
2048 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2049 NumProtocols = ProtocolsEnd-Protocols;
2050}
2051
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002052/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2053/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002054QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002055 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002056 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002057 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002058 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002059
2060 void *InsertPos = 0;
2061 if (ObjCObjectPointerType *QT =
2062 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2063 return QualType(QT, 0);
2064
John McCall54e14c42009-10-22 22:37:11 +00002065 // Sort the protocol list alphabetically to canonicalize it.
2066 QualType Canonical;
2067 if (!InterfaceT.isCanonical() ||
2068 !areSortedAndUniqued(Protocols, NumProtocols)) {
2069 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2070 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2071 unsigned UniqueCount = NumProtocols;
2072
2073 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2074 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2075
2076 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2077 &Sorted[0], UniqueCount);
2078 } else {
2079 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2080 Protocols, NumProtocols);
2081 }
2082
2083 // Regenerate InsertPos.
2084 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2085 }
2086
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002087 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002088 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002089 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002091 Types.push_back(QType);
2092 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2093 return QualType(QType, 0);
2094}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002095
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002096/// getObjCInterfaceType - Return the unique reference to the type for the
2097/// specified ObjC interface decl. The list of protocols is optional.
2098QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002099 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002100 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002101 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002103 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002104 if (ObjCInterfaceType *QT =
2105 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002106 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
John McCall54e14c42009-10-22 22:37:11 +00002108 // Sort the protocol list alphabetically to canonicalize it.
2109 QualType Canonical;
2110 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2111 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2112 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2113
2114 unsigned UniqueCount = NumProtocols;
2115 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2116
2117 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2118
2119 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2120 }
2121
John McCall6b304a02009-09-24 23:30:46 +00002122 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002123 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002124 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002125
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002126 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002127 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002128 return QualType(QType, 0);
2129}
2130
Douglas Gregor72564e72009-02-26 23:50:07 +00002131/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2132/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002133/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002134/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002135/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002136QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002137 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002138 if (tofExpr->isTypeDependent()) {
2139 llvm::FoldingSetNodeID ID;
2140 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Douglas Gregorb1975722009-07-30 23:18:24 +00002142 void *InsertPos = 0;
2143 DependentTypeOfExprType *Canon
2144 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2145 if (Canon) {
2146 // We already have a "canonical" version of an identical, dependent
2147 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002148 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002149 QualType((TypeOfExprType*)Canon, 0));
2150 }
2151 else {
2152 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002153 Canon
2154 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002155 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2156 toe = Canon;
2157 }
2158 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002159 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002160 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002161 }
Steve Naroff9752f252007-08-01 18:02:17 +00002162 Types.push_back(toe);
2163 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002164}
2165
Steve Naroff9752f252007-08-01 18:02:17 +00002166/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2167/// TypeOfType AST's. The only motivation to unique these nodes would be
2168/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002169/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002170/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002171QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002172 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002173 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002174 Types.push_back(tot);
2175 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002176}
2177
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002178/// getDecltypeForExpr - Given an expr, will return the decltype for that
2179/// expression, according to the rules in C++0x [dcl.type.simple]p4
2180static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002181 if (e->isTypeDependent())
2182 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002184 // If e is an id expression or a class member access, decltype(e) is defined
2185 // as the type of the entity named by e.
2186 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2187 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2188 return VD->getType();
2189 }
2190 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2191 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2192 return FD->getType();
2193 }
2194 // If e is a function call or an invocation of an overloaded operator,
2195 // (parentheses around e are ignored), decltype(e) is defined as the
2196 // return type of that function.
2197 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2198 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002200 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
2202 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002203 // defined as T&, otherwise decltype(e) is defined as T.
2204 if (e->isLvalue(Context) == Expr::LV_Valid)
2205 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002207 return T;
2208}
2209
Anders Carlsson395b4752009-06-24 19:06:50 +00002210/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2211/// DecltypeType AST's. The only motivation to unique these nodes would be
2212/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002213/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002214/// on canonical type's (which are always unique).
2215QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002216 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002217 if (e->isTypeDependent()) {
2218 llvm::FoldingSetNodeID ID;
2219 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002221 void *InsertPos = 0;
2222 DependentDecltypeType *Canon
2223 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2224 if (Canon) {
2225 // We already have a "canonical" version of an equivalent, dependent
2226 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002227 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002228 QualType((DecltypeType*)Canon, 0));
2229 }
2230 else {
2231 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002232 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002233 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2234 dt = Canon;
2235 }
2236 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002237 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002238 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002239 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002240 Types.push_back(dt);
2241 return QualType(dt, 0);
2242}
2243
Reid Spencer5f016e22007-07-11 17:01:13 +00002244/// getTagDeclType - Return the unique reference to the type for the
2245/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002246QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002247 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002248 // FIXME: What is the design on getTagDeclType when it requires casting
2249 // away const? mutable?
2250 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002251}
2252
Mike Stump1eb44332009-09-09 15:08:12 +00002253/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2254/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2255/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002256QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002257 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002258}
2259
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002260/// getSignedWCharType - Return the type of "signed wchar_t".
2261/// Used when in C++, as a GCC extension.
2262QualType ASTContext::getSignedWCharType() const {
2263 // FIXME: derive from "Target" ?
2264 return WCharTy;
2265}
2266
2267/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2268/// Used when in C++, as a GCC extension.
2269QualType ASTContext::getUnsignedWCharType() const {
2270 // FIXME: derive from "Target" ?
2271 return UnsignedIntTy;
2272}
2273
Chris Lattner8b9023b2007-07-13 03:05:23 +00002274/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2275/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2276QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002277 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002278}
2279
Chris Lattnere6327742008-04-02 05:18:44 +00002280//===----------------------------------------------------------------------===//
2281// Type Operators
2282//===----------------------------------------------------------------------===//
2283
John McCall54e14c42009-10-22 22:37:11 +00002284CanQualType ASTContext::getCanonicalParamType(QualType T) {
2285 // Push qualifiers into arrays, and then discard any remaining
2286 // qualifiers.
2287 T = getCanonicalType(T);
2288 const Type *Ty = T.getTypePtr();
2289
2290 QualType Result;
2291 if (isa<ArrayType>(Ty)) {
2292 Result = getArrayDecayedType(QualType(Ty,0));
2293 } else if (isa<FunctionType>(Ty)) {
2294 Result = getPointerType(QualType(Ty, 0));
2295 } else {
2296 Result = QualType(Ty, 0);
2297 }
2298
2299 return CanQualType::CreateUnsafe(Result);
2300}
2301
Chris Lattner77c96472008-04-06 22:41:35 +00002302/// getCanonicalType - Return the canonical (structural) type corresponding to
2303/// the specified potentially non-canonical type. The non-canonical version
2304/// of a type may have many "decorated" versions of types. Decorators can
2305/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2306/// to be free of any of these, allowing two canonical types to be compared
2307/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002308CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002309 QualifierCollector Quals;
2310 const Type *Ptr = Quals.strip(T);
2311 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002312
John McCall0953e762009-09-24 19:53:00 +00002313 // The canonical internal type will be the canonical type *except*
2314 // that we push type qualifiers down through array types.
2315
2316 // If there are no new qualifiers to push down, stop here.
2317 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002318 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002319
John McCall0953e762009-09-24 19:53:00 +00002320 // If the type qualifiers are on an array type, get the canonical
2321 // type of the array with the qualifiers applied to the element
2322 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002323 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2324 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002325 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002327 // Get the canonical version of the element with the extra qualifiers on it.
2328 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002329 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002330 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002332 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002333 return CanQualType::CreateUnsafe(
2334 getConstantArrayType(NewEltTy, CAT->getSize(),
2335 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002336 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002337 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002338 return CanQualType::CreateUnsafe(
2339 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002340 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregor898574e2008-12-05 23:32:09 +00002342 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002343 return CanQualType::CreateUnsafe(
2344 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002345 DSAT->getSizeExpr() ?
2346 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002347 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002348 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002349 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002350
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002351 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002352 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002353 VAT->getSizeExpr() ?
2354 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002355 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002356 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002357 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002358}
2359
John McCall80ad16f2009-11-24 18:42:40 +00002360DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2361 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2362 return TD->getDeclName();
2363
2364 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2365 if (DTN->isIdentifier()) {
2366 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2367 } else {
2368 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2369 }
2370 }
2371
John McCall0bd6feb2009-12-02 08:04:21 +00002372 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2373 assert(Storage);
2374 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002375}
2376
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002377TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2378 // If this template name refers to a template, the canonical
2379 // template name merely stores the template itself.
2380 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002381 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002382
John McCall0bd6feb2009-12-02 08:04:21 +00002383 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002384
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002385 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2386 assert(DTN && "Non-dependent template names must refer to template decls.");
2387 return DTN->CanonicalTemplateName;
2388}
2389
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002390bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2391 X = getCanonicalTemplateName(X);
2392 Y = getCanonicalTemplateName(Y);
2393 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2394}
2395
Mike Stump1eb44332009-09-09 15:08:12 +00002396TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002397ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2398 switch (Arg.getKind()) {
2399 case TemplateArgument::Null:
2400 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Douglas Gregor1275ae02009-07-28 23:00:59 +00002402 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002403 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Douglas Gregor1275ae02009-07-28 23:00:59 +00002405 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002406 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Douglas Gregor788cd062009-11-11 01:00:40 +00002408 case TemplateArgument::Template:
2409 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2410
Douglas Gregor1275ae02009-07-28 23:00:59 +00002411 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002412 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002413 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Douglas Gregor1275ae02009-07-28 23:00:59 +00002415 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002416 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Douglas Gregor1275ae02009-07-28 23:00:59 +00002418 case TemplateArgument::Pack: {
2419 // FIXME: Allocate in ASTContext
2420 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2421 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002422 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002423 AEnd = Arg.pack_end();
2424 A != AEnd; (void)++A, ++Idx)
2425 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Douglas Gregor1275ae02009-07-28 23:00:59 +00002427 TemplateArgument Result;
2428 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2429 return Result;
2430 }
2431 }
2432
2433 // Silence GCC warning
2434 assert(false && "Unhandled template argument kind");
2435 return TemplateArgument();
2436}
2437
Douglas Gregord57959a2009-03-27 23:10:48 +00002438NestedNameSpecifier *
2439ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002440 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002441 return 0;
2442
2443 switch (NNS->getKind()) {
2444 case NestedNameSpecifier::Identifier:
2445 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002446 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002447 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2448 NNS->getAsIdentifier());
2449
2450 case NestedNameSpecifier::Namespace:
2451 // A namespace is canonical; build a nested-name-specifier with
2452 // this namespace and no prefix.
2453 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2454
2455 case NestedNameSpecifier::TypeSpec:
2456 case NestedNameSpecifier::TypeSpecWithTemplate: {
2457 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002458 return NestedNameSpecifier::Create(*this, 0,
2459 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002460 T.getTypePtr());
2461 }
2462
2463 case NestedNameSpecifier::Global:
2464 // The global specifier is canonical and unique.
2465 return NNS;
2466 }
2467
2468 // Required to silence a GCC warning
2469 return 0;
2470}
2471
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002472
2473const ArrayType *ASTContext::getAsArrayType(QualType T) {
2474 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002475 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002476 // Handle the common positive case fast.
2477 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2478 return AT;
2479 }
Mike Stump1eb44332009-09-09 15:08:12 +00002480
John McCall0953e762009-09-24 19:53:00 +00002481 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002482 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002483 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002484 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002485
John McCall0953e762009-09-24 19:53:00 +00002486 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002487 // implements C99 6.7.3p8: "If the specification of an array type includes
2488 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002490 // If we get here, we either have type qualifiers on the type, or we have
2491 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002492 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002493
John McCall0953e762009-09-24 19:53:00 +00002494 QualifierCollector Qs;
2495 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002497 // If we have a simple case, just return now.
2498 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002499 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002500 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002502 // Otherwise, we have an array and we have qualifiers on it. Push the
2503 // qualifiers into the array element type and return a new array type.
2504 // Get the canonical version of the element with the extra qualifiers on it.
2505 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002506 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002507
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002508 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2509 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2510 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002511 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002512 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2513 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2514 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002515 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002516
Mike Stump1eb44332009-09-09 15:08:12 +00002517 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002518 = dyn_cast<DependentSizedArrayType>(ATy))
2519 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002520 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002521 DSAT->getSizeExpr() ?
2522 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002523 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002524 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002525 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002527 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002528 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002529 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002530 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002531 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002532 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002533 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002534}
2535
2536
Chris Lattnere6327742008-04-02 05:18:44 +00002537/// getArrayDecayedType - Return the properly qualified result of decaying the
2538/// specified array type to a pointer. This operation is non-trivial when
2539/// handling typedefs etc. The canonical type of "T" must be an array type,
2540/// this returns a pointer to a properly qualified element of the array.
2541///
2542/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2543QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002544 // Get the element type with 'getAsArrayType' so that we don't lose any
2545 // typedefs in the element type of the array. This also handles propagation
2546 // of type qualifiers from the array type into the element type if present
2547 // (C99 6.7.3p8).
2548 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2549 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002551 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002552
2553 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002554 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002555}
2556
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002557QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002558 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002559 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002560 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002561 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2562 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002563 } else {
John McCall0953e762009-09-24 19:53:00 +00002564 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002565 }
2566 }
2567}
2568
Anders Carlssonfbbce492009-09-25 01:23:32 +00002569QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2570 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Anders Carlssonfbbce492009-09-25 01:23:32 +00002572 if (const ArrayType *AT = getAsArrayType(ElemTy))
2573 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Anders Carlsson6183a992008-12-21 03:44:36 +00002575 return ElemTy;
2576}
2577
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002578/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002579uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002580ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2581 uint64_t ElementCount = 1;
2582 do {
2583 ElementCount *= CA->getSize().getZExtValue();
2584 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2585 } while (CA);
2586 return ElementCount;
2587}
2588
Reid Spencer5f016e22007-07-11 17:01:13 +00002589/// getFloatingRank - Return a relative rank for floating point types.
2590/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002591static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002592 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002594
John McCall183700f2009-09-21 23:43:11 +00002595 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2596 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002597 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 case BuiltinType::Float: return FloatRank;
2599 case BuiltinType::Double: return DoubleRank;
2600 case BuiltinType::LongDouble: return LongDoubleRank;
2601 }
2602}
2603
Mike Stump1eb44332009-09-09 15:08:12 +00002604/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2605/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002606/// 'typeDomain' is a real floating point or complex type.
2607/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002608QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2609 QualType Domain) const {
2610 FloatingRank EltRank = getFloatingRank(Size);
2611 if (Domain->isComplexType()) {
2612 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002613 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002614 case FloatRank: return FloatComplexTy;
2615 case DoubleRank: return DoubleComplexTy;
2616 case LongDoubleRank: return LongDoubleComplexTy;
2617 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 }
Chris Lattner1361b112008-04-06 23:58:54 +00002619
2620 assert(Domain->isRealFloatingType() && "Unknown domain!");
2621 switch (EltRank) {
2622 default: assert(0 && "getFloatingRank(): illegal value for rank");
2623 case FloatRank: return FloatTy;
2624 case DoubleRank: return DoubleTy;
2625 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002626 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002627}
2628
Chris Lattner7cfeb082008-04-06 23:55:33 +00002629/// getFloatingTypeOrder - Compare the rank of the two specified floating
2630/// point types, ignoring the domain of the type (i.e. 'double' ==
2631/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002632/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002633int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2634 FloatingRank LHSR = getFloatingRank(LHS);
2635 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Chris Lattnera75cea32008-04-06 23:38:49 +00002637 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002638 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002639 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002640 return 1;
2641 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002642}
2643
Chris Lattnerf52ab252008-04-06 22:59:24 +00002644/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2645/// routine will assert if passed a built-in type that isn't an integer or enum,
2646/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002647unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002648 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002649 if (EnumType* ET = dyn_cast<EnumType>(T))
2650 T = ET->getDecl()->getIntegerType().getTypePtr();
2651
Eli Friedmana3426752009-07-05 23:44:27 +00002652 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2653 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2654
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002655 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2656 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2657
2658 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2659 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2660
Eli Friedmanf98aba32009-02-13 02:31:07 +00002661 // There are two things which impact the integer rank: the width, and
2662 // the ordering of builtins. The builtin ordering is encoded in the
2663 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002664 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002665 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002666
Chris Lattnerf52ab252008-04-06 22:59:24 +00002667 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002668 default: assert(0 && "getIntegerRank(): not a built-in integer");
2669 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002670 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002671 case BuiltinType::Char_S:
2672 case BuiltinType::Char_U:
2673 case BuiltinType::SChar:
2674 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002675 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002676 case BuiltinType::Short:
2677 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002678 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002679 case BuiltinType::Int:
2680 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002681 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002682 case BuiltinType::Long:
2683 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002684 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002685 case BuiltinType::LongLong:
2686 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002687 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002688 case BuiltinType::Int128:
2689 case BuiltinType::UInt128:
2690 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002691 }
2692}
2693
Eli Friedman04e83572009-08-20 04:21:42 +00002694/// \brief Whether this is a promotable bitfield reference according
2695/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2696///
2697/// \returns the type this bit-field will promote to, or NULL if no
2698/// promotion occurs.
2699QualType ASTContext::isPromotableBitField(Expr *E) {
2700 FieldDecl *Field = E->getBitField();
2701 if (!Field)
2702 return QualType();
2703
2704 QualType FT = Field->getType();
2705
2706 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2707 uint64_t BitWidth = BitWidthAP.getZExtValue();
2708 uint64_t IntSize = getTypeSize(IntTy);
2709 // GCC extension compatibility: if the bit-field size is less than or equal
2710 // to the size of int, it gets promoted no matter what its type is.
2711 // For instance, unsigned long bf : 4 gets promoted to signed int.
2712 if (BitWidth < IntSize)
2713 return IntTy;
2714
2715 if (BitWidth == IntSize)
2716 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2717
2718 // Types bigger than int are not subject to promotions, and therefore act
2719 // like the base type.
2720 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2721 // is ridiculous.
2722 return QualType();
2723}
2724
Eli Friedmana95d7572009-08-19 07:44:53 +00002725/// getPromotedIntegerType - Returns the type that Promotable will
2726/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2727/// integer type.
2728QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2729 assert(!Promotable.isNull());
2730 assert(Promotable->isPromotableIntegerType());
2731 if (Promotable->isSignedIntegerType())
2732 return IntTy;
2733 uint64_t PromotableSize = getTypeSize(Promotable);
2734 uint64_t IntSize = getTypeSize(IntTy);
2735 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2736 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2737}
2738
Mike Stump1eb44332009-09-09 15:08:12 +00002739/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002740/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002741/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002742int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002743 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2744 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002745 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Chris Lattnerf52ab252008-04-06 22:59:24 +00002747 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2748 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Chris Lattner7cfeb082008-04-06 23:55:33 +00002750 unsigned LHSRank = getIntegerRank(LHSC);
2751 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Chris Lattner7cfeb082008-04-06 23:55:33 +00002753 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2754 if (LHSRank == RHSRank) return 0;
2755 return LHSRank > RHSRank ? 1 : -1;
2756 }
Mike Stump1eb44332009-09-09 15:08:12 +00002757
Chris Lattner7cfeb082008-04-06 23:55:33 +00002758 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2759 if (LHSUnsigned) {
2760 // If the unsigned [LHS] type is larger, return it.
2761 if (LHSRank >= RHSRank)
2762 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Chris Lattner7cfeb082008-04-06 23:55:33 +00002764 // If the signed type can represent all values of the unsigned type, it
2765 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002766 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002767 return -1;
2768 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002769
Chris Lattner7cfeb082008-04-06 23:55:33 +00002770 // If the unsigned [RHS] type is larger, return it.
2771 if (RHSRank >= LHSRank)
2772 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Chris Lattner7cfeb082008-04-06 23:55:33 +00002774 // If the signed type can represent all values of the unsigned type, it
2775 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002776 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002777 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002778}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002779
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002780static RecordDecl *
2781CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2782 SourceLocation L, IdentifierInfo *Id) {
2783 if (Ctx.getLangOptions().CPlusPlus)
2784 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2785 else
2786 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2787}
2788
Mike Stump1eb44332009-09-09 15:08:12 +00002789// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002790QualType ASTContext::getCFConstantStringType() {
2791 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002792 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002793 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2794 &Idents.get("NSConstantString"));
2795
Anders Carlssonf06273f2007-11-19 00:25:30 +00002796 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Anders Carlsson71993dd2007-08-17 05:31:46 +00002798 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002799 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002800 // int flags;
2801 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002802 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002803 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002804 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002805 FieldTypes[3] = LongTy;
2806
Anders Carlsson71993dd2007-08-17 05:31:46 +00002807 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002808 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002809 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002810 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002811 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002812 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002813 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002814 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002815 }
2816
2817 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002818 }
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Anders Carlsson71993dd2007-08-17 05:31:46 +00002820 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002821}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002822
Douglas Gregor319ac892009-04-23 22:29:11 +00002823void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002824 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002825 assert(Rec && "Invalid CFConstantStringType");
2826 CFConstantStringTypeDecl = Rec->getDecl();
2827}
2828
Mike Stump1eb44332009-09-09 15:08:12 +00002829QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002830 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002831 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002832 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2833 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002834
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002835 QualType FieldTypes[] = {
2836 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002837 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002838 getPointerType(UnsignedLongTy),
2839 getConstantArrayType(UnsignedLongTy,
2840 llvm::APInt(32, 5), ArrayType::Normal, 0)
2841 };
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Douglas Gregor44b43212008-12-11 16:49:14 +00002843 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002844 FieldDecl *Field = FieldDecl::Create(*this,
2845 ObjCFastEnumerationStateTypeDecl,
2846 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002847 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002848 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002849 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002850 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002851 }
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Douglas Gregor44b43212008-12-11 16:49:14 +00002853 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002854 }
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002856 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2857}
2858
Mike Stumpadaaad32009-10-20 02:12:22 +00002859QualType ASTContext::getBlockDescriptorType() {
2860 if (BlockDescriptorType)
2861 return getTagDeclType(BlockDescriptorType);
2862
2863 RecordDecl *T;
2864 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002865 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2866 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002867
2868 QualType FieldTypes[] = {
2869 UnsignedLongTy,
2870 UnsignedLongTy,
2871 };
2872
2873 const char *FieldNames[] = {
2874 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002875 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002876 };
2877
2878 for (size_t i = 0; i < 2; ++i) {
2879 FieldDecl *Field = FieldDecl::Create(*this,
2880 T,
2881 SourceLocation(),
2882 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002883 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002884 /*BitWidth=*/0,
2885 /*Mutable=*/false);
2886 T->addDecl(Field);
2887 }
2888
2889 T->completeDefinition(*this);
2890
2891 BlockDescriptorType = T;
2892
2893 return getTagDeclType(BlockDescriptorType);
2894}
2895
2896void ASTContext::setBlockDescriptorType(QualType T) {
2897 const RecordType *Rec = T->getAs<RecordType>();
2898 assert(Rec && "Invalid BlockDescriptorType");
2899 BlockDescriptorType = Rec->getDecl();
2900}
2901
Mike Stump083c25e2009-10-22 00:49:09 +00002902QualType ASTContext::getBlockDescriptorExtendedType() {
2903 if (BlockDescriptorExtendedType)
2904 return getTagDeclType(BlockDescriptorExtendedType);
2905
2906 RecordDecl *T;
2907 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002908 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2909 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002910
2911 QualType FieldTypes[] = {
2912 UnsignedLongTy,
2913 UnsignedLongTy,
2914 getPointerType(VoidPtrTy),
2915 getPointerType(VoidPtrTy)
2916 };
2917
2918 const char *FieldNames[] = {
2919 "reserved",
2920 "Size",
2921 "CopyFuncPtr",
2922 "DestroyFuncPtr"
2923 };
2924
2925 for (size_t i = 0; i < 4; ++i) {
2926 FieldDecl *Field = FieldDecl::Create(*this,
2927 T,
2928 SourceLocation(),
2929 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002930 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00002931 /*BitWidth=*/0,
2932 /*Mutable=*/false);
2933 T->addDecl(Field);
2934 }
2935
2936 T->completeDefinition(*this);
2937
2938 BlockDescriptorExtendedType = T;
2939
2940 return getTagDeclType(BlockDescriptorExtendedType);
2941}
2942
2943void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2944 const RecordType *Rec = T->getAs<RecordType>();
2945 assert(Rec && "Invalid BlockDescriptorType");
2946 BlockDescriptorExtendedType = Rec->getDecl();
2947}
2948
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002949bool ASTContext::BlockRequiresCopying(QualType Ty) {
2950 if (Ty->isBlockPointerType())
2951 return true;
2952 if (isObjCNSObjectType(Ty))
2953 return true;
2954 if (Ty->isObjCObjectPointerType())
2955 return true;
2956 return false;
2957}
2958
2959QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2960 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002961 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002962 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002963 // unsigned int __flags;
2964 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002965 // void *__copy_helper; // as needed
2966 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002967 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002968 // } *
2969
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002970 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2971
2972 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002973 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002974 llvm::SmallString<36> Name;
2975 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2976 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002977 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002978 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2979 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002980 T->startDefinition();
2981 QualType Int32Ty = IntTy;
2982 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2983 QualType FieldTypes[] = {
2984 getPointerType(VoidPtrTy),
2985 getPointerType(getTagDeclType(T)),
2986 Int32Ty,
2987 Int32Ty,
2988 getPointerType(VoidPtrTy),
2989 getPointerType(VoidPtrTy),
2990 Ty
2991 };
2992
2993 const char *FieldNames[] = {
2994 "__isa",
2995 "__forwarding",
2996 "__flags",
2997 "__size",
2998 "__copy_helper",
2999 "__destroy_helper",
3000 DeclName,
3001 };
3002
3003 for (size_t i = 0; i < 7; ++i) {
3004 if (!HasCopyAndDispose && i >=4 && i <= 5)
3005 continue;
3006 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3007 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003008 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003009 /*BitWidth=*/0, /*Mutable=*/false);
3010 T->addDecl(Field);
3011 }
3012
3013 T->completeDefinition(*this);
3014
3015 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003016}
3017
3018
3019QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003020 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003021 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003022 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003023 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003024 llvm::SmallString<36> Name;
3025 llvm::raw_svector_ostream(Name) << "__block_literal_"
3026 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003027 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003028 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3029 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003030 QualType FieldTypes[] = {
3031 getPointerType(VoidPtrTy),
3032 IntTy,
3033 IntTy,
3034 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003035 (BlockHasCopyDispose ?
3036 getPointerType(getBlockDescriptorExtendedType()) :
3037 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003038 };
3039
3040 const char *FieldNames[] = {
3041 "__isa",
3042 "__flags",
3043 "__reserved",
3044 "__FuncPtr",
3045 "__descriptor"
3046 };
3047
3048 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003049 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003050 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003051 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003052 /*BitWidth=*/0, /*Mutable=*/false);
3053 T->addDecl(Field);
3054 }
3055
3056 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3057 const Expr *E = BlockDeclRefDecls[i];
3058 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3059 clang::IdentifierInfo *Name = 0;
3060 if (BDRE) {
3061 const ValueDecl *D = BDRE->getDecl();
3062 Name = &Idents.get(D->getName());
3063 }
3064 QualType FieldType = E->getType();
3065
3066 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003067 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3068 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003069
3070 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003071 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003072 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003073 T->addDecl(Field);
3074 }
3075
3076 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003077
3078 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003079}
3080
Douglas Gregor319ac892009-04-23 22:29:11 +00003081void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003082 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003083 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3084 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3085}
3086
Anders Carlssone8c49532007-10-29 06:33:42 +00003087// This returns true if a type has been typedefed to BOOL:
3088// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003089static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003090 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003091 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3092 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003094 return false;
3095}
3096
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003097/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003098/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003099int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003100 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003102 // Make all integer and enum types at least as large as an int
3103 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003104 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003105 // Treat arrays as pointers, since that's how they're passed in.
3106 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003107 sz = getTypeSize(VoidPtrTy);
3108 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003109}
3110
David Chisnall5e530af2009-11-17 19:33:30 +00003111/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3112/// declaration.
3113void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3114 std::string& S) {
3115 const BlockDecl *Decl = Expr->getBlockDecl();
3116 QualType BlockTy =
3117 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3118 // Encode result type.
3119 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3120 // Compute size of all parameters.
3121 // Start with computing size of a pointer in number of bytes.
3122 // FIXME: There might(should) be a better way of doing this computation!
3123 SourceLocation Loc;
3124 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3125 int ParmOffset = PtrSize;
3126 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3127 E = Decl->param_end(); PI != E; ++PI) {
3128 QualType PType = (*PI)->getType();
3129 int sz = getObjCEncodingTypeSize(PType);
3130 assert (sz > 0 && "BlockExpr - Incomplete param type");
3131 ParmOffset += sz;
3132 }
3133 // Size of the argument frame
3134 S += llvm::utostr(ParmOffset);
3135 // Block pointer and offset.
3136 S += "@?0";
3137 ParmOffset = PtrSize;
3138
3139 // Argument types.
3140 ParmOffset = PtrSize;
3141 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3142 Decl->param_end(); PI != E; ++PI) {
3143 ParmVarDecl *PVDecl = *PI;
3144 QualType PType = PVDecl->getOriginalType();
3145 if (const ArrayType *AT =
3146 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3147 // Use array's original type only if it has known number of
3148 // elements.
3149 if (!isa<ConstantArrayType>(AT))
3150 PType = PVDecl->getType();
3151 } else if (PType->isFunctionType())
3152 PType = PVDecl->getType();
3153 getObjCEncodingForType(PType, S);
3154 S += llvm::utostr(ParmOffset);
3155 ParmOffset += getObjCEncodingTypeSize(PType);
3156 }
3157}
3158
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003159/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003160/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003161void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003162 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003163 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003164 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003166 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003167 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003168 // Compute size of all parameters.
3169 // Start with computing size of a pointer in number of bytes.
3170 // FIXME: There might(should) be a better way of doing this computation!
3171 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003172 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003173 // The first two arguments (self and _cmd) are pointers; account for
3174 // their size.
3175 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003176 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3177 E = Decl->param_end(); PI != E; ++PI) {
3178 QualType PType = (*PI)->getType();
3179 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003180 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003181 ParmOffset += sz;
3182 }
3183 S += llvm::utostr(ParmOffset);
3184 S += "@0:";
3185 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003187 // Argument types.
3188 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003189 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3190 E = Decl->param_end(); PI != E; ++PI) {
3191 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003192 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003193 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003194 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3195 // Use array's original type only if it has known number of
3196 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003197 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003198 PType = PVDecl->getType();
3199 } else if (PType->isFunctionType())
3200 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003201 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003202 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003203 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003204 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003205 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003206 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003207 }
3208}
3209
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003210/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003211/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003212/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3213/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003214/// Property attributes are stored as a comma-delimited C string. The simple
3215/// attributes readonly and bycopy are encoded as single characters. The
3216/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3217/// encoded as single characters, followed by an identifier. Property types
3218/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003219/// these attributes are defined by the following enumeration:
3220/// @code
3221/// enum PropertyAttributes {
3222/// kPropertyReadOnly = 'R', // property is read-only.
3223/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3224/// kPropertyByref = '&', // property is a reference to the value last assigned
3225/// kPropertyDynamic = 'D', // property is dynamic
3226/// kPropertyGetter = 'G', // followed by getter selector name
3227/// kPropertySetter = 'S', // followed by setter selector name
3228/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3229/// kPropertyType = 't' // followed by old-style type encoding.
3230/// kPropertyWeak = 'W' // 'weak' property
3231/// kPropertyStrong = 'P' // property GC'able
3232/// kPropertyNonAtomic = 'N' // property non-atomic
3233/// };
3234/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003235void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003236 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003237 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003238 // Collect information from the property implementation decl(s).
3239 bool Dynamic = false;
3240 ObjCPropertyImplDecl *SynthesizePID = 0;
3241
3242 // FIXME: Duplicated code due to poor abstraction.
3243 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003244 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003245 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3246 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003247 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003248 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003249 ObjCPropertyImplDecl *PID = *i;
3250 if (PID->getPropertyDecl() == PD) {
3251 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3252 Dynamic = true;
3253 } else {
3254 SynthesizePID = PID;
3255 }
3256 }
3257 }
3258 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003259 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003260 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003261 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003262 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003263 ObjCPropertyImplDecl *PID = *i;
3264 if (PID->getPropertyDecl() == PD) {
3265 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3266 Dynamic = true;
3267 } else {
3268 SynthesizePID = PID;
3269 }
3270 }
Mike Stump1eb44332009-09-09 15:08:12 +00003271 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003272 }
3273 }
3274
3275 // FIXME: This is not very efficient.
3276 S = "T";
3277
3278 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003279 // GCC has some special rules regarding encoding of properties which
3280 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003281 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003282 true /* outermost type */,
3283 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003284
3285 if (PD->isReadOnly()) {
3286 S += ",R";
3287 } else {
3288 switch (PD->getSetterKind()) {
3289 case ObjCPropertyDecl::Assign: break;
3290 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003291 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003292 }
3293 }
3294
3295 // It really isn't clear at all what this means, since properties
3296 // are "dynamic by default".
3297 if (Dynamic)
3298 S += ",D";
3299
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003300 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3301 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003303 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3304 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003305 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003306 }
3307
3308 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3309 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003310 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003311 }
3312
3313 if (SynthesizePID) {
3314 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3315 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003316 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003317 }
3318
3319 // FIXME: OBJCGC: weak & strong
3320}
3321
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003322/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003323/// Another legacy compatibility encoding: 32-bit longs are encoded as
3324/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003325/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3326///
3327void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003328 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003329 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003330 if (BT->getKind() == BuiltinType::ULong &&
3331 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003332 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003333 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003334 if (BT->getKind() == BuiltinType::Long &&
3335 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003336 PointeeTy = IntTy;
3337 }
3338 }
3339}
3340
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003341void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003342 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003343 // We follow the behavior of gcc, expanding structures which are
3344 // directly pointed to, and expanding embedded structures. Note that
3345 // these rules are sufficient to prevent recursive encoding of the
3346 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003347 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003348 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003349}
3350
Mike Stump1eb44332009-09-09 15:08:12 +00003351static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003352 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003353 const Expr *E = FD->getBitWidth();
3354 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3355 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003356 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003357 S += 'b';
3358 S += llvm::utostr(N);
3359}
3360
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003361// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003362void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3363 bool ExpandPointedToStructures,
3364 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003365 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003366 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003367 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003368 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003369 if (FD && FD->isBitField())
3370 return EncodeBitField(this, S, FD);
3371 char encoding;
3372 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003373 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003374 case BuiltinType::Void: encoding = 'v'; break;
3375 case BuiltinType::Bool: encoding = 'B'; break;
3376 case BuiltinType::Char_U:
3377 case BuiltinType::UChar: encoding = 'C'; break;
3378 case BuiltinType::UShort: encoding = 'S'; break;
3379 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003380 case BuiltinType::ULong:
3381 encoding =
3382 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003383 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003384 case BuiltinType::UInt128: encoding = 'T'; break;
3385 case BuiltinType::ULongLong: encoding = 'Q'; break;
3386 case BuiltinType::Char_S:
3387 case BuiltinType::SChar: encoding = 'c'; break;
3388 case BuiltinType::Short: encoding = 's'; break;
3389 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003390 case BuiltinType::Long:
3391 encoding =
3392 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003393 break;
3394 case BuiltinType::LongLong: encoding = 'q'; break;
3395 case BuiltinType::Int128: encoding = 't'; break;
3396 case BuiltinType::Float: encoding = 'f'; break;
3397 case BuiltinType::Double: encoding = 'd'; break;
3398 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003399 }
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003401 S += encoding;
3402 return;
3403 }
Mike Stump1eb44332009-09-09 15:08:12 +00003404
John McCall183700f2009-09-21 23:43:11 +00003405 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003406 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003407 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003408 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003409 return;
3410 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003411
Ted Kremenek6217b802009-07-29 21:53:49 +00003412 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003413 if (PT->isObjCSelType()) {
3414 S += ':';
3415 return;
3416 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003417 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003418
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003419 bool isReadOnly = false;
3420 // For historical/compatibility reasons, the read-only qualifier of the
3421 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3422 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003423 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003424 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003425 if (OutermostType && T.isConstQualified()) {
3426 isReadOnly = true;
3427 S += 'r';
3428 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003429 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003430 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003431 while (P->getAs<PointerType>())
3432 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003433 if (P.isConstQualified()) {
3434 isReadOnly = true;
3435 S += 'r';
3436 }
3437 }
3438 if (isReadOnly) {
3439 // Another legacy compatibility encoding. Some ObjC qualifier and type
3440 // combinations need to be rearranged.
3441 // Rewrite "in const" from "nr" to "rn"
3442 const char * s = S.c_str();
3443 int len = S.length();
3444 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3445 std::string replace = "rn";
3446 S.replace(S.end()-2, S.end(), replace);
3447 }
3448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003450 if (PointeeTy->isCharType()) {
3451 // char pointer types should be encoded as '*' unless it is a
3452 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003453 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003454 S += '*';
3455 return;
3456 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003457 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003458 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3459 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3460 S += '#';
3461 return;
3462 }
3463 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3464 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3465 S += '@';
3466 return;
3467 }
3468 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003469 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003470 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003471 getLegacyIntegralTypeEncoding(PointeeTy);
3472
Mike Stump1eb44332009-09-09 15:08:12 +00003473 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003474 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003475 return;
3476 }
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003478 if (const ArrayType *AT =
3479 // Ignore type qualifiers etc.
3480 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003481 if (isa<IncompleteArrayType>(AT)) {
3482 // Incomplete arrays are encoded as a pointer to the array element.
3483 S += '^';
3484
Mike Stump1eb44332009-09-09 15:08:12 +00003485 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003486 false, ExpandStructures, FD);
3487 } else {
3488 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Anders Carlsson559a8332009-02-22 01:38:57 +00003490 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3491 S += llvm::utostr(CAT->getSize().getZExtValue());
3492 else {
3493 //Variable length arrays are encoded as a regular array with 0 elements.
3494 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3495 S += '0';
3496 }
Mike Stump1eb44332009-09-09 15:08:12 +00003497
3498 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003499 false, ExpandStructures, FD);
3500 S += ']';
3501 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003502 return;
3503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
John McCall183700f2009-09-21 23:43:11 +00003505 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003506 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003507 return;
3508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Ted Kremenek6217b802009-07-29 21:53:49 +00003510 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003511 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003512 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003513 // Anonymous structures print as '?'
3514 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3515 S += II->getName();
3516 } else {
3517 S += '?';
3518 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003519 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003520 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003521 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3522 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003523 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003524 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003525 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003526 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003527 S += '"';
3528 }
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003530 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003531 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003532 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003533 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003534 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003535 QualType qt = Field->getType();
3536 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003537 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003538 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003539 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003540 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003541 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003542 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003543 return;
3544 }
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003546 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003547 if (FD && FD->isBitField())
3548 EncodeBitField(this, S, FD);
3549 else
3550 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003551 return;
3552 }
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003554 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003555 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003556 return;
3557 }
Mike Stump1eb44332009-09-09 15:08:12 +00003558
John McCall0953e762009-09-24 19:53:00 +00003559 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003560 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003561 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003562 S += '{';
3563 const IdentifierInfo *II = OI->getIdentifier();
3564 S += II->getName();
3565 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003566 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003567 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003568 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003569 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003570 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003571 RecFields[i]);
3572 else
Mike Stump1eb44332009-09-09 15:08:12 +00003573 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003574 FD);
3575 }
3576 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003577 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003578 }
Mike Stump1eb44332009-09-09 15:08:12 +00003579
John McCall183700f2009-09-21 23:43:11 +00003580 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003581 if (OPT->isObjCIdType()) {
3582 S += '@';
3583 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003584 }
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Steve Naroff27d20a22009-10-28 22:03:49 +00003586 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3587 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3588 // Since this is a binary compatibility issue, need to consult with runtime
3589 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003590 S += '#';
3591 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003592 }
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003594 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003595 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003596 ExpandPointedToStructures,
3597 ExpandStructures, FD);
3598 if (FD || EncodingProperty) {
3599 // Note that we do extended encoding of protocol qualifer list
3600 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003601 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003602 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3603 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003604 S += '<';
3605 S += (*I)->getNameAsString();
3606 S += '>';
3607 }
3608 S += '"';
3609 }
3610 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003611 }
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003613 QualType PointeeTy = OPT->getPointeeType();
3614 if (!EncodingProperty &&
3615 isa<TypedefType>(PointeeTy.getTypePtr())) {
3616 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003617 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003618 // {...};
3619 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003620 getObjCEncodingForTypeImpl(PointeeTy, S,
3621 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003622 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003623 return;
3624 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003625
3626 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003627 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003628 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003629 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003630 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3631 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003632 S += '<';
3633 S += (*I)->getNameAsString();
3634 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003635 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003636 S += '"';
3637 }
3638 return;
3639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003641 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003642}
3643
Mike Stump1eb44332009-09-09 15:08:12 +00003644void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003645 std::string& S) const {
3646 if (QT & Decl::OBJC_TQ_In)
3647 S += 'n';
3648 if (QT & Decl::OBJC_TQ_Inout)
3649 S += 'N';
3650 if (QT & Decl::OBJC_TQ_Out)
3651 S += 'o';
3652 if (QT & Decl::OBJC_TQ_Bycopy)
3653 S += 'O';
3654 if (QT & Decl::OBJC_TQ_Byref)
3655 S += 'R';
3656 if (QT & Decl::OBJC_TQ_Oneway)
3657 S += 'V';
3658}
3659
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003660void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003661 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003663 BuiltinVaListType = T;
3664}
3665
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003666void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003667 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003668}
3669
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003670void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003671 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003672}
3673
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003674void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003675 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003676}
3677
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003678void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003679 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003680}
3681
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003682void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003683 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003684 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003686 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003687}
3688
John McCall0bd6feb2009-12-02 08:04:21 +00003689/// \brief Retrieve the template name that corresponds to a non-empty
3690/// lookup.
3691TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3692 NamedDecl * const *End) {
3693 unsigned size = End - Begin;
3694 assert(size > 1 && "set is not overloaded!");
3695
3696 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3697 size * sizeof(FunctionTemplateDecl*));
3698 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3699
3700 NamedDecl **Storage = OT->getStorage();
3701 for (NamedDecl * const *I = Begin; I != End; ++I) {
3702 NamedDecl *D = *I;
3703 assert(isa<FunctionTemplateDecl>(D) ||
3704 (isa<UsingShadowDecl>(D) &&
3705 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3706 *Storage++ = D;
3707 }
3708
3709 return TemplateName(OT);
3710}
3711
Douglas Gregor7532dc62009-03-30 22:58:21 +00003712/// \brief Retrieve the template name that represents a qualified
3713/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003714TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003715 bool TemplateKeyword,
3716 TemplateDecl *Template) {
3717 llvm::FoldingSetNodeID ID;
3718 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3719
3720 void *InsertPos = 0;
3721 QualifiedTemplateName *QTN =
3722 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3723 if (!QTN) {
3724 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3725 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3726 }
3727
3728 return TemplateName(QTN);
3729}
3730
3731/// \brief Retrieve the template name that represents a dependent
3732/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003733TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003734 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003735 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003736 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003737
3738 llvm::FoldingSetNodeID ID;
3739 DependentTemplateName::Profile(ID, NNS, Name);
3740
3741 void *InsertPos = 0;
3742 DependentTemplateName *QTN =
3743 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3744
3745 if (QTN)
3746 return TemplateName(QTN);
3747
3748 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3749 if (CanonNNS == NNS) {
3750 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3751 } else {
3752 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3753 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3754 }
3755
3756 DependentTemplateNames.InsertNode(QTN, InsertPos);
3757 return TemplateName(QTN);
3758}
3759
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003760/// \brief Retrieve the template name that represents a dependent
3761/// template name such as \c MetaFun::template operator+.
3762TemplateName
3763ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3764 OverloadedOperatorKind Operator) {
3765 assert((!NNS || NNS->isDependent()) &&
3766 "Nested name specifier must be dependent");
3767
3768 llvm::FoldingSetNodeID ID;
3769 DependentTemplateName::Profile(ID, NNS, Operator);
3770
3771 void *InsertPos = 0;
3772 DependentTemplateName *QTN =
3773 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3774
3775 if (QTN)
3776 return TemplateName(QTN);
3777
3778 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3779 if (CanonNNS == NNS) {
3780 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3781 } else {
3782 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3783 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3784 }
3785
3786 DependentTemplateNames.InsertNode(QTN, InsertPos);
3787 return TemplateName(QTN);
3788}
3789
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003790/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003791/// TargetInfo, produce the corresponding type. The unsigned @p Type
3792/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003793CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003794 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003795 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003796 case TargetInfo::SignedShort: return ShortTy;
3797 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3798 case TargetInfo::SignedInt: return IntTy;
3799 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3800 case TargetInfo::SignedLong: return LongTy;
3801 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3802 case TargetInfo::SignedLongLong: return LongLongTy;
3803 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3804 }
3805
3806 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003807 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003808}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003809
3810//===----------------------------------------------------------------------===//
3811// Type Predicates.
3812//===----------------------------------------------------------------------===//
3813
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003814/// isObjCNSObjectType - Return true if this is an NSObject object using
3815/// NSObject attribute on a c-style pointer type.
3816/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003817/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003818///
3819bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3820 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3821 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003822 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003823 return true;
3824 }
Mike Stump1eb44332009-09-09 15:08:12 +00003825 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003826}
3827
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003828/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3829/// garbage collection attribute.
3830///
John McCall0953e762009-09-24 19:53:00 +00003831Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3832 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003833 if (getLangOptions().ObjC1 &&
3834 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003835 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003836 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003837 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003838 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003839 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003840 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003841 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003842 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003843 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003844 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003845 // Non-pointers have none gc'able attribute regardless of the attribute
3846 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003847 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003848 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003849 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003850 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003851}
3852
Chris Lattner6ac46a42008-04-07 06:51:04 +00003853//===----------------------------------------------------------------------===//
3854// Type Compatibility Testing
3855//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003856
Mike Stump1eb44332009-09-09 15:08:12 +00003857/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003858/// compatible.
3859static bool areCompatVectorTypes(const VectorType *LHS,
3860 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003861 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003862 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003863 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003864}
3865
Steve Naroff4084c302009-07-23 01:01:38 +00003866//===----------------------------------------------------------------------===//
3867// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3868//===----------------------------------------------------------------------===//
3869
3870/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3871/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003872bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3873 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003874 if (lProto == rProto)
3875 return true;
3876 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3877 E = rProto->protocol_end(); PI != E; ++PI)
3878 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3879 return true;
3880 return false;
3881}
3882
Steve Naroff4084c302009-07-23 01:01:38 +00003883/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3884/// return true if lhs's protocols conform to rhs's protocol; false
3885/// otherwise.
3886bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3887 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3888 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3889 return false;
3890}
3891
3892/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3893/// ObjCQualifiedIDType.
3894bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3895 bool compare) {
3896 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003897 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003898 lhs->isObjCIdType() || lhs->isObjCClassType())
3899 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003900 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003901 rhs->isObjCIdType() || rhs->isObjCClassType())
3902 return true;
3903
3904 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003905 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Steve Naroff4084c302009-07-23 01:01:38 +00003907 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Steve Naroff4084c302009-07-23 01:01:38 +00003909 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003910 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003911 // make sure we check the class hierarchy.
3912 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3913 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3914 E = lhsQID->qual_end(); I != E; ++I) {
3915 // when comparing an id<P> on lhs with a static type on rhs,
3916 // see if static class implements all of id's protocols, directly or
3917 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003918 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003919 return false;
3920 }
3921 }
3922 // If there are no qualifiers and no interface, we have an 'id'.
3923 return true;
3924 }
Mike Stump1eb44332009-09-09 15:08:12 +00003925 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003926 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3927 E = lhsQID->qual_end(); I != E; ++I) {
3928 ObjCProtocolDecl *lhsProto = *I;
3929 bool match = false;
3930
3931 // when comparing an id<P> on lhs with a static type on rhs,
3932 // see if static class implements all of id's protocols, directly or
3933 // through its super class and categories.
3934 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3935 E = rhsOPT->qual_end(); J != E; ++J) {
3936 ObjCProtocolDecl *rhsProto = *J;
3937 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3938 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3939 match = true;
3940 break;
3941 }
3942 }
Mike Stump1eb44332009-09-09 15:08:12 +00003943 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003944 // make sure we check the class hierarchy.
3945 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3946 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3947 E = lhsQID->qual_end(); I != E; ++I) {
3948 // when comparing an id<P> on lhs with a static type on rhs,
3949 // see if static class implements all of id's protocols, directly or
3950 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003951 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003952 match = true;
3953 break;
3954 }
3955 }
3956 }
3957 if (!match)
3958 return false;
3959 }
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Steve Naroff4084c302009-07-23 01:01:38 +00003961 return true;
3962 }
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Steve Naroff4084c302009-07-23 01:01:38 +00003964 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3965 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3966
Mike Stump1eb44332009-09-09 15:08:12 +00003967 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003968 lhs->getAsObjCInterfacePointerType()) {
3969 if (lhsOPT->qual_empty()) {
3970 bool match = false;
3971 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3972 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3973 E = rhsQID->qual_end(); I != E; ++I) {
3974 // when comparing an id<P> on lhs with a static type on rhs,
3975 // see if static class implements all of id's protocols, directly or
3976 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003977 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003978 match = true;
3979 break;
3980 }
3981 }
3982 if (!match)
3983 return false;
3984 }
3985 return true;
3986 }
Mike Stump1eb44332009-09-09 15:08:12 +00003987 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003988 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3989 E = lhsOPT->qual_end(); I != E; ++I) {
3990 ObjCProtocolDecl *lhsProto = *I;
3991 bool match = false;
3992
3993 // when comparing an id<P> on lhs with a static type on rhs,
3994 // see if static class implements all of id's protocols, directly or
3995 // through its super class and categories.
3996 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3997 E = rhsQID->qual_end(); J != E; ++J) {
3998 ObjCProtocolDecl *rhsProto = *J;
3999 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4000 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4001 match = true;
4002 break;
4003 }
4004 }
4005 if (!match)
4006 return false;
4007 }
4008 return true;
4009 }
4010 return false;
4011}
4012
Eli Friedman3d815e72008-08-22 00:56:42 +00004013/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004014/// compatible for assignment from RHS to LHS. This handles validation of any
4015/// protocol qualifiers on the LHS or RHS.
4016///
Steve Naroff14108da2009-07-10 23:34:53 +00004017bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4018 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004019 // If either type represents the built-in 'id' or 'Class' types, return true.
4020 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004021 return true;
4022
Steve Naroff4084c302009-07-23 01:01:38 +00004023 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004024 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4025 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004026 false);
4027
Steve Naroff14108da2009-07-10 23:34:53 +00004028 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4029 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004030 if (LHS && RHS) // We have 2 user-defined types.
4031 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Steve Naroff4084c302009-07-23 01:01:38 +00004033 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004034}
4035
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004036/// getIntersectionOfProtocols - This routine finds the intersection of set
4037/// of protocols inherited from two distinct objective-c pointer objects.
4038/// It is used to build composite qualifier list of the composite type of
4039/// the conditional expression involving two objective-c pointer objects.
4040static
4041void getIntersectionOfProtocols(ASTContext &Context,
4042 const ObjCObjectPointerType *LHSOPT,
4043 const ObjCObjectPointerType *RHSOPT,
4044 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4045
4046 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4047 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4048
4049 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4050 unsigned LHSNumProtocols = LHS->getNumProtocols();
4051 if (LHSNumProtocols > 0)
4052 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4053 else {
4054 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4055 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4056 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4057 LHSInheritedProtocols.end());
4058 }
4059
4060 unsigned RHSNumProtocols = RHS->getNumProtocols();
4061 if (RHSNumProtocols > 0) {
4062 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4063 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4064 if (InheritedProtocolSet.count(RHSProtocols[i]))
4065 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4066 }
4067 else {
4068 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4069 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4070 // FIXME. This may cause duplication of protocols in the list, but should
4071 // be harmless.
4072 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4073 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4074 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4075 }
4076}
4077
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004078/// areCommonBaseCompatible - Returns common base class of the two classes if
4079/// one found. Note that this is O'2 algorithm. But it will be called as the
4080/// last type comparison in a ?-exp of ObjC pointer types before a
4081/// warning is issued. So, its invokation is extremely rare.
4082QualType ASTContext::areCommonBaseCompatible(
4083 const ObjCObjectPointerType *LHSOPT,
4084 const ObjCObjectPointerType *RHSOPT) {
4085 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4086 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4087 if (!LHS || !RHS)
4088 return QualType();
4089
4090 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4091 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4092 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004093 if (canAssignObjCInterfaces(LHS, RHS)) {
4094 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4095 getIntersectionOfProtocols(*this,
4096 LHSOPT, RHSOPT, IntersectionOfProtocols);
4097 if (IntersectionOfProtocols.empty())
4098 LHSTy = getObjCObjectPointerType(LHSTy);
4099 else
4100 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4101 IntersectionOfProtocols.size());
4102 return LHSTy;
4103 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004104 }
4105
4106 return QualType();
4107}
4108
Eli Friedman3d815e72008-08-22 00:56:42 +00004109bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4110 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004111 // Verify that the base decls are compatible: the RHS must be a subclass of
4112 // the LHS.
4113 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4114 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Chris Lattner6ac46a42008-04-07 06:51:04 +00004116 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4117 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004118 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004119 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Chris Lattner6ac46a42008-04-07 06:51:04 +00004121 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4122 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004123 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004124 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004126 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4127 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004128 LHSPI != LHSPE; LHSPI++) {
4129 bool RHSImplementsProtocol = false;
4130
4131 // If the RHS doesn't implement the protocol on the left, the types
4132 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004133 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004134 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004135 RHSPI != RHSPE; RHSPI++) {
4136 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004137 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004138 break;
4139 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004140 }
4141 // FIXME: For better diagnostics, consider passing back the protocol name.
4142 if (!RHSImplementsProtocol)
4143 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004144 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004145 // The RHS implements all protocols listed on the LHS.
4146 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004147}
4148
Steve Naroff389bf462009-02-12 17:52:19 +00004149bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4150 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004151 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4152 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004153
Steve Naroff14108da2009-07-10 23:34:53 +00004154 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004155 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004156
4157 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4158 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004159}
4160
Mike Stump1eb44332009-09-09 15:08:12 +00004161/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004162/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004163/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004164/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004165bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4166 return !mergeTypes(LHS, RHS).isNull();
4167}
4168
4169QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004170 const FunctionType *lbase = lhs->getAs<FunctionType>();
4171 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004172 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4173 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004174 bool allLTypes = true;
4175 bool allRTypes = true;
4176
4177 // Check return type
4178 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4179 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004180 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4181 allLTypes = false;
4182 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4183 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004184 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004185 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4186 if (NoReturn != lbase->getNoReturnAttr())
4187 allLTypes = false;
4188 if (NoReturn != rbase->getNoReturnAttr())
4189 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004190
Eli Friedman3d815e72008-08-22 00:56:42 +00004191 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004192 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4193 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004194 unsigned lproto_nargs = lproto->getNumArgs();
4195 unsigned rproto_nargs = rproto->getNumArgs();
4196
4197 // Compatible functions must have the same number of arguments
4198 if (lproto_nargs != rproto_nargs)
4199 return QualType();
4200
4201 // Variadic and non-variadic functions aren't compatible
4202 if (lproto->isVariadic() != rproto->isVariadic())
4203 return QualType();
4204
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004205 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4206 return QualType();
4207
Eli Friedman3d815e72008-08-22 00:56:42 +00004208 // Check argument compatibility
4209 llvm::SmallVector<QualType, 10> types;
4210 for (unsigned i = 0; i < lproto_nargs; i++) {
4211 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4212 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4213 QualType argtype = mergeTypes(largtype, rargtype);
4214 if (argtype.isNull()) return QualType();
4215 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004216 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4217 allLTypes = false;
4218 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4219 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004220 }
4221 if (allLTypes) return lhs;
4222 if (allRTypes) return rhs;
4223 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004224 lproto->isVariadic(), lproto->getTypeQuals(),
4225 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004226 }
4227
4228 if (lproto) allRTypes = false;
4229 if (rproto) allLTypes = false;
4230
Douglas Gregor72564e72009-02-26 23:50:07 +00004231 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004232 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004233 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004234 if (proto->isVariadic()) return QualType();
4235 // Check that the types are compatible with the types that
4236 // would result from default argument promotions (C99 6.7.5.3p15).
4237 // The only types actually affected are promotable integer
4238 // types and floats, which would be passed as a different
4239 // type depending on whether the prototype is visible.
4240 unsigned proto_nargs = proto->getNumArgs();
4241 for (unsigned i = 0; i < proto_nargs; ++i) {
4242 QualType argTy = proto->getArgType(i);
4243 if (argTy->isPromotableIntegerType() ||
4244 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4245 return QualType();
4246 }
4247
4248 if (allLTypes) return lhs;
4249 if (allRTypes) return rhs;
4250 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004251 proto->getNumArgs(), proto->isVariadic(),
4252 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004253 }
4254
4255 if (allLTypes) return lhs;
4256 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004257 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004258}
4259
4260QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004261 // C++ [expr]: If an expression initially has the type "reference to T", the
4262 // type is adjusted to "T" prior to any further analysis, the expression
4263 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004264 // expression is an lvalue unless the reference is an rvalue reference and
4265 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004266 // FIXME: C++ shouldn't be going through here! The rules are different
4267 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004268 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4269 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004270 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004271 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004272 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004273 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004274
Eli Friedman3d815e72008-08-22 00:56:42 +00004275 QualType LHSCan = getCanonicalType(LHS),
4276 RHSCan = getCanonicalType(RHS);
4277
4278 // If two types are identical, they are compatible.
4279 if (LHSCan == RHSCan)
4280 return LHS;
4281
John McCall0953e762009-09-24 19:53:00 +00004282 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004283 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4284 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004285 if (LQuals != RQuals) {
4286 // If any of these qualifiers are different, we have a type
4287 // mismatch.
4288 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4289 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4290 return QualType();
4291
4292 // Exactly one GC qualifier difference is allowed: __strong is
4293 // okay if the other type has no GC qualifier but is an Objective
4294 // C object pointer (i.e. implicitly strong by default). We fix
4295 // this by pretending that the unqualified type was actually
4296 // qualified __strong.
4297 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4298 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4299 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4300
4301 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4302 return QualType();
4303
4304 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4305 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4306 }
4307 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4308 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4309 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004310 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004311 }
4312
4313 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004314
Eli Friedman852d63b2009-06-01 01:22:52 +00004315 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4316 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004317
Chris Lattner1adb8832008-01-14 05:45:46 +00004318 // We want to consider the two function types to be the same for these
4319 // comparisons, just force one to the other.
4320 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4321 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004322
4323 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004324 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4325 LHSClass = Type::ConstantArray;
4326 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4327 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004328
Nate Begeman213541a2008-04-18 23:10:10 +00004329 // Canonicalize ExtVector -> Vector.
4330 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4331 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004332
Chris Lattnera36a61f2008-04-07 05:43:21 +00004333 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004334 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004335 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004336 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004337 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004338 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4339 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004340 }
John McCall183700f2009-09-21 23:43:11 +00004341 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004342 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4343 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004344 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004345
Eli Friedman3d815e72008-08-22 00:56:42 +00004346 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004347 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004348
Steve Naroff4a746782008-01-09 22:43:08 +00004349 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004350 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004351#define TYPE(Class, Base)
4352#define ABSTRACT_TYPE(Class, Base)
4353#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4354#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4355#include "clang/AST/TypeNodes.def"
4356 assert(false && "Non-canonical and dependent types shouldn't get here");
4357 return QualType();
4358
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004359 case Type::LValueReference:
4360 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004361 case Type::MemberPointer:
4362 assert(false && "C++ should never be in mergeTypes");
4363 return QualType();
4364
4365 case Type::IncompleteArray:
4366 case Type::VariableArray:
4367 case Type::FunctionProto:
4368 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004369 assert(false && "Types are eliminated above");
4370 return QualType();
4371
Chris Lattner1adb8832008-01-14 05:45:46 +00004372 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004373 {
4374 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004375 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4376 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004377 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4378 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004379 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004380 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004381 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004382 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004383 return getPointerType(ResultType);
4384 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004385 case Type::BlockPointer:
4386 {
4387 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004388 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4389 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004390 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4391 if (ResultType.isNull()) return QualType();
4392 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4393 return LHS;
4394 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4395 return RHS;
4396 return getBlockPointerType(ResultType);
4397 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004398 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004399 {
4400 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4401 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4402 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4403 return QualType();
4404
4405 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4406 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4407 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4408 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004409 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4410 return LHS;
4411 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4412 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004413 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4414 ArrayType::ArraySizeModifier(), 0);
4415 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4416 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004417 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4418 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004419 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4420 return LHS;
4421 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4422 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004423 if (LVAT) {
4424 // FIXME: This isn't correct! But tricky to implement because
4425 // the array's size has to be the size of LHS, but the type
4426 // has to be different.
4427 return LHS;
4428 }
4429 if (RVAT) {
4430 // FIXME: This isn't correct! But tricky to implement because
4431 // the array's size has to be the size of RHS, but the type
4432 // has to be different.
4433 return RHS;
4434 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004435 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4436 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004437 return getIncompleteArrayType(ResultType,
4438 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004439 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004440 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004441 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004442 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004443 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004444 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004445 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004446 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004447 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004448 case Type::Complex:
4449 // Distinct complex types are incompatible.
4450 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004451 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004452 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004453 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004454 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004455 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004456 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004457 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004458 // FIXME: This should be type compatibility, e.g. whether
4459 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004460 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4461 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004462 if (LHSIface && RHSIface &&
4463 canAssignObjCInterfaces(LHSIface, RHSIface))
4464 return LHS;
4465
Eli Friedman3d815e72008-08-22 00:56:42 +00004466 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004467 }
Steve Naroff14108da2009-07-10 23:34:53 +00004468 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004469 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4470 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004471 return LHS;
4472
Steve Naroffbc76dd02008-12-10 22:14:21 +00004473 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004474 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004475 case Type::FixedWidthInt:
4476 // Distinct fixed-width integers are not compatible.
4477 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004478 case Type::TemplateSpecialization:
4479 assert(false && "Dependent types have no size");
4480 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004481 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004482
4483 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004484}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004485
Chris Lattner5426bf62008-04-07 07:01:58 +00004486//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004487// Integer Predicates
4488//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004489
Eli Friedmanad74a752008-06-28 06:23:08 +00004490unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004491 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004492 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004493 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004494 return FWIT->getWidth();
4495 }
4496 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004497 return (unsigned)getTypeSize(T);
4498}
4499
4500QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4501 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004502
4503 // Turn <4 x signed int> -> <4 x unsigned int>
4504 if (const VectorType *VTy = T->getAs<VectorType>())
4505 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4506 VTy->getNumElements());
4507
4508 // For enums, we return the unsigned version of the base type.
4509 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004510 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004511
4512 const BuiltinType *BTy = T->getAs<BuiltinType>();
4513 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004514 switch (BTy->getKind()) {
4515 case BuiltinType::Char_S:
4516 case BuiltinType::SChar:
4517 return UnsignedCharTy;
4518 case BuiltinType::Short:
4519 return UnsignedShortTy;
4520 case BuiltinType::Int:
4521 return UnsignedIntTy;
4522 case BuiltinType::Long:
4523 return UnsignedLongTy;
4524 case BuiltinType::LongLong:
4525 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004526 case BuiltinType::Int128:
4527 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004528 default:
4529 assert(0 && "Unexpected signed integer type");
4530 return QualType();
4531 }
4532}
4533
Douglas Gregor2cf26342009-04-09 22:27:44 +00004534ExternalASTSource::~ExternalASTSource() { }
4535
4536void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004537
4538
4539//===----------------------------------------------------------------------===//
4540// Builtin Type Computation
4541//===----------------------------------------------------------------------===//
4542
4543/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4544/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004545static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004546 ASTContext::GetBuiltinTypeError &Error,
4547 bool AllowTypeModifiers = true) {
4548 // Modifiers.
4549 int HowLong = 0;
4550 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Chris Lattner86df27b2009-06-14 00:45:47 +00004552 // Read the modifiers first.
4553 bool Done = false;
4554 while (!Done) {
4555 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004556 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004557 case 'S':
4558 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4559 assert(!Signed && "Can't use 'S' modifier multiple times!");
4560 Signed = true;
4561 break;
4562 case 'U':
4563 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4564 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4565 Unsigned = true;
4566 break;
4567 case 'L':
4568 assert(HowLong <= 2 && "Can't have LLLL modifier");
4569 ++HowLong;
4570 break;
4571 }
4572 }
4573
4574 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Chris Lattner86df27b2009-06-14 00:45:47 +00004576 // Read the base type.
4577 switch (*Str++) {
4578 default: assert(0 && "Unknown builtin type letter!");
4579 case 'v':
4580 assert(HowLong == 0 && !Signed && !Unsigned &&
4581 "Bad modifiers used with 'v'!");
4582 Type = Context.VoidTy;
4583 break;
4584 case 'f':
4585 assert(HowLong == 0 && !Signed && !Unsigned &&
4586 "Bad modifiers used with 'f'!");
4587 Type = Context.FloatTy;
4588 break;
4589 case 'd':
4590 assert(HowLong < 2 && !Signed && !Unsigned &&
4591 "Bad modifiers used with 'd'!");
4592 if (HowLong)
4593 Type = Context.LongDoubleTy;
4594 else
4595 Type = Context.DoubleTy;
4596 break;
4597 case 's':
4598 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4599 if (Unsigned)
4600 Type = Context.UnsignedShortTy;
4601 else
4602 Type = Context.ShortTy;
4603 break;
4604 case 'i':
4605 if (HowLong == 3)
4606 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4607 else if (HowLong == 2)
4608 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4609 else if (HowLong == 1)
4610 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4611 else
4612 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4613 break;
4614 case 'c':
4615 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4616 if (Signed)
4617 Type = Context.SignedCharTy;
4618 else if (Unsigned)
4619 Type = Context.UnsignedCharTy;
4620 else
4621 Type = Context.CharTy;
4622 break;
4623 case 'b': // boolean
4624 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4625 Type = Context.BoolTy;
4626 break;
4627 case 'z': // size_t.
4628 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4629 Type = Context.getSizeType();
4630 break;
4631 case 'F':
4632 Type = Context.getCFConstantStringType();
4633 break;
4634 case 'a':
4635 Type = Context.getBuiltinVaListType();
4636 assert(!Type.isNull() && "builtin va list type not initialized!");
4637 break;
4638 case 'A':
4639 // This is a "reference" to a va_list; however, what exactly
4640 // this means depends on how va_list is defined. There are two
4641 // different kinds of va_list: ones passed by value, and ones
4642 // passed by reference. An example of a by-value va_list is
4643 // x86, where va_list is a char*. An example of by-ref va_list
4644 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4645 // we want this argument to be a char*&; for x86-64, we want
4646 // it to be a __va_list_tag*.
4647 Type = Context.getBuiltinVaListType();
4648 assert(!Type.isNull() && "builtin va list type not initialized!");
4649 if (Type->isArrayType()) {
4650 Type = Context.getArrayDecayedType(Type);
4651 } else {
4652 Type = Context.getLValueReferenceType(Type);
4653 }
4654 break;
4655 case 'V': {
4656 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004657 unsigned NumElements = strtoul(Str, &End, 10);
4658 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004659
Chris Lattner86df27b2009-06-14 00:45:47 +00004660 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004661
Chris Lattner86df27b2009-06-14 00:45:47 +00004662 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4663 Type = Context.getVectorType(ElementType, NumElements);
4664 break;
4665 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004666 case 'X': {
4667 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4668 Type = Context.getComplexType(ElementType);
4669 break;
4670 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004671 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004672 Type = Context.getFILEType();
4673 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004674 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004675 return QualType();
4676 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004677 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004678 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004679 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004680 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004681 else
4682 Type = Context.getjmp_bufType();
4683
Mike Stumpfd612db2009-07-28 23:47:15 +00004684 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004685 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004686 return QualType();
4687 }
4688 break;
Mike Stump782fa302009-07-28 02:25:19 +00004689 }
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Chris Lattner86df27b2009-06-14 00:45:47 +00004691 if (!AllowTypeModifiers)
4692 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Chris Lattner86df27b2009-06-14 00:45:47 +00004694 Done = false;
4695 while (!Done) {
4696 switch (*Str++) {
4697 default: Done = true; --Str; break;
4698 case '*':
4699 Type = Context.getPointerType(Type);
4700 break;
4701 case '&':
4702 Type = Context.getLValueReferenceType(Type);
4703 break;
4704 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4705 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004706 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004707 break;
4708 }
4709 }
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Chris Lattner86df27b2009-06-14 00:45:47 +00004711 return Type;
4712}
4713
4714/// GetBuiltinType - Return the type for the specified builtin.
4715QualType ASTContext::GetBuiltinType(unsigned id,
4716 GetBuiltinTypeError &Error) {
4717 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Chris Lattner86df27b2009-06-14 00:45:47 +00004719 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Chris Lattner86df27b2009-06-14 00:45:47 +00004721 Error = GE_None;
4722 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4723 if (Error != GE_None)
4724 return QualType();
4725 while (TypeStr[0] && TypeStr[0] != '.') {
4726 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4727 if (Error != GE_None)
4728 return QualType();
4729
4730 // Do array -> pointer decay. The builtin should use the decayed type.
4731 if (Ty->isArrayType())
4732 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Chris Lattner86df27b2009-06-14 00:45:47 +00004734 ArgTypes.push_back(Ty);
4735 }
4736
4737 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4738 "'.' should only occur at end of builtin type list!");
4739
4740 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4741 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4742 return getFunctionNoProtoType(ResType);
4743 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4744 TypeStr[0] == '.', 0);
4745}
Eli Friedmana95d7572009-08-19 07:44:53 +00004746
4747QualType
4748ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4749 // Perform the usual unary conversions. We do this early so that
4750 // integral promotions to "int" can allow us to exit early, in the
4751 // lhs == rhs check. Also, for conversion purposes, we ignore any
4752 // qualifiers. For example, "const float" and "float" are
4753 // equivalent.
4754 if (lhs->isPromotableIntegerType())
4755 lhs = getPromotedIntegerType(lhs);
4756 else
4757 lhs = lhs.getUnqualifiedType();
4758 if (rhs->isPromotableIntegerType())
4759 rhs = getPromotedIntegerType(rhs);
4760 else
4761 rhs = rhs.getUnqualifiedType();
4762
4763 // If both types are identical, no conversion is needed.
4764 if (lhs == rhs)
4765 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004766
Eli Friedmana95d7572009-08-19 07:44:53 +00004767 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4768 // The caller can deal with this (e.g. pointer + int).
4769 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4770 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004771
4772 // At this point, we have two different arithmetic types.
4773
Eli Friedmana95d7572009-08-19 07:44:53 +00004774 // Handle complex types first (C99 6.3.1.8p1).
4775 if (lhs->isComplexType() || rhs->isComplexType()) {
4776 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004777 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004778 // convert the rhs to the lhs complex type.
4779 return lhs;
4780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004782 // convert the lhs to the rhs complex type.
4783 return rhs;
4784 }
4785 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004786 // When both operands are complex, the shorter operand is converted to the
4787 // type of the longer, and that is the type of the result. This corresponds
4788 // to what is done when combining two real floating-point operands.
4789 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004790 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004791 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004792 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004793 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004794 // "double _Complex" is promoted to "long double _Complex".
4795 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004796
4797 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004798 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004799 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004800 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004801 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004802 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4803 // domains match. This is a requirement for our implementation, C99
4804 // does not require this promotion.
4805 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4806 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4807 return rhs;
4808 } else { // handle "_Complex double, double".
4809 return lhs;
4810 }
4811 }
4812 return lhs; // The domain/size match exactly.
4813 }
4814 // Now handle "real" floating types (i.e. float, double, long double).
4815 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4816 // if we have an integer operand, the result is the real floating type.
4817 if (rhs->isIntegerType()) {
4818 // convert rhs to the lhs floating point type.
4819 return lhs;
4820 }
4821 if (rhs->isComplexIntegerType()) {
4822 // convert rhs to the complex floating point type.
4823 return getComplexType(lhs);
4824 }
4825 if (lhs->isIntegerType()) {
4826 // convert lhs to the rhs floating point type.
4827 return rhs;
4828 }
Mike Stump1eb44332009-09-09 15:08:12 +00004829 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004830 // convert lhs to the complex floating point type.
4831 return getComplexType(rhs);
4832 }
4833 // We have two real floating types, float/complex combos were handled above.
4834 // Convert the smaller operand to the bigger result.
4835 int result = getFloatingTypeOrder(lhs, rhs);
4836 if (result > 0) // convert the rhs
4837 return lhs;
4838 assert(result < 0 && "illegal float comparison");
4839 return rhs; // convert the lhs
4840 }
4841 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4842 // Handle GCC complex int extension.
4843 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4844 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4845
4846 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004847 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004848 rhsComplexInt->getElementType()) >= 0)
4849 return lhs; // convert the rhs
4850 return rhs;
4851 } else if (lhsComplexInt && rhs->isIntegerType()) {
4852 // convert the rhs to the lhs complex type.
4853 return lhs;
4854 } else if (rhsComplexInt && lhs->isIntegerType()) {
4855 // convert the lhs to the rhs complex type.
4856 return rhs;
4857 }
4858 }
4859 // Finally, we have two differing integer types.
4860 // The rules for this case are in C99 6.3.1.8
4861 int compare = getIntegerTypeOrder(lhs, rhs);
4862 bool lhsSigned = lhs->isSignedIntegerType(),
4863 rhsSigned = rhs->isSignedIntegerType();
4864 QualType destType;
4865 if (lhsSigned == rhsSigned) {
4866 // Same signedness; use the higher-ranked type
4867 destType = compare >= 0 ? lhs : rhs;
4868 } else if (compare != (lhsSigned ? 1 : -1)) {
4869 // The unsigned type has greater than or equal rank to the
4870 // signed type, so use the unsigned type
4871 destType = lhsSigned ? rhs : lhs;
4872 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4873 // The two types are different widths; if we are here, that
4874 // means the signed type is larger than the unsigned type, so
4875 // use the signed type.
4876 destType = lhsSigned ? lhs : rhs;
4877 } else {
4878 // The signed type is higher-ranked than the unsigned type,
4879 // but isn't actually any bigger (like unsigned int and long
4880 // on most 32-bit systems). Use the unsigned type corresponding
4881 // to the signed type.
4882 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4883 }
4884 return destType;
4885}