blob: 6121580bab8768d5301a8da7b4463a99a9427e9b [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();
Mike Stump1eb44332009-09-09 15:08:12 +000051 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000052 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000053 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000054}
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056ASTContext::~ASTContext() {
57 // Deallocate all the types.
58 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000059 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000060 Types.pop_back();
61 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000062
Nuno Lopesb74668e2008-12-17 22:30:25 +000063 {
John McCall0953e762009-09-24 19:53:00 +000064 llvm::FoldingSet<ExtQuals>::iterator
65 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
66 while (I != E)
67 Deallocate(&*I++);
68 }
69
70 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000071 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
72 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
73 while (I != E) {
74 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
75 delete R;
76 }
77 }
78
79 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000080 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
81 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000082 while (I != E) {
83 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
84 delete R;
85 }
86 }
87
Douglas Gregorab452ba2009-03-26 23:50:42 +000088 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000089 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000091 NNSEnd = NestedNameSpecifiers.end();
92 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000093 /* Increment in loop */)
94 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000095
96 if (GlobalNestedNameSpecifier)
97 GlobalNestedNameSpecifier->Destroy(*this);
98
Eli Friedmanb26153c2008-05-27 03:08:09 +000099 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000100}
101
Mike Stump1eb44332009-09-09 15:08:12 +0000102void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000103ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
104 ExternalSource.reset(Source.take());
105}
106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107void ASTContext::PrintStats() const {
108 fprintf(stderr, "*** AST Context Stats:\n");
109 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000110
Douglas Gregordbe833d2009-05-26 14:40:08 +0000111 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000112#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000113#define ABSTRACT_TYPE(Name, Parent)
114#include "clang/AST/TypeNodes.def"
115 0 // Extra
116 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
119 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000120 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 }
122
Douglas Gregordbe833d2009-05-26 14:40:08 +0000123 unsigned Idx = 0;
124 unsigned TotalBytes = 0;
125#define TYPE(Name, Parent) \
126 if (counts[Idx]) \
127 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
128 TotalBytes += counts[Idx] * sizeof(Name##Type); \
129 ++Idx;
130#define ABSTRACT_TYPE(Name, Parent)
131#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Douglas Gregordbe833d2009-05-26 14:40:08 +0000133 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000134
135 if (ExternalSource.get()) {
136 fprintf(stderr, "\n");
137 ExternalSource->PrintStats();
138 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000139}
140
141
John McCalle27ec8a2009-10-23 23:03:21 +0000142void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000143 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000144 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000145 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000146}
147
Reid Spencer5f016e22007-07-11 17:01:13 +0000148void ASTContext::InitBuiltinTypes() {
149 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 // C99 6.2.5p19.
152 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 // C99 6.2.5p2.
155 InitBuiltinType(BoolTy, BuiltinType::Bool);
156 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000157 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 InitBuiltinType(CharTy, BuiltinType::Char_S);
159 else
160 InitBuiltinType(CharTy, BuiltinType::Char_U);
161 // C99 6.2.5p4.
162 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
163 InitBuiltinType(ShortTy, BuiltinType::Short);
164 InitBuiltinType(IntTy, BuiltinType::Int);
165 InitBuiltinType(LongTy, BuiltinType::Long);
166 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 // C99 6.2.5p6.
169 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
170 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
171 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
172 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
173 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 // C99 6.2.5p10.
176 InitBuiltinType(FloatTy, BuiltinType::Float);
177 InitBuiltinType(DoubleTy, BuiltinType::Double);
178 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000179
Chris Lattner2df9ced2009-04-30 02:43:43 +0000180 // GNU extension, 128-bit integers.
181 InitBuiltinType(Int128Ty, BuiltinType::Int128);
182 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
183
Chris Lattner3a250322009-02-26 23:43:47 +0000184 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
185 InitBuiltinType(WCharTy, BuiltinType::WChar);
186 else // C99
187 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000188
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000189 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
190 InitBuiltinType(Char16Ty, BuiltinType::Char16);
191 else // C99
192 Char16Ty = getFromTargetType(Target.getChar16Type());
193
194 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
195 InitBuiltinType(Char32Ty, BuiltinType::Char32);
196 else // C99
197 Char32Ty = getFromTargetType(Target.getChar32Type());
198
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000199 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000200 InitBuiltinType(OverloadTy, BuiltinType::Overload);
201
202 // Placeholder type for type-dependent expressions whose type is
203 // completely unknown. No code should ever check a type against
204 // DependentTy and users should never see it; however, it is here to
205 // help diagnose failures to properly check for type-dependent
206 // expressions.
207 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000208
Mike Stump1eb44332009-09-09 15:08:12 +0000209 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000210 // not yet been deduced.
211 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // C99 6.2.5p11.
214 FloatComplexTy = getComplexType(FloatTy);
215 DoubleComplexTy = getComplexType(DoubleTy);
216 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000217
Steve Naroff7e219e42007-10-15 14:41:52 +0000218 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Steve Naroffde2e22d2009-07-15 18:40:39 +0000220 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
221 ObjCIdTypedefType = QualType();
222 ObjCClassTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Steve Naroffde2e22d2009-07-15 18:40:39 +0000224 // Builtin types for 'id' and 'Class'.
225 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
226 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000227
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000230 // void * type
231 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000232
233 // nullptr type (C++0x 2.14.7)
234 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000235}
236
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000237MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000238ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000239 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000240 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000241 = InstantiatedFromStaticDataMember.find(Var);
242 if (Pos == InstantiatedFromStaticDataMember.end())
243 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Douglas Gregor7caa6822009-07-24 20:34:43 +0000245 return Pos->second;
246}
247
Mike Stump1eb44332009-09-09 15:08:12 +0000248void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000249ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
250 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000251 assert(Inst->isStaticDataMember() && "Not a static data member");
252 assert(Tmpl->isStaticDataMember() && "Not a static data member");
253 assert(!InstantiatedFromStaticDataMember[Inst] &&
254 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000255 InstantiatedFromStaticDataMember[Inst]
256 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000257}
258
John McCall7ba107a2009-11-18 02:36:19 +0000259NamedDecl *
Anders Carlsson0d8df782009-08-29 19:37:28 +0000260ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000261 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
Anders Carlsson0d8df782009-08-29 19:37:28 +0000262 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
263 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
264 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Anders Carlsson0d8df782009-08-29 19:37:28 +0000266 return Pos->second;
267}
268
269void
270ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
John McCall7ba107a2009-11-18 02:36:19 +0000271 NamedDecl *UUD) {
272 assert((isa<UnresolvedUsingValueDecl>(UUD) ||
273 isa<UnresolvedUsingTypenameDecl>(UUD)) &&
274 "original declaration is not an unresolved using decl");
Anders Carlsson0d8df782009-08-29 19:37:28 +0000275 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
276 "Already noted what using decl what instantiated from");
277 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
278}
279
Anders Carlssond8b285f2009-09-01 04:26:58 +0000280FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
281 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
282 = InstantiatedFromUnnamedFieldDecl.find(Field);
283 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
284 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Anders Carlssond8b285f2009-09-01 04:26:58 +0000286 return Pos->second;
287}
288
289void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
290 FieldDecl *Tmpl) {
291 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
292 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
293 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
294 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Anders Carlssond8b285f2009-09-01 04:26:58 +0000296 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
297}
298
Douglas Gregor2e222532009-07-02 17:08:52 +0000299namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000300 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000301 : std::binary_function<SourceRange, SourceRange, bool> {
302 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Douglas Gregor2e222532009-07-02 17:08:52 +0000304 public:
305 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Douglas Gregor2e222532009-07-02 17:08:52 +0000307 bool operator()(SourceRange X, SourceRange Y) {
308 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
309 }
310 };
311}
312
313/// \brief Determine whether the given comment is a Doxygen-style comment.
314///
315/// \param Start the start of the comment text.
316///
317/// \param End the end of the comment text.
318///
319/// \param Member whether we want to check whether this is a member comment
320/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
321/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000322static bool
323isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000324 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000325 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
327 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
328 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor2e222532009-07-02 17:08:52 +0000330 if (End - Start < 4)
331 return false;
332
333 assert(Start[0] == '/' && "Not a comment?");
334 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
335 return false;
336 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
337 return false;
338
339 return (Start[3] == '<') == Member;
340}
341
342/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000343/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000344const char *ASTContext::getCommentForDecl(const Decl *D) {
345 if (!D)
346 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Douglas Gregor2e222532009-07-02 17:08:52 +0000348 // Check whether we have cached a comment string for this declaration
349 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000350 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000351 = DeclComments.find(D);
352 if (Pos != DeclComments.end())
353 return Pos->second.c_str();
354
Mike Stump1eb44332009-09-09 15:08:12 +0000355 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000356 // that source, do so now.
357 if (ExternalSource && !LoadedExternalComments) {
358 std::vector<SourceRange> LoadedComments;
359 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor2e222532009-07-02 17:08:52 +0000361 if (!LoadedComments.empty())
362 Comments.insert(Comments.begin(), LoadedComments.begin(),
363 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Douglas Gregor2e222532009-07-02 17:08:52 +0000365 LoadedExternalComments = true;
366 }
Mike Stump1eb44332009-09-09 15:08:12 +0000367
368 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000369 if (Comments.empty())
370 return 0;
371
372 // If the declaration doesn't map directly to a location in a file, we
373 // can't find the comment.
374 SourceLocation DeclStartLoc = D->getLocStart();
375 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
376 return 0;
377
378 // Find the comment that occurs just before this declaration.
379 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000380 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000381 SourceRange(DeclStartLoc),
382 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 // Decompose the location for the start of the declaration and find the
385 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000386 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000387 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000388 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000389 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Douglas Gregor2e222532009-07-02 17:08:52 +0000391 // First check whether we have a comment for a member.
392 if (LastComment != Comments.end() &&
393 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
394 isDoxygenComment(SourceMgr, *LastComment, true)) {
395 std::pair<FileID, unsigned> LastCommentEndDecomp
396 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
397 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
398 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000399 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000400 LastCommentEndDecomp.second)) {
401 // The Doxygen member comment comes after the declaration starts and
402 // is on the same line and in the same file as the declaration. This
403 // is the comment we want.
404 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000405 Result.append(FileBufferStart +
406 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000407 FileBufferStart + LastCommentEndDecomp.second + 1);
408 return Result.c_str();
409 }
410 }
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Douglas Gregor2e222532009-07-02 17:08:52 +0000412 if (LastComment == Comments.begin())
413 return 0;
414 --LastComment;
415
416 // Decompose the end of the comment.
417 std::pair<FileID, unsigned> LastCommentEndDecomp
418 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Douglas Gregor2e222532009-07-02 17:08:52 +0000420 // If the comment and the declaration aren't in the same file, then they
421 // aren't related.
422 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
423 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregor2e222532009-07-02 17:08:52 +0000425 // Check that we actually have a Doxygen comment.
426 if (!isDoxygenComment(SourceMgr, *LastComment))
427 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregor2e222532009-07-02 17:08:52 +0000429 // Compute the starting line for the declaration and for the end of the
430 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000431 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000432 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
433 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000434 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000435 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Douglas Gregor2e222532009-07-02 17:08:52 +0000437 // If the comment does not end on the line prior to the declaration, then
438 // the comment is not associated with the declaration at all.
439 if (CommentEndLine + 1 != DeclStartLine)
440 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Douglas Gregor2e222532009-07-02 17:08:52 +0000442 // We have a comment, but there may be more comments on the previous lines.
443 // Keep looking so long as the comments are still Doxygen comments and are
444 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000445 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000446 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
447 std::vector<SourceRange>::iterator FirstComment = LastComment;
448 while (FirstComment != Comments.begin()) {
449 // Look at the previous comment
450 --FirstComment;
451 std::pair<FileID, unsigned> Decomp
452 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 // If this previous comment is in a different file, we're done.
455 if (Decomp.first != DeclStartDecomp.first) {
456 ++FirstComment;
457 break;
458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Douglas Gregor2e222532009-07-02 17:08:52 +0000460 // If this comment is not a Doxygen comment, we're done.
461 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
462 ++FirstComment;
463 break;
464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Douglas Gregor2e222532009-07-02 17:08:52 +0000466 // If the line number is not what we expected, we're done.
467 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
468 if (Line != ExpectedLine) {
469 ++FirstComment;
470 break;
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor2e222532009-07-02 17:08:52 +0000473 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000474 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000475 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Douglas Gregor2e222532009-07-02 17:08:52 +0000478 // The iterator range [FirstComment, LastComment] contains all of the
479 // BCPL comments that, together, are associated with this declaration.
480 // Form a single comment block string for this declaration that concatenates
481 // all of these comments.
482 std::string &Result = DeclComments[D];
483 while (FirstComment != LastComment) {
484 std::pair<FileID, unsigned> DecompStart
485 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
486 std::pair<FileID, unsigned> DecompEnd
487 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
488 Result.append(FileBufferStart + DecompStart.second,
489 FileBufferStart + DecompEnd.second + 1);
490 ++FirstComment;
491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregor2e222532009-07-02 17:08:52 +0000493 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000494 Result.append(FileBufferStart +
495 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000496 FileBufferStart + LastCommentEndDecomp.second + 1);
497 return Result.c_str();
498}
499
Chris Lattner464175b2007-07-18 17:52:12 +0000500//===----------------------------------------------------------------------===//
501// Type Sizing and Analysis
502//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000503
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000504/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
505/// scalar floating point type.
506const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000507 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000508 assert(BT && "Not a floating point type!");
509 switch (BT->getKind()) {
510 default: assert(0 && "Not a floating point type!");
511 case BuiltinType::Float: return Target.getFloatFormat();
512 case BuiltinType::Double: return Target.getDoubleFormat();
513 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
514 }
515}
516
Mike Stump196efbf2009-09-22 02:43:44 +0000517/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000518/// specified decl. Note that bitfields do not have a valid alignment, so
519/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000520unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000521 unsigned Align = Target.getCharWidth();
522
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000523 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000524 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000525
Chris Lattneraf707ab2009-01-24 21:53:27 +0000526 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
527 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000528 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000529 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000530 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000531 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
532 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000533 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
534 T = cast<ArrayType>(T)->getElementType();
535
536 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
537 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000538 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000539
540 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000541}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000542
Chris Lattnera7674d82007-07-13 22:13:22 +0000543/// getTypeSize - Return the size of the specified type, in bits. This method
544/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000545///
546/// FIXME: Pointers into different addr spaces could have different sizes and
547/// alignment requirements: getPointerInfo should take an AddrSpace, this
548/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000549std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000550ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000551 uint64_t Width=0;
552 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000553 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000554#define TYPE(Class, Base)
555#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000556#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000557#define DEPENDENT_TYPE(Class, Base) case Type::Class:
558#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000559 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000560 break;
561
Chris Lattner692233e2007-07-13 22:27:08 +0000562 case Type::FunctionNoProto:
563 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000564 // GCC extension: alignof(function) = 32 bits
565 Width = 0;
566 Align = 32;
567 break;
568
Douglas Gregor72564e72009-02-26 23:50:07 +0000569 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000570 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000571 Width = 0;
572 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
573 break;
574
Steve Narofffb22d962007-08-30 01:06:46 +0000575 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000576 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner98be4942008-03-05 18:54:05 +0000578 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000579 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000580 Align = EltInfo.second;
581 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000582 }
Nate Begeman213541a2008-04-18 23:10:10 +0000583 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000584 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000585 const VectorType *VT = cast<VectorType>(T);
586 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
587 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000588 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000589 // If the alignment is not a power of 2, round up to the next power of 2.
590 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000591 if (VT->getNumElements() & (VT->getNumElements()-1)) {
592 Align = llvm::NextPowerOf2(Align);
593 Width = llvm::RoundUpToAlignment(Width, Align);
594 }
Chris Lattner030d8842007-07-19 22:06:24 +0000595 break;
596 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000597
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000598 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000599 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000600 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000601 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000602 // GCC extension: alignof(void) = 8 bits.
603 Width = 0;
604 Align = 8;
605 break;
606
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000607 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000608 Width = Target.getBoolWidth();
609 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000610 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000611 case BuiltinType::Char_S:
612 case BuiltinType::Char_U:
613 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000614 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000615 Width = Target.getCharWidth();
616 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000617 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000618 case BuiltinType::WChar:
619 Width = Target.getWCharWidth();
620 Align = Target.getWCharAlign();
621 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000622 case BuiltinType::Char16:
623 Width = Target.getChar16Width();
624 Align = Target.getChar16Align();
625 break;
626 case BuiltinType::Char32:
627 Width = Target.getChar32Width();
628 Align = Target.getChar32Align();
629 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000630 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getShortWidth();
633 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000636 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000637 Width = Target.getIntWidth();
638 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000640 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000642 Width = Target.getLongWidth();
643 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000645 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000646 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000647 Width = Target.getLongLongWidth();
648 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000649 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000650 case BuiltinType::Int128:
651 case BuiltinType::UInt128:
652 Width = 128;
653 Align = 128; // int128_t is 128-bit aligned on all targets.
654 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getFloatWidth();
657 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
659 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000660 Width = Target.getDoubleWidth();
661 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 break;
663 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000664 Width = Target.getLongDoubleWidth();
665 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000666 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000667 case BuiltinType::NullPtr:
668 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
669 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000670 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000671 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000672 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000673 case Type::FixedWidthInt:
674 // FIXME: This isn't precisely correct; the width/alignment should depend
675 // on the available types for the target
676 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000677 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000678 Align = Width;
679 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000680 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000681 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000682 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000684 case Type::BlockPointer: {
685 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
686 Width = Target.getPointerWidth(AS);
687 Align = Target.getPointerAlign(AS);
688 break;
689 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000690 case Type::Pointer: {
691 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000692 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000693 Align = Target.getPointerAlign(AS);
694 break;
695 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000696 case Type::LValueReference:
697 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000698 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000699 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000700 // FIXME: This is wrong for struct layout: a reference in a struct has
701 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000702 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000703 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000704 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
705 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
706 // If we ever want to support other ABIs this needs to be abstracted.
707
Sebastian Redlf30208a2009-01-24 21:16:55 +0000708 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000709 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000710 getTypeInfo(getPointerDiffType());
711 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000712 if (Pointee->isFunctionType())
713 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000714 Align = PtrDiffInfo.second;
715 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000716 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000717 case Type::Complex: {
718 // Complex types have the same alignment as their elements, but twice the
719 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000720 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000721 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000722 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000723 Align = EltInfo.second;
724 break;
725 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000726 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000727 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000728 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
729 Width = Layout.getSize();
730 Align = Layout.getAlignment();
731 break;
732 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000733 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000734 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000735 const TagType *TT = cast<TagType>(T);
736
737 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000738 Width = 1;
739 Align = 1;
740 break;
741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Daniel Dunbar1d751182008-11-08 05:48:37 +0000743 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000744 return getTypeInfo(ET->getDecl()->getIntegerType());
745
Daniel Dunbar1d751182008-11-08 05:48:37 +0000746 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000747 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
748 Width = Layout.getSize();
749 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000750 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000751 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000752
Chris Lattner9fcfe922009-10-22 05:17:15 +0000753 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000754 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
755 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000756
Chris Lattner9fcfe922009-10-22 05:17:15 +0000757 case Type::Elaborated:
758 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
759 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000760
Douglas Gregor18857642009-04-30 17:32:17 +0000761 case Type::Typedef: {
762 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000763 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000764 Align = std::max(Aligned->getMaxAlignment(),
765 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000766 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
767 } else
768 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000769 break;
Chris Lattner71763312008-04-06 22:05:18 +0000770 }
Douglas Gregor18857642009-04-30 17:32:17 +0000771
772 case Type::TypeOfExpr:
773 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
774 .getTypePtr());
775
776 case Type::TypeOf:
777 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
778
Anders Carlsson395b4752009-06-24 19:06:50 +0000779 case Type::Decltype:
780 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
781 .getTypePtr());
782
Douglas Gregor18857642009-04-30 17:32:17 +0000783 case Type::QualifiedName:
784 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregor18857642009-04-30 17:32:17 +0000786 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000787 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000788 "Cannot request the size of a dependent type");
789 // FIXME: this is likely to be wrong once we support template
790 // aliases, since a template alias could refer to a typedef that
791 // has an __aligned__ attribute on it.
792 return getTypeInfo(getCanonicalType(T));
793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Chris Lattner464175b2007-07-18 17:52:12 +0000795 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000796 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000797}
798
Chris Lattner34ebde42009-01-27 18:08:34 +0000799/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
800/// type for the current target in bits. This can be different than the ABI
801/// alignment in cases where it is beneficial for performance to overalign
802/// a data type.
803unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
804 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000805
806 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000807 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000808 T = CT->getElementType().getTypePtr();
809 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
810 T->isSpecificBuiltinType(BuiltinType::LongLong))
811 return std::max(ABIAlign, (unsigned)getTypeSize(T));
812
Chris Lattner34ebde42009-01-27 18:08:34 +0000813 return ABIAlign;
814}
815
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000816static void CollectLocalObjCIvars(ASTContext *Ctx,
817 const ObjCInterfaceDecl *OI,
818 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000819 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
820 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000821 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000822 if (!IVDecl->isInvalidDecl())
823 Fields.push_back(cast<FieldDecl>(IVDecl));
824 }
825}
826
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000827void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
828 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
829 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
830 CollectObjCIvars(SuperClass, Fields);
831 CollectLocalObjCIvars(this, OI, Fields);
832}
833
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000834/// ShallowCollectObjCIvars -
835/// Collect all ivars, including those synthesized, in the current class.
836///
837void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
838 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
839 bool CollectSynthesized) {
840 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
841 E = OI->ivar_end(); I != E; ++I) {
842 Ivars.push_back(*I);
843 }
844 if (CollectSynthesized)
845 CollectSynthesizedIvars(OI, Ivars);
846}
847
Fariborz Jahanian98200742009-05-12 18:14:29 +0000848void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
849 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000850 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
851 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000852 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
853 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Fariborz Jahanian98200742009-05-12 18:14:29 +0000855 // Also look into nested protocols.
856 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
857 E = PD->protocol_end(); P != E; ++P)
858 CollectProtocolSynthesizedIvars(*P, Ivars);
859}
860
861/// CollectSynthesizedIvars -
862/// This routine collect synthesized ivars for the designated class.
863///
864void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
865 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000866 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
867 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000868 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
869 Ivars.push_back(Ivar);
870 }
871 // Also look into interface's protocol list for properties declared
872 // in the protocol and whose ivars are synthesized.
873 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
874 PE = OI->protocol_end(); P != PE; ++P) {
875 ObjCProtocolDecl *PD = (*P);
876 CollectProtocolSynthesizedIvars(PD, Ivars);
877 }
878}
879
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000880/// CollectInheritedProtocols - Collect all protocols in current class and
881/// those inherited by it.
882void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
883 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
884 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
885 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
886 PE = OI->protocol_end(); P != PE; ++P) {
887 ObjCProtocolDecl *Proto = (*P);
888 Protocols.push_back(Proto);
889 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
890 PE = Proto->protocol_end(); P != PE; ++P)
891 CollectInheritedProtocols(*P, Protocols);
892 }
893
894 // Categories of this Interface.
895 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
896 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
897 CollectInheritedProtocols(CDeclChain, Protocols);
898 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
899 while (SD) {
900 CollectInheritedProtocols(SD, Protocols);
901 SD = SD->getSuperClass();
902 }
903 return;
904 }
905 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
906 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
907 PE = OC->protocol_end(); P != PE; ++P) {
908 ObjCProtocolDecl *Proto = (*P);
909 Protocols.push_back(Proto);
910 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
911 PE = Proto->protocol_end(); P != PE; ++P)
912 CollectInheritedProtocols(*P, Protocols);
913 }
914 return;
915 }
916 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
917 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
918 PE = OP->protocol_end(); P != PE; ++P) {
919 ObjCProtocolDecl *Proto = (*P);
920 Protocols.push_back(Proto);
921 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
922 PE = Proto->protocol_end(); P != PE; ++P)
923 CollectInheritedProtocols(*P, Protocols);
924 }
925 return;
926 }
927}
928
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000929unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
930 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000931 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
932 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000933 if ((*I)->getPropertyIvarDecl())
934 ++count;
935
936 // Also look into nested protocols.
937 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
938 E = PD->protocol_end(); P != E; ++P)
939 count += CountProtocolSynthesizedIvars(*P);
940 return count;
941}
942
Mike Stump1eb44332009-09-09 15:08:12 +0000943unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000944 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000945 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
946 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000947 if ((*I)->getPropertyIvarDecl())
948 ++count;
949 }
950 // Also look into interface's protocol list for properties declared
951 // in the protocol and whose ivars are synthesized.
952 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
953 PE = OI->protocol_end(); P != PE; ++P) {
954 ObjCProtocolDecl *PD = (*P);
955 count += CountProtocolSynthesizedIvars(PD);
956 }
957 return count;
958}
959
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000960/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
961ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
962 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
963 I = ObjCImpls.find(D);
964 if (I != ObjCImpls.end())
965 return cast<ObjCImplementationDecl>(I->second);
966 return 0;
967}
968/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
969ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
970 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
971 I = ObjCImpls.find(D);
972 if (I != ObjCImpls.end())
973 return cast<ObjCCategoryImplDecl>(I->second);
974 return 0;
975}
976
977/// \brief Set the implementation of ObjCInterfaceDecl.
978void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
979 ObjCImplementationDecl *ImplD) {
980 assert(IFaceD && ImplD && "Passed null params");
981 ObjCImpls[IFaceD] = ImplD;
982}
983/// \brief Set the implementation of ObjCCategoryDecl.
984void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
985 ObjCCategoryImplDecl *ImplD) {
986 assert(CatD && ImplD && "Passed null params");
987 ObjCImpls[CatD] = ImplD;
988}
989
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000990/// \brief Allocate an uninitialized DeclaratorInfo.
991///
992/// The caller should initialize the memory held by DeclaratorInfo using
993/// the TypeLoc wrappers.
994///
995/// \param T the type that will be the basis for type source info. This type
996/// should refer to how the declarator was written in source code, not to
997/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +0000998DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
999 unsigned DataSize) {
1000 if (!DataSize)
1001 DataSize = TypeLoc::getFullDataSizeForType(T);
1002 else
1003 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1004 "incorrect data size provided to CreateDeclaratorInfo!");
1005
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001006 DeclaratorInfo *DInfo =
1007 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1008 new (DInfo) DeclaratorInfo(T);
1009 return DInfo;
1010}
1011
John McCalla4eb74d2009-10-23 21:14:09 +00001012DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1013 SourceLocation L) {
1014 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1015 DI->getTypeLoc().initialize(L);
1016 return DI;
1017}
1018
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001019/// getInterfaceLayoutImpl - Get or compute information about the
1020/// layout of the given interface.
1021///
1022/// \param Impl - If given, also include the layout of the interface's
1023/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001024const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001025ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1026 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001027 assert(!D->isForwardDecl() && "Invalid interface decl!");
1028
Devang Patel44a3dde2008-06-04 21:54:36 +00001029 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001030 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001031 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1032 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1033 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001034
Daniel Dunbar453addb2009-05-03 11:16:44 +00001035 // Add in synthesized ivar count if laying out an implementation.
1036 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001037 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001038 unsigned SynthCount = CountSynthesizedIvars(D);
1039 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001040 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001041 // entry. Note we can't cache this because we simply free all
1042 // entries later; however we shouldn't look up implementations
1043 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001044 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001045 return getObjCLayout(D, 0);
1046 }
1047
Mike Stump1eb44332009-09-09 15:08:12 +00001048 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001049 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1050 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Devang Patel44a3dde2008-06-04 21:54:36 +00001052 return *NewEntry;
1053}
1054
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001055const ASTRecordLayout &
1056ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1057 return getObjCLayout(D, 0);
1058}
1059
1060const ASTRecordLayout &
1061ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1062 return getObjCLayout(D->getClassInterface(), D);
1063}
1064
Devang Patel88a981b2007-11-01 19:11:01 +00001065/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001066/// specified record (struct/union/class), which indicates its size and field
1067/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001068const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001069 D = D->getDefinition(*this);
1070 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001071
Chris Lattner464175b2007-07-18 17:52:12 +00001072 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001073 // Note that we can't save a reference to the entry because this function
1074 // is recursive.
1075 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001076 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001077
Mike Stump1eb44332009-09-09 15:08:12 +00001078 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001079 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001080 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Chris Lattner5d2a6302007-07-18 18:26:58 +00001082 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001083}
1084
Chris Lattnera7674d82007-07-13 22:13:22 +00001085//===----------------------------------------------------------------------===//
1086// Type creation/memoization methods
1087//===----------------------------------------------------------------------===//
1088
John McCall0953e762009-09-24 19:53:00 +00001089QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1090 unsigned Fast = Quals.getFastQualifiers();
1091 Quals.removeFastQualifiers();
1092
1093 // Check if we've already instantiated this type.
1094 llvm::FoldingSetNodeID ID;
1095 ExtQuals::Profile(ID, TypeNode, Quals);
1096 void *InsertPos = 0;
1097 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1098 assert(EQ->getQualifiers() == Quals);
1099 QualType T = QualType(EQ, Fast);
1100 return T;
1101 }
1102
John McCall6b304a02009-09-24 23:30:46 +00001103 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001104 ExtQualNodes.InsertNode(New, InsertPos);
1105 QualType T = QualType(New, Fast);
1106 return T;
1107}
1108
1109QualType ASTContext::getVolatileType(QualType T) {
1110 QualType CanT = getCanonicalType(T);
1111 if (CanT.isVolatileQualified()) return T;
1112
1113 QualifierCollector Quals;
1114 const Type *TypeNode = Quals.strip(T);
1115 Quals.addVolatile();
1116
1117 return getExtQualType(TypeNode, Quals);
1118}
1119
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001120QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001121 QualType CanT = getCanonicalType(T);
1122 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001123 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001124
John McCall0953e762009-09-24 19:53:00 +00001125 // If we are composing extended qualifiers together, merge together
1126 // into one ExtQuals node.
1127 QualifierCollector Quals;
1128 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCall0953e762009-09-24 19:53:00 +00001130 // If this type already has an address space specified, it cannot get
1131 // another one.
1132 assert(!Quals.hasAddressSpace() &&
1133 "Type cannot be in multiple addr spaces!");
1134 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
John McCall0953e762009-09-24 19:53:00 +00001136 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001137}
1138
Chris Lattnerb7d25532009-02-18 22:53:11 +00001139QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001140 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001141 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001142 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001143 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001145 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001146 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001147 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001148 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1149 return getPointerType(ResultType);
1150 }
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
John McCall0953e762009-09-24 19:53:00 +00001153 // If we are composing extended qualifiers together, merge together
1154 // into one ExtQuals node.
1155 QualifierCollector Quals;
1156 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001157
John McCall0953e762009-09-24 19:53:00 +00001158 // If this type already has an ObjCGC specified, it cannot get
1159 // another one.
1160 assert(!Quals.hasObjCGCAttr() &&
1161 "Type cannot have multiple ObjCGCs!");
1162 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001163
John McCall0953e762009-09-24 19:53:00 +00001164 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001165}
Chris Lattnera7674d82007-07-13 22:13:22 +00001166
Mike Stump24556362009-07-25 21:26:53 +00001167QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001168 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001169 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001170 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001171 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001172 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001173 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001174 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001175 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001176 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001177 } else {
1178 assert (T->isFunctionType()
1179 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001181 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1182 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001183 } else {
1184 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1185 ResultType
1186 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1187 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1188 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1189 F->getNumExceptions(), F->exception_begin(), true);
1190 }
Mike Stump24556362009-07-25 21:26:53 +00001191 }
John McCall0953e762009-09-24 19:53:00 +00001192
Douglas Gregora4923eb2009-11-16 21:35:15 +00001193 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001194}
1195
Reid Spencer5f016e22007-07-11 17:01:13 +00001196/// getComplexType - Return the uniqued reference to the type for a complex
1197/// number with the specified element type.
1198QualType ASTContext::getComplexType(QualType T) {
1199 // Unique pointers, to guarantee there is only one pointer of a particular
1200 // structure.
1201 llvm::FoldingSetNodeID ID;
1202 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 void *InsertPos = 0;
1205 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1206 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 // If the pointee type isn't canonical, this won't be a canonical type either,
1209 // so fill in the canonical type field.
1210 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001211 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001212 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 // Get the new insert position for the node we care about.
1215 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001216 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 }
John McCall6b304a02009-09-24 23:30:46 +00001218 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 Types.push_back(New);
1220 ComplexTypes.InsertNode(New, InsertPos);
1221 return QualType(New, 0);
1222}
1223
Eli Friedmanf98aba32009-02-13 02:31:07 +00001224QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1225 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1226 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1227 FixedWidthIntType *&Entry = Map[Width];
1228 if (!Entry)
1229 Entry = new FixedWidthIntType(Width, Signed);
1230 return QualType(Entry, 0);
1231}
Reid Spencer5f016e22007-07-11 17:01:13 +00001232
1233/// getPointerType - Return the uniqued reference to the type for a pointer to
1234/// the specified type.
1235QualType ASTContext::getPointerType(QualType T) {
1236 // Unique pointers, to guarantee there is only one pointer of a particular
1237 // structure.
1238 llvm::FoldingSetNodeID ID;
1239 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 void *InsertPos = 0;
1242 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1243 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // If the pointee type isn't canonical, this won't be a canonical type either,
1246 // so fill in the canonical type field.
1247 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001248 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001249 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 // Get the new insert position for the node we care about.
1252 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001253 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 }
John McCall6b304a02009-09-24 23:30:46 +00001255 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 Types.push_back(New);
1257 PointerTypes.InsertNode(New, InsertPos);
1258 return QualType(New, 0);
1259}
1260
Mike Stump1eb44332009-09-09 15:08:12 +00001261/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001262/// a pointer to the specified block.
1263QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001264 assert(T->isFunctionType() && "block of function types only");
1265 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001266 // structure.
1267 llvm::FoldingSetNodeID ID;
1268 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Steve Naroff5618bd42008-08-27 16:04:49 +00001270 void *InsertPos = 0;
1271 if (BlockPointerType *PT =
1272 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1273 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
1275 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001276 // type either so fill in the canonical type field.
1277 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001278 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001279 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Steve Naroff5618bd42008-08-27 16:04:49 +00001281 // Get the new insert position for the node we care about.
1282 BlockPointerType *NewIP =
1283 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001284 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001285 }
John McCall6b304a02009-09-24 23:30:46 +00001286 BlockPointerType *New
1287 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001288 Types.push_back(New);
1289 BlockPointerTypes.InsertNode(New, InsertPos);
1290 return QualType(New, 0);
1291}
1292
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001293/// getLValueReferenceType - Return the uniqued reference to the type for an
1294/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001295QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 // Unique pointers, to guarantee there is only one pointer of a particular
1297 // structure.
1298 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001299 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300
1301 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001302 if (LValueReferenceType *RT =
1303 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305
John McCall54e14c42009-10-22 22:37:11 +00001306 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1307
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 // If the referencee type isn't canonical, this won't be a canonical type
1309 // either, so fill in the canonical type field.
1310 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001311 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1312 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1313 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001314
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001316 LValueReferenceType *NewIP =
1317 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001318 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 }
1320
John McCall6b304a02009-09-24 23:30:46 +00001321 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001322 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1323 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001325 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001326
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001327 return QualType(New, 0);
1328}
1329
1330/// getRValueReferenceType - Return the uniqued reference to the type for an
1331/// rvalue reference to the specified type.
1332QualType ASTContext::getRValueReferenceType(QualType T) {
1333 // Unique pointers, to guarantee there is only one pointer of a particular
1334 // structure.
1335 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001336 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001337
1338 void *InsertPos = 0;
1339 if (RValueReferenceType *RT =
1340 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1341 return QualType(RT, 0);
1342
John McCall54e14c42009-10-22 22:37:11 +00001343 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1344
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001345 // If the referencee type isn't canonical, this won't be a canonical type
1346 // either, so fill in the canonical type field.
1347 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001348 if (InnerRef || !T.isCanonical()) {
1349 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1350 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001351
1352 // Get the new insert position for the node we care about.
1353 RValueReferenceType *NewIP =
1354 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1355 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1356 }
1357
John McCall6b304a02009-09-24 23:30:46 +00001358 RValueReferenceType *New
1359 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001360 Types.push_back(New);
1361 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 return QualType(New, 0);
1363}
1364
Sebastian Redlf30208a2009-01-24 21:16:55 +00001365/// getMemberPointerType - Return the uniqued reference to the type for a
1366/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001367QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001368 // Unique pointers, to guarantee there is only one pointer of a particular
1369 // structure.
1370 llvm::FoldingSetNodeID ID;
1371 MemberPointerType::Profile(ID, T, Cls);
1372
1373 void *InsertPos = 0;
1374 if (MemberPointerType *PT =
1375 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1376 return QualType(PT, 0);
1377
1378 // If the pointee or class type isn't canonical, this won't be a canonical
1379 // type either, so fill in the canonical type field.
1380 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001381 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001382 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1383
1384 // Get the new insert position for the node we care about.
1385 MemberPointerType *NewIP =
1386 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1387 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1388 }
John McCall6b304a02009-09-24 23:30:46 +00001389 MemberPointerType *New
1390 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001391 Types.push_back(New);
1392 MemberPointerTypes.InsertNode(New, InsertPos);
1393 return QualType(New, 0);
1394}
1395
Mike Stump1eb44332009-09-09 15:08:12 +00001396/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001397/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001398QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001399 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001400 ArrayType::ArraySizeModifier ASM,
1401 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001402 assert((EltTy->isDependentType() ||
1403 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001404 "Constant array of VLAs is illegal!");
1405
Chris Lattner38aeec72009-05-13 04:12:56 +00001406 // Convert the array size into a canonical width matching the pointer size for
1407 // the target.
1408 llvm::APInt ArySize(ArySizeIn);
1409 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001412 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001415 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001416 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 // If the element type isn't canonical, this won't be a canonical type either,
1420 // so fill in the canonical type field.
1421 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001422 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001423 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001424 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001426 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001427 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001428 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
John McCall6b304a02009-09-24 23:30:46 +00001431 ConstantArrayType *New = new(*this,TypeAlignment)
1432 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001433 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 Types.push_back(New);
1435 return QualType(New, 0);
1436}
1437
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001438/// getVariableArrayType - Returns a non-unique reference to the type for a
1439/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001440QualType ASTContext::getVariableArrayType(QualType EltTy,
1441 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001442 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001443 unsigned EltTypeQuals,
1444 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001445 // Since we don't unique expressions, it isn't possible to unique VLA's
1446 // that have an expression provided for their size.
1447
John McCall6b304a02009-09-24 23:30:46 +00001448 VariableArrayType *New = new(*this, TypeAlignment)
1449 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001450
1451 VariableArrayTypes.push_back(New);
1452 Types.push_back(New);
1453 return QualType(New, 0);
1454}
1455
Douglas Gregor898574e2008-12-05 23:32:09 +00001456/// getDependentSizedArrayType - Returns a non-unique reference to
1457/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001458/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001459QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1460 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001461 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001462 unsigned EltTypeQuals,
1463 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001464 assert((!NumElts || NumElts->isTypeDependent() ||
1465 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001466 "Size must be type- or value-dependent!");
1467
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001468 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001469 DependentSizedArrayType *Canon = 0;
1470
1471 if (NumElts) {
1472 // Dependently-sized array types that do not have a specified
1473 // number of elements will have their sizes deduced from an
1474 // initializer.
1475 llvm::FoldingSetNodeID ID;
1476 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1477 EltTypeQuals, NumElts);
1478
1479 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1480 }
1481
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001482 DependentSizedArrayType *New;
1483 if (Canon) {
1484 // We already have a canonical version of this array type; use it as
1485 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001486 New = new (*this, TypeAlignment)
1487 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1488 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001489 } else {
1490 QualType CanonEltTy = getCanonicalType(EltTy);
1491 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001492 New = new (*this, TypeAlignment)
1493 DependentSizedArrayType(*this, EltTy, QualType(),
1494 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001495
1496 if (NumElts)
1497 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001498 } else {
1499 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1500 ASM, EltTypeQuals,
1501 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001502 New = new (*this, TypeAlignment)
1503 DependentSizedArrayType(*this, EltTy, Canon,
1504 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001505 }
1506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Douglas Gregor898574e2008-12-05 23:32:09 +00001508 Types.push_back(New);
1509 return QualType(New, 0);
1510}
1511
Eli Friedmanc5773c42008-02-15 18:16:39 +00001512QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1513 ArrayType::ArraySizeModifier ASM,
1514 unsigned EltTypeQuals) {
1515 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001516 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001517
1518 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001519 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001520 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1521 return QualType(ATP, 0);
1522
1523 // If the element type isn't canonical, this won't be a canonical type
1524 // either, so fill in the canonical type field.
1525 QualType Canonical;
1526
John McCall467b27b2009-10-22 20:10:53 +00001527 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001528 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001529 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001530
1531 // Get the new insert position for the node we care about.
1532 IncompleteArrayType *NewIP =
1533 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001534 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001535 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001536
John McCall6b304a02009-09-24 23:30:46 +00001537 IncompleteArrayType *New = new (*this, TypeAlignment)
1538 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001539
1540 IncompleteArrayTypes.InsertNode(New, InsertPos);
1541 Types.push_back(New);
1542 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001543}
1544
Steve Naroff73322922007-07-18 18:00:27 +00001545/// getVectorType - Return the unique reference to a vector type of
1546/// the specified element type and size. VectorType must be a built-in type.
1547QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattnerf52ab252008-04-06 22:59:24 +00001550 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001551 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 // Check if we've already instantiated a vector of this type.
1554 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001555 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 void *InsertPos = 0;
1557 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1558 return QualType(VTP, 0);
1559
1560 // If the element type isn't canonical, this won't be a canonical type either,
1561 // so fill in the canonical type field.
1562 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001563 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001564 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Get the new insert position for the node we care about.
1567 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001568 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 }
John McCall6b304a02009-09-24 23:30:46 +00001570 VectorType *New = new (*this, TypeAlignment)
1571 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 VectorTypes.InsertNode(New, InsertPos);
1573 Types.push_back(New);
1574 return QualType(New, 0);
1575}
1576
Nate Begeman213541a2008-04-18 23:10:10 +00001577/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001578/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001579QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001580 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Chris Lattnerf52ab252008-04-06 22:59:24 +00001582 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001583 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Steve Naroff73322922007-07-18 18:00:27 +00001585 // Check if we've already instantiated a vector of this type.
1586 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001587 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001588 void *InsertPos = 0;
1589 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1590 return QualType(VTP, 0);
1591
1592 // If the element type isn't canonical, this won't be a canonical type either,
1593 // so fill in the canonical type field.
1594 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001595 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001596 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Steve Naroff73322922007-07-18 18:00:27 +00001598 // Get the new insert position for the node we care about.
1599 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001601 }
John McCall6b304a02009-09-24 23:30:46 +00001602 ExtVectorType *New = new (*this, TypeAlignment)
1603 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001604 VectorTypes.InsertNode(New, InsertPos);
1605 Types.push_back(New);
1606 return QualType(New, 0);
1607}
1608
Mike Stump1eb44332009-09-09 15:08:12 +00001609QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001610 Expr *SizeExpr,
1611 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001612 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001613 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001614 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001616 void *InsertPos = 0;
1617 DependentSizedExtVectorType *Canon
1618 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1619 DependentSizedExtVectorType *New;
1620 if (Canon) {
1621 // We already have a canonical version of this array type; use it as
1622 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001623 New = new (*this, TypeAlignment)
1624 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1625 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001626 } else {
1627 QualType CanonVecTy = getCanonicalType(vecType);
1628 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001629 New = new (*this, TypeAlignment)
1630 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1631 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001632 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1633 } else {
1634 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1635 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001636 New = new (*this, TypeAlignment)
1637 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001638 }
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001641 Types.push_back(New);
1642 return QualType(New, 0);
1643}
1644
Douglas Gregor72564e72009-02-26 23:50:07 +00001645/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001646///
Mike Stump24556362009-07-25 21:26:53 +00001647QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 // Unique functions, to guarantee there is only one function of a particular
1649 // structure.
1650 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001651 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001654 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001655 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001659 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001660 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001663 FunctionNoProtoType *NewIP =
1664 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001665 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
John McCall6b304a02009-09-24 23:30:46 +00001668 FunctionNoProtoType *New = new (*this, TypeAlignment)
1669 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001671 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 return QualType(New, 0);
1673}
1674
1675/// getFunctionType - Return a normal function type with a typed argument
1676/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001677QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001678 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001679 unsigned TypeQuals, bool hasExceptionSpec,
1680 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001681 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 // Unique functions, to guarantee there is only one function of a particular
1683 // structure.
1684 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001685 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001686 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001687 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001688
1689 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001690 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001691 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001693
1694 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001695 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001697 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 isCanonical = false;
1699
1700 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001701 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 QualType Canonical;
1703 if (!isCanonical) {
1704 llvm::SmallVector<QualType, 16> CanonicalArgs;
1705 CanonicalArgs.reserve(NumArgs);
1706 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001707 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001708
Chris Lattnerf52ab252008-04-06 22:59:24 +00001709 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001710 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001711 isVariadic, TypeQuals, false,
1712 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001715 FunctionProtoType *NewIP =
1716 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001717 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001719
Douglas Gregor72564e72009-02-26 23:50:07 +00001720 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001721 // for two variable size arrays (for parameter and exception types) at the
1722 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001723 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001724 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1725 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001726 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001727 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001728 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001729 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001731 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 return QualType(FTP, 0);
1733}
1734
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001735/// getTypeDeclType - Return the unique reference to the type for the
1736/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001737QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001738 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001739 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001741 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001742 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001743 else if (isa<TemplateTypeParmDecl>(Decl)) {
1744 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001745 } else if (ObjCInterfaceDecl *ObjCInterface
1746 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001747 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001748
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001749 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001750 if (PrevDecl)
1751 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001752 else
John McCall6b304a02009-09-24 23:30:46 +00001753 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001754 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001755 if (PrevDecl)
1756 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001757 else
John McCall6b304a02009-09-24 23:30:46 +00001758 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001759 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001760 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001761
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001762 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001763 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001764}
1765
Reid Spencer5f016e22007-07-11 17:01:13 +00001766/// getTypedefType - Return the unique reference to the type for the
1767/// specified typename decl.
1768QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1769 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Chris Lattnerf52ab252008-04-06 22:59:24 +00001771 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001772 Decl->TypeForDecl = new(*this, TypeAlignment)
1773 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 Types.push_back(Decl->TypeForDecl);
1775 return QualType(Decl->TypeForDecl, 0);
1776}
1777
John McCall49a832b2009-10-18 09:09:24 +00001778/// \brief Retrieve a substitution-result type.
1779QualType
1780ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1781 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001782 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001783 && "replacement types must always be canonical");
1784
1785 llvm::FoldingSetNodeID ID;
1786 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1787 void *InsertPos = 0;
1788 SubstTemplateTypeParmType *SubstParm
1789 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1790
1791 if (!SubstParm) {
1792 SubstParm = new (*this, TypeAlignment)
1793 SubstTemplateTypeParmType(Parm, Replacement);
1794 Types.push_back(SubstParm);
1795 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1796 }
1797
1798 return QualType(SubstParm, 0);
1799}
1800
Douglas Gregorfab9d672009-02-05 23:33:38 +00001801/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001802/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001803/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001804QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001805 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001806 IdentifierInfo *Name) {
1807 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001808 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001809 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001810 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001811 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1812
1813 if (TypeParm)
1814 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001816 if (Name) {
1817 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001818 TypeParm = new (*this, TypeAlignment)
1819 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001820 } else
John McCall6b304a02009-09-24 23:30:46 +00001821 TypeParm = new (*this, TypeAlignment)
1822 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001823
1824 Types.push_back(TypeParm);
1825 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1826
1827 return QualType(TypeParm, 0);
1828}
1829
Mike Stump1eb44332009-09-09 15:08:12 +00001830QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001831ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall833ca992009-10-29 08:12:44 +00001832 const TemplateArgumentLoc *Args,
1833 unsigned NumArgs,
1834 QualType Canon) {
1835 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1836 ArgVec.reserve(NumArgs);
1837 for (unsigned i = 0; i != NumArgs; ++i)
1838 ArgVec.push_back(Args[i].getArgument());
1839
1840 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1841}
1842
1843QualType
1844ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001845 const TemplateArgument *Args,
1846 unsigned NumArgs,
1847 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001848 if (!Canon.isNull())
1849 Canon = getCanonicalType(Canon);
1850 else {
1851 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001852 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1853 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1854 CanonArgs.reserve(NumArgs);
1855 for (unsigned I = 0; I != NumArgs; ++I)
1856 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1857
1858 // Determine whether this canonical template specialization type already
1859 // exists.
1860 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001861 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001862 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001863
1864 void *InsertPos = 0;
1865 TemplateSpecializationType *Spec
1866 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Douglas Gregor1275ae02009-07-28 23:00:59 +00001868 if (!Spec) {
1869 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001870 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001871 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001872 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001873 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001874 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001875 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001876 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001877 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001878 }
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Douglas Gregorb88e8882009-07-30 17:40:51 +00001880 if (Canon.isNull())
1881 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001882 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001883 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001884 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001885
Douglas Gregor1275ae02009-07-28 23:00:59 +00001886 // Allocate the (non-canonical) template specialization type, but don't
1887 // try to unique it: these types typically have location information that
1888 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001889 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001890 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001891 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001892 TemplateSpecializationType *Spec
1893 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001894 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Douglas Gregor55f6b142009-02-09 18:46:07 +00001896 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001897 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001898}
1899
Mike Stump1eb44332009-09-09 15:08:12 +00001900QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001901ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001902 QualType NamedType) {
1903 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001904 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001905
1906 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001907 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001908 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1909 if (T)
1910 return QualType(T, 0);
1911
Mike Stump1eb44332009-09-09 15:08:12 +00001912 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001913 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001914 Types.push_back(T);
1915 QualifiedNameTypes.InsertNode(T, InsertPos);
1916 return QualType(T, 0);
1917}
1918
Mike Stump1eb44332009-09-09 15:08:12 +00001919QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001920 const IdentifierInfo *Name,
1921 QualType Canon) {
1922 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1923
1924 if (Canon.isNull()) {
1925 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1926 if (CanonNNS != NNS)
1927 Canon = getTypenameType(CanonNNS, Name);
1928 }
1929
1930 llvm::FoldingSetNodeID ID;
1931 TypenameType::Profile(ID, NNS, Name);
1932
1933 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001934 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001935 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1936 if (T)
1937 return QualType(T, 0);
1938
1939 T = new (*this) TypenameType(NNS, Name, Canon);
1940 Types.push_back(T);
1941 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001942 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001943}
1944
Mike Stump1eb44332009-09-09 15:08:12 +00001945QualType
1946ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001947 const TemplateSpecializationType *TemplateId,
1948 QualType Canon) {
1949 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1950
1951 if (Canon.isNull()) {
1952 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1953 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1954 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1955 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001956 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001957 assert(CanonTemplateId &&
1958 "Canonical type must also be a template specialization type");
1959 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1960 }
1961 }
1962
1963 llvm::FoldingSetNodeID ID;
1964 TypenameType::Profile(ID, NNS, TemplateId);
1965
1966 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001967 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001968 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1969 if (T)
1970 return QualType(T, 0);
1971
1972 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1973 Types.push_back(T);
1974 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001975 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001976}
1977
John McCall7da24312009-09-05 00:15:47 +00001978QualType
1979ASTContext::getElaboratedType(QualType UnderlyingType,
1980 ElaboratedType::TagKind Tag) {
1981 llvm::FoldingSetNodeID ID;
1982 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
John McCall7da24312009-09-05 00:15:47 +00001984 void *InsertPos = 0;
1985 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1986 if (T)
1987 return QualType(T, 0);
1988
1989 QualType Canon = getCanonicalType(UnderlyingType);
1990
1991 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1992 Types.push_back(T);
1993 ElaboratedTypes.InsertNode(T, InsertPos);
1994 return QualType(T, 0);
1995}
1996
Chris Lattner88cb27a2008-04-07 04:56:42 +00001997/// CmpProtocolNames - Comparison predicate for sorting protocols
1998/// alphabetically.
1999static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2000 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002001 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002002}
2003
John McCall54e14c42009-10-22 22:37:11 +00002004static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2005 unsigned NumProtocols) {
2006 if (NumProtocols == 0) return true;
2007
2008 for (unsigned i = 1; i != NumProtocols; ++i)
2009 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2010 return false;
2011 return true;
2012}
2013
2014static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002015 unsigned &NumProtocols) {
2016 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Chris Lattner88cb27a2008-04-07 04:56:42 +00002018 // Sort protocols, keyed by name.
2019 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2020
2021 // Remove duplicates.
2022 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2023 NumProtocols = ProtocolsEnd-Protocols;
2024}
2025
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002026/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2027/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002028QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002029 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002030 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002031 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002032 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002033
2034 void *InsertPos = 0;
2035 if (ObjCObjectPointerType *QT =
2036 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2037 return QualType(QT, 0);
2038
John McCall54e14c42009-10-22 22:37:11 +00002039 // Sort the protocol list alphabetically to canonicalize it.
2040 QualType Canonical;
2041 if (!InterfaceT.isCanonical() ||
2042 !areSortedAndUniqued(Protocols, NumProtocols)) {
2043 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2044 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2045 unsigned UniqueCount = NumProtocols;
2046
2047 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2048 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2049
2050 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2051 &Sorted[0], UniqueCount);
2052 } else {
2053 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2054 Protocols, NumProtocols);
2055 }
2056
2057 // Regenerate InsertPos.
2058 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2059 }
2060
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002061 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002062 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002063 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002065 Types.push_back(QType);
2066 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2067 return QualType(QType, 0);
2068}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002069
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002070/// getObjCInterfaceType - Return the unique reference to the type for the
2071/// specified ObjC interface decl. The list of protocols is optional.
2072QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002073 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002074 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002075 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002077 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002078 if (ObjCInterfaceType *QT =
2079 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002080 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
John McCall54e14c42009-10-22 22:37:11 +00002082 // Sort the protocol list alphabetically to canonicalize it.
2083 QualType Canonical;
2084 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2085 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2086 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2087
2088 unsigned UniqueCount = NumProtocols;
2089 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2090
2091 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2092
2093 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2094 }
2095
John McCall6b304a02009-09-24 23:30:46 +00002096 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002097 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002098 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002099
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002100 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002101 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002102 return QualType(QType, 0);
2103}
2104
Douglas Gregor72564e72009-02-26 23:50:07 +00002105/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2106/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002107/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002108/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002109/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002110QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002111 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002112 if (tofExpr->isTypeDependent()) {
2113 llvm::FoldingSetNodeID ID;
2114 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Douglas Gregorb1975722009-07-30 23:18:24 +00002116 void *InsertPos = 0;
2117 DependentTypeOfExprType *Canon
2118 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2119 if (Canon) {
2120 // We already have a "canonical" version of an identical, dependent
2121 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002122 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002123 QualType((TypeOfExprType*)Canon, 0));
2124 }
2125 else {
2126 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002127 Canon
2128 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002129 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2130 toe = Canon;
2131 }
2132 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002133 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002134 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002135 }
Steve Naroff9752f252007-08-01 18:02:17 +00002136 Types.push_back(toe);
2137 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002138}
2139
Steve Naroff9752f252007-08-01 18:02:17 +00002140/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2141/// TypeOfType AST's. The only motivation to unique these nodes would be
2142/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002143/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002144/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002145QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002146 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002147 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002148 Types.push_back(tot);
2149 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002150}
2151
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002152/// getDecltypeForExpr - Given an expr, will return the decltype for that
2153/// expression, according to the rules in C++0x [dcl.type.simple]p4
2154static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002155 if (e->isTypeDependent())
2156 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002158 // If e is an id expression or a class member access, decltype(e) is defined
2159 // as the type of the entity named by e.
2160 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2161 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2162 return VD->getType();
2163 }
2164 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2165 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2166 return FD->getType();
2167 }
2168 // If e is a function call or an invocation of an overloaded operator,
2169 // (parentheses around e are ignored), decltype(e) is defined as the
2170 // return type of that function.
2171 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2172 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002174 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002175
2176 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002177 // defined as T&, otherwise decltype(e) is defined as T.
2178 if (e->isLvalue(Context) == Expr::LV_Valid)
2179 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002181 return T;
2182}
2183
Anders Carlsson395b4752009-06-24 19:06:50 +00002184/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2185/// DecltypeType AST's. The only motivation to unique these nodes would be
2186/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002187/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002188/// on canonical type's (which are always unique).
2189QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002190 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002191 if (e->isTypeDependent()) {
2192 llvm::FoldingSetNodeID ID;
2193 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002195 void *InsertPos = 0;
2196 DependentDecltypeType *Canon
2197 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2198 if (Canon) {
2199 // We already have a "canonical" version of an equivalent, dependent
2200 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002201 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002202 QualType((DecltypeType*)Canon, 0));
2203 }
2204 else {
2205 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002206 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002207 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2208 dt = Canon;
2209 }
2210 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002211 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002212 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002213 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002214 Types.push_back(dt);
2215 return QualType(dt, 0);
2216}
2217
Reid Spencer5f016e22007-07-11 17:01:13 +00002218/// getTagDeclType - Return the unique reference to the type for the
2219/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002220QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002221 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002222 // FIXME: What is the design on getTagDeclType when it requires casting
2223 // away const? mutable?
2224 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002225}
2226
Mike Stump1eb44332009-09-09 15:08:12 +00002227/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2228/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2229/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002230QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002231 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002232}
2233
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002234/// getSignedWCharType - Return the type of "signed wchar_t".
2235/// Used when in C++, as a GCC extension.
2236QualType ASTContext::getSignedWCharType() const {
2237 // FIXME: derive from "Target" ?
2238 return WCharTy;
2239}
2240
2241/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2242/// Used when in C++, as a GCC extension.
2243QualType ASTContext::getUnsignedWCharType() const {
2244 // FIXME: derive from "Target" ?
2245 return UnsignedIntTy;
2246}
2247
Chris Lattner8b9023b2007-07-13 03:05:23 +00002248/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2249/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2250QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002251 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002252}
2253
Chris Lattnere6327742008-04-02 05:18:44 +00002254//===----------------------------------------------------------------------===//
2255// Type Operators
2256//===----------------------------------------------------------------------===//
2257
John McCall54e14c42009-10-22 22:37:11 +00002258CanQualType ASTContext::getCanonicalParamType(QualType T) {
2259 // Push qualifiers into arrays, and then discard any remaining
2260 // qualifiers.
2261 T = getCanonicalType(T);
2262 const Type *Ty = T.getTypePtr();
2263
2264 QualType Result;
2265 if (isa<ArrayType>(Ty)) {
2266 Result = getArrayDecayedType(QualType(Ty,0));
2267 } else if (isa<FunctionType>(Ty)) {
2268 Result = getPointerType(QualType(Ty, 0));
2269 } else {
2270 Result = QualType(Ty, 0);
2271 }
2272
2273 return CanQualType::CreateUnsafe(Result);
2274}
2275
Chris Lattner77c96472008-04-06 22:41:35 +00002276/// getCanonicalType - Return the canonical (structural) type corresponding to
2277/// the specified potentially non-canonical type. The non-canonical version
2278/// of a type may have many "decorated" versions of types. Decorators can
2279/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2280/// to be free of any of these, allowing two canonical types to be compared
2281/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002282CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002283 QualifierCollector Quals;
2284 const Type *Ptr = Quals.strip(T);
2285 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002286
John McCall0953e762009-09-24 19:53:00 +00002287 // The canonical internal type will be the canonical type *except*
2288 // that we push type qualifiers down through array types.
2289
2290 // If there are no new qualifiers to push down, stop here.
2291 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002292 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002293
John McCall0953e762009-09-24 19:53:00 +00002294 // If the type qualifiers are on an array type, get the canonical
2295 // type of the array with the qualifiers applied to the element
2296 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002297 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2298 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002299 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002301 // Get the canonical version of the element with the extra qualifiers on it.
2302 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002303 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002304 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002306 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002307 return CanQualType::CreateUnsafe(
2308 getConstantArrayType(NewEltTy, CAT->getSize(),
2309 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002310 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002311 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002312 return CanQualType::CreateUnsafe(
2313 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002314 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Douglas Gregor898574e2008-12-05 23:32:09 +00002316 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002317 return CanQualType::CreateUnsafe(
2318 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002319 DSAT->getSizeExpr() ?
2320 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002321 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002322 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002323 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002324
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002325 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002326 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002327 VAT->getSizeExpr() ?
2328 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002329 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002330 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002331 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002332}
2333
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002334TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2335 // If this template name refers to a template, the canonical
2336 // template name merely stores the template itself.
2337 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002338 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002339
Mike Stump1eb44332009-09-09 15:08:12 +00002340 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002341 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002342 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2343 OverloadedFunctionDecl *CanonOvl = 0;
2344 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2345 FEnd = Ovl->function_end();
2346 F != FEnd; ++F) {
2347 Decl *Canon = F->get()->getCanonicalDecl();
2348 if (CanonOvl || Canon != F->get()) {
2349 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002350 CanonOvl = OverloadedFunctionDecl::Create(*this,
2351 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002352 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002354 CanonOvl->addOverload(
2355 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2356 }
2357 }
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002359 return TemplateName(CanonOvl? CanonOvl : Ovl);
2360 }
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002362 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2363 assert(DTN && "Non-dependent template names must refer to template decls.");
2364 return DTN->CanonicalTemplateName;
2365}
2366
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002367bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2368 X = getCanonicalTemplateName(X);
2369 Y = getCanonicalTemplateName(Y);
2370 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2371}
2372
Mike Stump1eb44332009-09-09 15:08:12 +00002373TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002374ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2375 switch (Arg.getKind()) {
2376 case TemplateArgument::Null:
2377 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Douglas Gregor1275ae02009-07-28 23:00:59 +00002379 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002380 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Douglas Gregor1275ae02009-07-28 23:00:59 +00002382 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002383 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002384
Douglas Gregor788cd062009-11-11 01:00:40 +00002385 case TemplateArgument::Template:
2386 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2387
Douglas Gregor1275ae02009-07-28 23:00:59 +00002388 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002389 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002390 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregor1275ae02009-07-28 23:00:59 +00002392 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002393 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Douglas Gregor1275ae02009-07-28 23:00:59 +00002395 case TemplateArgument::Pack: {
2396 // FIXME: Allocate in ASTContext
2397 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2398 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002399 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002400 AEnd = Arg.pack_end();
2401 A != AEnd; (void)++A, ++Idx)
2402 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Douglas Gregor1275ae02009-07-28 23:00:59 +00002404 TemplateArgument Result;
2405 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2406 return Result;
2407 }
2408 }
2409
2410 // Silence GCC warning
2411 assert(false && "Unhandled template argument kind");
2412 return TemplateArgument();
2413}
2414
Douglas Gregord57959a2009-03-27 23:10:48 +00002415NestedNameSpecifier *
2416ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002417 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002418 return 0;
2419
2420 switch (NNS->getKind()) {
2421 case NestedNameSpecifier::Identifier:
2422 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002423 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002424 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2425 NNS->getAsIdentifier());
2426
2427 case NestedNameSpecifier::Namespace:
2428 // A namespace is canonical; build a nested-name-specifier with
2429 // this namespace and no prefix.
2430 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2431
2432 case NestedNameSpecifier::TypeSpec:
2433 case NestedNameSpecifier::TypeSpecWithTemplate: {
2434 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002435 return NestedNameSpecifier::Create(*this, 0,
2436 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002437 T.getTypePtr());
2438 }
2439
2440 case NestedNameSpecifier::Global:
2441 // The global specifier is canonical and unique.
2442 return NNS;
2443 }
2444
2445 // Required to silence a GCC warning
2446 return 0;
2447}
2448
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002449
2450const ArrayType *ASTContext::getAsArrayType(QualType T) {
2451 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002452 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002453 // Handle the common positive case fast.
2454 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2455 return AT;
2456 }
Mike Stump1eb44332009-09-09 15:08:12 +00002457
John McCall0953e762009-09-24 19:53:00 +00002458 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002459 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002460 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002461 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002462
John McCall0953e762009-09-24 19:53:00 +00002463 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002464 // implements C99 6.7.3p8: "If the specification of an array type includes
2465 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002467 // If we get here, we either have type qualifiers on the type, or we have
2468 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002469 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002470
John McCall0953e762009-09-24 19:53:00 +00002471 QualifierCollector Qs;
2472 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002474 // If we have a simple case, just return now.
2475 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002476 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002477 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002479 // Otherwise, we have an array and we have qualifiers on it. Push the
2480 // qualifiers into the array element type and return a new array type.
2481 // Get the canonical version of the element with the extra qualifiers on it.
2482 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002483 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002485 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2486 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2487 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002488 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002489 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2490 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2491 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002492 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002493
Mike Stump1eb44332009-09-09 15:08:12 +00002494 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002495 = dyn_cast<DependentSizedArrayType>(ATy))
2496 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002497 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002498 DSAT->getSizeExpr() ?
2499 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002500 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002501 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002502 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002504 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002505 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002506 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002507 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002508 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002509 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002510 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002511}
2512
2513
Chris Lattnere6327742008-04-02 05:18:44 +00002514/// getArrayDecayedType - Return the properly qualified result of decaying the
2515/// specified array type to a pointer. This operation is non-trivial when
2516/// handling typedefs etc. The canonical type of "T" must be an array type,
2517/// this returns a pointer to a properly qualified element of the array.
2518///
2519/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2520QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521 // Get the element type with 'getAsArrayType' so that we don't lose any
2522 // typedefs in the element type of the array. This also handles propagation
2523 // of type qualifiers from the array type into the element type if present
2524 // (C99 6.7.3p8).
2525 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2526 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002528 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002529
2530 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002531 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002532}
2533
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002534QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002535 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002536 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002537 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002538 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2539 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002540 } else {
John McCall0953e762009-09-24 19:53:00 +00002541 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002542 }
2543 }
2544}
2545
Anders Carlssonfbbce492009-09-25 01:23:32 +00002546QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2547 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002548
Anders Carlssonfbbce492009-09-25 01:23:32 +00002549 if (const ArrayType *AT = getAsArrayType(ElemTy))
2550 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Anders Carlsson6183a992008-12-21 03:44:36 +00002552 return ElemTy;
2553}
2554
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002555/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002556uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002557ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2558 uint64_t ElementCount = 1;
2559 do {
2560 ElementCount *= CA->getSize().getZExtValue();
2561 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2562 } while (CA);
2563 return ElementCount;
2564}
2565
Reid Spencer5f016e22007-07-11 17:01:13 +00002566/// getFloatingRank - Return a relative rank for floating point types.
2567/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002568static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002569 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002571
John McCall183700f2009-09-21 23:43:11 +00002572 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2573 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002574 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 case BuiltinType::Float: return FloatRank;
2576 case BuiltinType::Double: return DoubleRank;
2577 case BuiltinType::LongDouble: return LongDoubleRank;
2578 }
2579}
2580
Mike Stump1eb44332009-09-09 15:08:12 +00002581/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2582/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002583/// 'typeDomain' is a real floating point or complex type.
2584/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002585QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2586 QualType Domain) const {
2587 FloatingRank EltRank = getFloatingRank(Size);
2588 if (Domain->isComplexType()) {
2589 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002590 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002591 case FloatRank: return FloatComplexTy;
2592 case DoubleRank: return DoubleComplexTy;
2593 case LongDoubleRank: return LongDoubleComplexTy;
2594 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 }
Chris Lattner1361b112008-04-06 23:58:54 +00002596
2597 assert(Domain->isRealFloatingType() && "Unknown domain!");
2598 switch (EltRank) {
2599 default: assert(0 && "getFloatingRank(): illegal value for rank");
2600 case FloatRank: return FloatTy;
2601 case DoubleRank: return DoubleTy;
2602 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002603 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002604}
2605
Chris Lattner7cfeb082008-04-06 23:55:33 +00002606/// getFloatingTypeOrder - Compare the rank of the two specified floating
2607/// point types, ignoring the domain of the type (i.e. 'double' ==
2608/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002609/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002610int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2611 FloatingRank LHSR = getFloatingRank(LHS);
2612 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Chris Lattnera75cea32008-04-06 23:38:49 +00002614 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002615 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002616 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002617 return 1;
2618 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002619}
2620
Chris Lattnerf52ab252008-04-06 22:59:24 +00002621/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2622/// routine will assert if passed a built-in type that isn't an integer or enum,
2623/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002624unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002625 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002626 if (EnumType* ET = dyn_cast<EnumType>(T))
2627 T = ET->getDecl()->getIntegerType().getTypePtr();
2628
Eli Friedmana3426752009-07-05 23:44:27 +00002629 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2630 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2631
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002632 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2633 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2634
2635 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2636 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2637
Eli Friedmanf98aba32009-02-13 02:31:07 +00002638 // There are two things which impact the integer rank: the width, and
2639 // the ordering of builtins. The builtin ordering is encoded in the
2640 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002641 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002642 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002643
Chris Lattnerf52ab252008-04-06 22:59:24 +00002644 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002645 default: assert(0 && "getIntegerRank(): not a built-in integer");
2646 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002647 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002648 case BuiltinType::Char_S:
2649 case BuiltinType::Char_U:
2650 case BuiltinType::SChar:
2651 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002652 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002653 case BuiltinType::Short:
2654 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002655 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002656 case BuiltinType::Int:
2657 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002658 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002659 case BuiltinType::Long:
2660 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002661 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002662 case BuiltinType::LongLong:
2663 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002664 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002665 case BuiltinType::Int128:
2666 case BuiltinType::UInt128:
2667 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002668 }
2669}
2670
Eli Friedman04e83572009-08-20 04:21:42 +00002671/// \brief Whether this is a promotable bitfield reference according
2672/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2673///
2674/// \returns the type this bit-field will promote to, or NULL if no
2675/// promotion occurs.
2676QualType ASTContext::isPromotableBitField(Expr *E) {
2677 FieldDecl *Field = E->getBitField();
2678 if (!Field)
2679 return QualType();
2680
2681 QualType FT = Field->getType();
2682
2683 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2684 uint64_t BitWidth = BitWidthAP.getZExtValue();
2685 uint64_t IntSize = getTypeSize(IntTy);
2686 // GCC extension compatibility: if the bit-field size is less than or equal
2687 // to the size of int, it gets promoted no matter what its type is.
2688 // For instance, unsigned long bf : 4 gets promoted to signed int.
2689 if (BitWidth < IntSize)
2690 return IntTy;
2691
2692 if (BitWidth == IntSize)
2693 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2694
2695 // Types bigger than int are not subject to promotions, and therefore act
2696 // like the base type.
2697 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2698 // is ridiculous.
2699 return QualType();
2700}
2701
Eli Friedmana95d7572009-08-19 07:44:53 +00002702/// getPromotedIntegerType - Returns the type that Promotable will
2703/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2704/// integer type.
2705QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2706 assert(!Promotable.isNull());
2707 assert(Promotable->isPromotableIntegerType());
2708 if (Promotable->isSignedIntegerType())
2709 return IntTy;
2710 uint64_t PromotableSize = getTypeSize(Promotable);
2711 uint64_t IntSize = getTypeSize(IntTy);
2712 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2713 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2714}
2715
Mike Stump1eb44332009-09-09 15:08:12 +00002716/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002717/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002718/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002719int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002720 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2721 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002722 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Chris Lattnerf52ab252008-04-06 22:59:24 +00002724 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2725 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Chris Lattner7cfeb082008-04-06 23:55:33 +00002727 unsigned LHSRank = getIntegerRank(LHSC);
2728 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Chris Lattner7cfeb082008-04-06 23:55:33 +00002730 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2731 if (LHSRank == RHSRank) return 0;
2732 return LHSRank > RHSRank ? 1 : -1;
2733 }
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Chris Lattner7cfeb082008-04-06 23:55:33 +00002735 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2736 if (LHSUnsigned) {
2737 // If the unsigned [LHS] type is larger, return it.
2738 if (LHSRank >= RHSRank)
2739 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Chris Lattner7cfeb082008-04-06 23:55:33 +00002741 // If the signed type can represent all values of the unsigned type, it
2742 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002743 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002744 return -1;
2745 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002746
Chris Lattner7cfeb082008-04-06 23:55:33 +00002747 // If the unsigned [RHS] type is larger, return it.
2748 if (RHSRank >= LHSRank)
2749 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Chris Lattner7cfeb082008-04-06 23:55:33 +00002751 // If the signed type can represent all values of the unsigned type, it
2752 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002753 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002754 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002755}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002756
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002757static RecordDecl *
2758CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2759 SourceLocation L, IdentifierInfo *Id) {
2760 if (Ctx.getLangOptions().CPlusPlus)
2761 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2762 else
2763 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2764}
2765
Mike Stump1eb44332009-09-09 15:08:12 +00002766// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002767QualType ASTContext::getCFConstantStringType() {
2768 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002769 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002770 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2771 &Idents.get("NSConstantString"));
2772
Anders Carlssonf06273f2007-11-19 00:25:30 +00002773 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Anders Carlsson71993dd2007-08-17 05:31:46 +00002775 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002776 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002777 // int flags;
2778 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002779 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002780 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002781 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002782 FieldTypes[3] = LongTy;
2783
Anders Carlsson71993dd2007-08-17 05:31:46 +00002784 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002785 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002786 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002787 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002788 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002789 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002790 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002791 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002792 }
2793
2794 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002795 }
Mike Stump1eb44332009-09-09 15:08:12 +00002796
Anders Carlsson71993dd2007-08-17 05:31:46 +00002797 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002798}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002799
Douglas Gregor319ac892009-04-23 22:29:11 +00002800void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002801 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002802 assert(Rec && "Invalid CFConstantStringType");
2803 CFConstantStringTypeDecl = Rec->getDecl();
2804}
2805
Mike Stump1eb44332009-09-09 15:08:12 +00002806QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002807 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002808 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002809 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2810 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002812 QualType FieldTypes[] = {
2813 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002814 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002815 getPointerType(UnsignedLongTy),
2816 getConstantArrayType(UnsignedLongTy,
2817 llvm::APInt(32, 5), ArrayType::Normal, 0)
2818 };
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Douglas Gregor44b43212008-12-11 16:49:14 +00002820 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002821 FieldDecl *Field = FieldDecl::Create(*this,
2822 ObjCFastEnumerationStateTypeDecl,
2823 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002824 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002825 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002826 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002827 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002828 }
Mike Stump1eb44332009-09-09 15:08:12 +00002829
Douglas Gregor44b43212008-12-11 16:49:14 +00002830 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002831 }
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002833 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2834}
2835
Mike Stumpadaaad32009-10-20 02:12:22 +00002836QualType ASTContext::getBlockDescriptorType() {
2837 if (BlockDescriptorType)
2838 return getTagDeclType(BlockDescriptorType);
2839
2840 RecordDecl *T;
2841 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002842 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2843 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002844
2845 QualType FieldTypes[] = {
2846 UnsignedLongTy,
2847 UnsignedLongTy,
2848 };
2849
2850 const char *FieldNames[] = {
2851 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002852 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002853 };
2854
2855 for (size_t i = 0; i < 2; ++i) {
2856 FieldDecl *Field = FieldDecl::Create(*this,
2857 T,
2858 SourceLocation(),
2859 &Idents.get(FieldNames[i]),
2860 FieldTypes[i], /*DInfo=*/0,
2861 /*BitWidth=*/0,
2862 /*Mutable=*/false);
2863 T->addDecl(Field);
2864 }
2865
2866 T->completeDefinition(*this);
2867
2868 BlockDescriptorType = T;
2869
2870 return getTagDeclType(BlockDescriptorType);
2871}
2872
2873void ASTContext::setBlockDescriptorType(QualType T) {
2874 const RecordType *Rec = T->getAs<RecordType>();
2875 assert(Rec && "Invalid BlockDescriptorType");
2876 BlockDescriptorType = Rec->getDecl();
2877}
2878
Mike Stump083c25e2009-10-22 00:49:09 +00002879QualType ASTContext::getBlockDescriptorExtendedType() {
2880 if (BlockDescriptorExtendedType)
2881 return getTagDeclType(BlockDescriptorExtendedType);
2882
2883 RecordDecl *T;
2884 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002885 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2886 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002887
2888 QualType FieldTypes[] = {
2889 UnsignedLongTy,
2890 UnsignedLongTy,
2891 getPointerType(VoidPtrTy),
2892 getPointerType(VoidPtrTy)
2893 };
2894
2895 const char *FieldNames[] = {
2896 "reserved",
2897 "Size",
2898 "CopyFuncPtr",
2899 "DestroyFuncPtr"
2900 };
2901
2902 for (size_t i = 0; i < 4; ++i) {
2903 FieldDecl *Field = FieldDecl::Create(*this,
2904 T,
2905 SourceLocation(),
2906 &Idents.get(FieldNames[i]),
2907 FieldTypes[i], /*DInfo=*/0,
2908 /*BitWidth=*/0,
2909 /*Mutable=*/false);
2910 T->addDecl(Field);
2911 }
2912
2913 T->completeDefinition(*this);
2914
2915 BlockDescriptorExtendedType = T;
2916
2917 return getTagDeclType(BlockDescriptorExtendedType);
2918}
2919
2920void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2921 const RecordType *Rec = T->getAs<RecordType>();
2922 assert(Rec && "Invalid BlockDescriptorType");
2923 BlockDescriptorExtendedType = Rec->getDecl();
2924}
2925
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002926bool ASTContext::BlockRequiresCopying(QualType Ty) {
2927 if (Ty->isBlockPointerType())
2928 return true;
2929 if (isObjCNSObjectType(Ty))
2930 return true;
2931 if (Ty->isObjCObjectPointerType())
2932 return true;
2933 return false;
2934}
2935
2936QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2937 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002938 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002939 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002940 // unsigned int __flags;
2941 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002942 // void *__copy_helper; // as needed
2943 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002944 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002945 // } *
2946
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002947 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2948
2949 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002950 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002951 llvm::SmallString<36> Name;
2952 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2953 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002954 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002955 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2956 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002957 T->startDefinition();
2958 QualType Int32Ty = IntTy;
2959 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2960 QualType FieldTypes[] = {
2961 getPointerType(VoidPtrTy),
2962 getPointerType(getTagDeclType(T)),
2963 Int32Ty,
2964 Int32Ty,
2965 getPointerType(VoidPtrTy),
2966 getPointerType(VoidPtrTy),
2967 Ty
2968 };
2969
2970 const char *FieldNames[] = {
2971 "__isa",
2972 "__forwarding",
2973 "__flags",
2974 "__size",
2975 "__copy_helper",
2976 "__destroy_helper",
2977 DeclName,
2978 };
2979
2980 for (size_t i = 0; i < 7; ++i) {
2981 if (!HasCopyAndDispose && i >=4 && i <= 5)
2982 continue;
2983 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2984 &Idents.get(FieldNames[i]),
2985 FieldTypes[i], /*DInfo=*/0,
2986 /*BitWidth=*/0, /*Mutable=*/false);
2987 T->addDecl(Field);
2988 }
2989
2990 T->completeDefinition(*this);
2991
2992 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002993}
2994
2995
2996QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002997 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002998 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002999 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003000 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003001 llvm::SmallString<36> Name;
3002 llvm::raw_svector_ostream(Name) << "__block_literal_"
3003 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003004 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003005 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3006 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003007 QualType FieldTypes[] = {
3008 getPointerType(VoidPtrTy),
3009 IntTy,
3010 IntTy,
3011 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003012 (BlockHasCopyDispose ?
3013 getPointerType(getBlockDescriptorExtendedType()) :
3014 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003015 };
3016
3017 const char *FieldNames[] = {
3018 "__isa",
3019 "__flags",
3020 "__reserved",
3021 "__FuncPtr",
3022 "__descriptor"
3023 };
3024
3025 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003026 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003027 &Idents.get(FieldNames[i]),
3028 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003029 /*BitWidth=*/0, /*Mutable=*/false);
3030 T->addDecl(Field);
3031 }
3032
3033 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3034 const Expr *E = BlockDeclRefDecls[i];
3035 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3036 clang::IdentifierInfo *Name = 0;
3037 if (BDRE) {
3038 const ValueDecl *D = BDRE->getDecl();
3039 Name = &Idents.get(D->getName());
3040 }
3041 QualType FieldType = E->getType();
3042
3043 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003044 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3045 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003046
3047 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3048 Name, FieldType, /*DInfo=*/0,
3049 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003050 T->addDecl(Field);
3051 }
3052
3053 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003054
3055 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003056}
3057
Douglas Gregor319ac892009-04-23 22:29:11 +00003058void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003059 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003060 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3061 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3062}
3063
Anders Carlssone8c49532007-10-29 06:33:42 +00003064// This returns true if a type has been typedefed to BOOL:
3065// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003066static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003067 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003068 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3069 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003070
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003071 return false;
3072}
3073
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003074/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003075/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003076int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003077 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003079 // Make all integer and enum types at least as large as an int
3080 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003081 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003082 // Treat arrays as pointers, since that's how they're passed in.
3083 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003084 sz = getTypeSize(VoidPtrTy);
3085 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003086}
3087
David Chisnall5e530af2009-11-17 19:33:30 +00003088/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3089/// declaration.
3090void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3091 std::string& S) {
3092 const BlockDecl *Decl = Expr->getBlockDecl();
3093 QualType BlockTy =
3094 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3095 // Encode result type.
3096 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3097 // Compute size of all parameters.
3098 // Start with computing size of a pointer in number of bytes.
3099 // FIXME: There might(should) be a better way of doing this computation!
3100 SourceLocation Loc;
3101 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3102 int ParmOffset = PtrSize;
3103 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3104 E = Decl->param_end(); PI != E; ++PI) {
3105 QualType PType = (*PI)->getType();
3106 int sz = getObjCEncodingTypeSize(PType);
3107 assert (sz > 0 && "BlockExpr - Incomplete param type");
3108 ParmOffset += sz;
3109 }
3110 // Size of the argument frame
3111 S += llvm::utostr(ParmOffset);
3112 // Block pointer and offset.
3113 S += "@?0";
3114 ParmOffset = PtrSize;
3115
3116 // Argument types.
3117 ParmOffset = PtrSize;
3118 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3119 Decl->param_end(); PI != E; ++PI) {
3120 ParmVarDecl *PVDecl = *PI;
3121 QualType PType = PVDecl->getOriginalType();
3122 if (const ArrayType *AT =
3123 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3124 // Use array's original type only if it has known number of
3125 // elements.
3126 if (!isa<ConstantArrayType>(AT))
3127 PType = PVDecl->getType();
3128 } else if (PType->isFunctionType())
3129 PType = PVDecl->getType();
3130 getObjCEncodingForType(PType, S);
3131 S += llvm::utostr(ParmOffset);
3132 ParmOffset += getObjCEncodingTypeSize(PType);
3133 }
3134}
3135
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003136/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003137/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003138void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003139 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003140 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003141 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003142 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003143 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003144 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003145 // Compute size of all parameters.
3146 // Start with computing size of a pointer in number of bytes.
3147 // FIXME: There might(should) be a better way of doing this computation!
3148 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003149 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003150 // The first two arguments (self and _cmd) are pointers; account for
3151 // their size.
3152 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003153 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3154 E = Decl->param_end(); PI != E; ++PI) {
3155 QualType PType = (*PI)->getType();
3156 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003157 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003158 ParmOffset += sz;
3159 }
3160 S += llvm::utostr(ParmOffset);
3161 S += "@0:";
3162 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003164 // Argument types.
3165 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003166 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3167 E = Decl->param_end(); PI != E; ++PI) {
3168 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003169 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003170 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003171 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3172 // Use array's original type only if it has known number of
3173 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003174 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003175 PType = PVDecl->getType();
3176 } else if (PType->isFunctionType())
3177 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003178 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003179 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003180 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003181 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003182 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003183 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003184 }
3185}
3186
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003187/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003188/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003189/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3190/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003191/// Property attributes are stored as a comma-delimited C string. The simple
3192/// attributes readonly and bycopy are encoded as single characters. The
3193/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3194/// encoded as single characters, followed by an identifier. Property types
3195/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003196/// these attributes are defined by the following enumeration:
3197/// @code
3198/// enum PropertyAttributes {
3199/// kPropertyReadOnly = 'R', // property is read-only.
3200/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3201/// kPropertyByref = '&', // property is a reference to the value last assigned
3202/// kPropertyDynamic = 'D', // property is dynamic
3203/// kPropertyGetter = 'G', // followed by getter selector name
3204/// kPropertySetter = 'S', // followed by setter selector name
3205/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3206/// kPropertyType = 't' // followed by old-style type encoding.
3207/// kPropertyWeak = 'W' // 'weak' property
3208/// kPropertyStrong = 'P' // property GC'able
3209/// kPropertyNonAtomic = 'N' // property non-atomic
3210/// };
3211/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003212void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003213 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003214 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003215 // Collect information from the property implementation decl(s).
3216 bool Dynamic = false;
3217 ObjCPropertyImplDecl *SynthesizePID = 0;
3218
3219 // FIXME: Duplicated code due to poor abstraction.
3220 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003221 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003222 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3223 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003224 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003225 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003226 ObjCPropertyImplDecl *PID = *i;
3227 if (PID->getPropertyDecl() == PD) {
3228 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3229 Dynamic = true;
3230 } else {
3231 SynthesizePID = PID;
3232 }
3233 }
3234 }
3235 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003236 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003237 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003238 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003239 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003240 ObjCPropertyImplDecl *PID = *i;
3241 if (PID->getPropertyDecl() == PD) {
3242 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3243 Dynamic = true;
3244 } else {
3245 SynthesizePID = PID;
3246 }
3247 }
Mike Stump1eb44332009-09-09 15:08:12 +00003248 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003249 }
3250 }
3251
3252 // FIXME: This is not very efficient.
3253 S = "T";
3254
3255 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003256 // GCC has some special rules regarding encoding of properties which
3257 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003258 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003259 true /* outermost type */,
3260 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003261
3262 if (PD->isReadOnly()) {
3263 S += ",R";
3264 } else {
3265 switch (PD->getSetterKind()) {
3266 case ObjCPropertyDecl::Assign: break;
3267 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003268 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003269 }
3270 }
3271
3272 // It really isn't clear at all what this means, since properties
3273 // are "dynamic by default".
3274 if (Dynamic)
3275 S += ",D";
3276
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003277 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3278 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3281 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003282 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003283 }
3284
3285 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3286 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003287 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003288 }
3289
3290 if (SynthesizePID) {
3291 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3292 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003293 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003294 }
3295
3296 // FIXME: OBJCGC: weak & strong
3297}
3298
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003299/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003300/// Another legacy compatibility encoding: 32-bit longs are encoded as
3301/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003302/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3303///
3304void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003305 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003306 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003307 if (BT->getKind() == BuiltinType::ULong &&
3308 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003309 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003310 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003311 if (BT->getKind() == BuiltinType::Long &&
3312 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003313 PointeeTy = IntTy;
3314 }
3315 }
3316}
3317
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003318void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003319 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003320 // We follow the behavior of gcc, expanding structures which are
3321 // directly pointed to, and expanding embedded structures. Note that
3322 // these rules are sufficient to prevent recursive encoding of the
3323 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003324 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003325 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003326}
3327
Mike Stump1eb44332009-09-09 15:08:12 +00003328static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003329 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003330 const Expr *E = FD->getBitWidth();
3331 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3332 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003333 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003334 S += 'b';
3335 S += llvm::utostr(N);
3336}
3337
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003338// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003339void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3340 bool ExpandPointedToStructures,
3341 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003342 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003343 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003344 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003345 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003346 if (FD && FD->isBitField())
3347 return EncodeBitField(this, S, FD);
3348 char encoding;
3349 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003350 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003351 case BuiltinType::Void: encoding = 'v'; break;
3352 case BuiltinType::Bool: encoding = 'B'; break;
3353 case BuiltinType::Char_U:
3354 case BuiltinType::UChar: encoding = 'C'; break;
3355 case BuiltinType::UShort: encoding = 'S'; break;
3356 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003357 case BuiltinType::ULong:
3358 encoding =
3359 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003360 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003361 case BuiltinType::UInt128: encoding = 'T'; break;
3362 case BuiltinType::ULongLong: encoding = 'Q'; break;
3363 case BuiltinType::Char_S:
3364 case BuiltinType::SChar: encoding = 'c'; break;
3365 case BuiltinType::Short: encoding = 's'; break;
3366 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003367 case BuiltinType::Long:
3368 encoding =
3369 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003370 break;
3371 case BuiltinType::LongLong: encoding = 'q'; break;
3372 case BuiltinType::Int128: encoding = 't'; break;
3373 case BuiltinType::Float: encoding = 'f'; break;
3374 case BuiltinType::Double: encoding = 'd'; break;
3375 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003376 }
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003378 S += encoding;
3379 return;
3380 }
Mike Stump1eb44332009-09-09 15:08:12 +00003381
John McCall183700f2009-09-21 23:43:11 +00003382 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003383 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003384 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003385 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003386 return;
3387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Ted Kremenek6217b802009-07-29 21:53:49 +00003389 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003390 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003391 bool isReadOnly = false;
3392 // For historical/compatibility reasons, the read-only qualifier of the
3393 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3394 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003395 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003396 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003397 if (OutermostType && T.isConstQualified()) {
3398 isReadOnly = true;
3399 S += 'r';
3400 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003401 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003402 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003403 while (P->getAs<PointerType>())
3404 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003405 if (P.isConstQualified()) {
3406 isReadOnly = true;
3407 S += 'r';
3408 }
3409 }
3410 if (isReadOnly) {
3411 // Another legacy compatibility encoding. Some ObjC qualifier and type
3412 // combinations need to be rearranged.
3413 // Rewrite "in const" from "nr" to "rn"
3414 const char * s = S.c_str();
3415 int len = S.length();
3416 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3417 std::string replace = "rn";
3418 S.replace(S.end()-2, S.end(), replace);
3419 }
3420 }
Steve Naroff14108da2009-07-10 23:34:53 +00003421 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003422 S += ':';
3423 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003424 }
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003426 if (PointeeTy->isCharType()) {
3427 // char pointer types should be encoded as '*' unless it is a
3428 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003429 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003430 S += '*';
3431 return;
3432 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003433 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003434 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3435 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3436 S += '#';
3437 return;
3438 }
3439 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3440 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3441 S += '@';
3442 return;
3443 }
3444 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003445 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003446 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003447 getLegacyIntegralTypeEncoding(PointeeTy);
3448
Mike Stump1eb44332009-09-09 15:08:12 +00003449 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003450 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003451 return;
3452 }
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003454 if (const ArrayType *AT =
3455 // Ignore type qualifiers etc.
3456 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003457 if (isa<IncompleteArrayType>(AT)) {
3458 // Incomplete arrays are encoded as a pointer to the array element.
3459 S += '^';
3460
Mike Stump1eb44332009-09-09 15:08:12 +00003461 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003462 false, ExpandStructures, FD);
3463 } else {
3464 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Anders Carlsson559a8332009-02-22 01:38:57 +00003466 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3467 S += llvm::utostr(CAT->getSize().getZExtValue());
3468 else {
3469 //Variable length arrays are encoded as a regular array with 0 elements.
3470 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3471 S += '0';
3472 }
Mike Stump1eb44332009-09-09 15:08:12 +00003473
3474 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003475 false, ExpandStructures, FD);
3476 S += ']';
3477 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003478 return;
3479 }
Mike Stump1eb44332009-09-09 15:08:12 +00003480
John McCall183700f2009-09-21 23:43:11 +00003481 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003482 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003483 return;
3484 }
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Ted Kremenek6217b802009-07-29 21:53:49 +00003486 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003487 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003488 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003489 // Anonymous structures print as '?'
3490 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3491 S += II->getName();
3492 } else {
3493 S += '?';
3494 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003495 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003496 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003497 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3498 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003499 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003500 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003501 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003502 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003503 S += '"';
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003506 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003507 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003508 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003509 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003510 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003511 QualType qt = Field->getType();
3512 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003513 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003514 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003515 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003516 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003517 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003518 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003519 return;
3520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003522 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003523 if (FD && FD->isBitField())
3524 EncodeBitField(this, S, FD);
3525 else
3526 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003527 return;
3528 }
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003530 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003531 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003532 return;
3533 }
Mike Stump1eb44332009-09-09 15:08:12 +00003534
John McCall0953e762009-09-24 19:53:00 +00003535 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003536 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003537 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003538 S += '{';
3539 const IdentifierInfo *II = OI->getIdentifier();
3540 S += II->getName();
3541 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003542 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003543 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003544 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003545 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003546 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003547 RecFields[i]);
3548 else
Mike Stump1eb44332009-09-09 15:08:12 +00003549 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003550 FD);
3551 }
3552 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003553 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003554 }
Mike Stump1eb44332009-09-09 15:08:12 +00003555
John McCall183700f2009-09-21 23:43:11 +00003556 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003557 if (OPT->isObjCIdType()) {
3558 S += '@';
3559 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003560 }
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Steve Naroff27d20a22009-10-28 22:03:49 +00003562 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3563 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3564 // Since this is a binary compatibility issue, need to consult with runtime
3565 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003566 S += '#';
3567 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003568 }
Mike Stump1eb44332009-09-09 15:08:12 +00003569
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003570 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003571 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003572 ExpandPointedToStructures,
3573 ExpandStructures, FD);
3574 if (FD || EncodingProperty) {
3575 // Note that we do extended encoding of protocol qualifer list
3576 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003577 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003578 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3579 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003580 S += '<';
3581 S += (*I)->getNameAsString();
3582 S += '>';
3583 }
3584 S += '"';
3585 }
3586 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003587 }
Mike Stump1eb44332009-09-09 15:08:12 +00003588
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003589 QualType PointeeTy = OPT->getPointeeType();
3590 if (!EncodingProperty &&
3591 isa<TypedefType>(PointeeTy.getTypePtr())) {
3592 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003593 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003594 // {...};
3595 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003596 getObjCEncodingForTypeImpl(PointeeTy, S,
3597 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003599 return;
3600 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003601
3602 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003603 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003604 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003605 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003606 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3607 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003608 S += '<';
3609 S += (*I)->getNameAsString();
3610 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003611 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003612 S += '"';
3613 }
3614 return;
3615 }
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003617 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003618}
3619
Mike Stump1eb44332009-09-09 15:08:12 +00003620void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003621 std::string& S) const {
3622 if (QT & Decl::OBJC_TQ_In)
3623 S += 'n';
3624 if (QT & Decl::OBJC_TQ_Inout)
3625 S += 'N';
3626 if (QT & Decl::OBJC_TQ_Out)
3627 S += 'o';
3628 if (QT & Decl::OBJC_TQ_Bycopy)
3629 S += 'O';
3630 if (QT & Decl::OBJC_TQ_Byref)
3631 S += 'R';
3632 if (QT & Decl::OBJC_TQ_Oneway)
3633 S += 'V';
3634}
3635
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003636void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003637 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003639 BuiltinVaListType = T;
3640}
3641
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003642void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003643 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003644}
3645
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003646void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003647 ObjCSelType = T;
3648
John McCall183700f2009-09-21 23:43:11 +00003649 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003650 if (!TT)
3651 return;
3652 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003653
3654 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003655 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003656 if (!ptr)
3657 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003658 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003659 if (!rec)
3660 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003661 SelStructType = rec;
3662}
3663
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003664void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003665 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003666}
3667
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003668void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003669 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003670}
3671
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003672void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003673 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003674 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003676 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003677}
3678
Douglas Gregor7532dc62009-03-30 22:58:21 +00003679/// \brief Retrieve the template name that represents a qualified
3680/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003681TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003682 bool TemplateKeyword,
3683 TemplateDecl *Template) {
3684 llvm::FoldingSetNodeID ID;
3685 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3686
3687 void *InsertPos = 0;
3688 QualifiedTemplateName *QTN =
3689 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3690 if (!QTN) {
3691 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3692 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3693 }
3694
3695 return TemplateName(QTN);
3696}
3697
Douglas Gregord99cbe62009-07-29 18:26:50 +00003698/// \brief Retrieve the template name that represents a qualified
3699/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003700TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003701 bool TemplateKeyword,
3702 OverloadedFunctionDecl *Template) {
3703 llvm::FoldingSetNodeID ID;
3704 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregord99cbe62009-07-29 18:26:50 +00003706 void *InsertPos = 0;
3707 QualifiedTemplateName *QTN =
3708 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3709 if (!QTN) {
3710 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3711 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3712 }
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Douglas Gregord99cbe62009-07-29 18:26:50 +00003714 return TemplateName(QTN);
3715}
3716
Douglas Gregor7532dc62009-03-30 22:58:21 +00003717/// \brief Retrieve the template name that represents a dependent
3718/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003719TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003720 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003721 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003722 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003723
3724 llvm::FoldingSetNodeID ID;
3725 DependentTemplateName::Profile(ID, NNS, Name);
3726
3727 void *InsertPos = 0;
3728 DependentTemplateName *QTN =
3729 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3730
3731 if (QTN)
3732 return TemplateName(QTN);
3733
3734 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3735 if (CanonNNS == NNS) {
3736 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3737 } else {
3738 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3739 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3740 }
3741
3742 DependentTemplateNames.InsertNode(QTN, InsertPos);
3743 return TemplateName(QTN);
3744}
3745
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003746/// \brief Retrieve the template name that represents a dependent
3747/// template name such as \c MetaFun::template operator+.
3748TemplateName
3749ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3750 OverloadedOperatorKind Operator) {
3751 assert((!NNS || NNS->isDependent()) &&
3752 "Nested name specifier must be dependent");
3753
3754 llvm::FoldingSetNodeID ID;
3755 DependentTemplateName::Profile(ID, NNS, Operator);
3756
3757 void *InsertPos = 0;
3758 DependentTemplateName *QTN =
3759 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3760
3761 if (QTN)
3762 return TemplateName(QTN);
3763
3764 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3765 if (CanonNNS == NNS) {
3766 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3767 } else {
3768 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3769 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3770 }
3771
3772 DependentTemplateNames.InsertNode(QTN, InsertPos);
3773 return TemplateName(QTN);
3774}
3775
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003776/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003777/// TargetInfo, produce the corresponding type. The unsigned @p Type
3778/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003779CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003780 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003781 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003782 case TargetInfo::SignedShort: return ShortTy;
3783 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3784 case TargetInfo::SignedInt: return IntTy;
3785 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3786 case TargetInfo::SignedLong: return LongTy;
3787 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3788 case TargetInfo::SignedLongLong: return LongLongTy;
3789 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3790 }
3791
3792 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003793 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003794}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003795
3796//===----------------------------------------------------------------------===//
3797// Type Predicates.
3798//===----------------------------------------------------------------------===//
3799
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003800/// isObjCNSObjectType - Return true if this is an NSObject object using
3801/// NSObject attribute on a c-style pointer type.
3802/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003803/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003804///
3805bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3806 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3807 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003808 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003809 return true;
3810 }
Mike Stump1eb44332009-09-09 15:08:12 +00003811 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003812}
3813
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003814/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3815/// garbage collection attribute.
3816///
John McCall0953e762009-09-24 19:53:00 +00003817Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3818 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003819 if (getLangOptions().ObjC1 &&
3820 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003821 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003822 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003823 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003824 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003825 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003826 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003827 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003828 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003829 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003830 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003831 // Non-pointers have none gc'able attribute regardless of the attribute
3832 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003833 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003834 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003835 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003836 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003837}
3838
Chris Lattner6ac46a42008-04-07 06:51:04 +00003839//===----------------------------------------------------------------------===//
3840// Type Compatibility Testing
3841//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003842
Mike Stump1eb44332009-09-09 15:08:12 +00003843/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003844/// compatible.
3845static bool areCompatVectorTypes(const VectorType *LHS,
3846 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003847 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003848 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003849 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003850}
3851
Steve Naroff4084c302009-07-23 01:01:38 +00003852//===----------------------------------------------------------------------===//
3853// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3854//===----------------------------------------------------------------------===//
3855
3856/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3857/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003858bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3859 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003860 if (lProto == rProto)
3861 return true;
3862 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3863 E = rProto->protocol_end(); PI != E; ++PI)
3864 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3865 return true;
3866 return false;
3867}
3868
Steve Naroff4084c302009-07-23 01:01:38 +00003869/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3870/// return true if lhs's protocols conform to rhs's protocol; false
3871/// otherwise.
3872bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3873 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3874 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3875 return false;
3876}
3877
3878/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3879/// ObjCQualifiedIDType.
3880bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3881 bool compare) {
3882 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003883 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003884 lhs->isObjCIdType() || lhs->isObjCClassType())
3885 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003886 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003887 rhs->isObjCIdType() || rhs->isObjCClassType())
3888 return true;
3889
3890 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003891 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003892
Steve Naroff4084c302009-07-23 01:01:38 +00003893 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Steve Naroff4084c302009-07-23 01:01:38 +00003895 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003896 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003897 // make sure we check the class hierarchy.
3898 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3899 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3900 E = lhsQID->qual_end(); I != E; ++I) {
3901 // when comparing an id<P> on lhs with a static type on rhs,
3902 // see if static class implements all of id's protocols, directly or
3903 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003904 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003905 return false;
3906 }
3907 }
3908 // If there are no qualifiers and no interface, we have an 'id'.
3909 return true;
3910 }
Mike Stump1eb44332009-09-09 15:08:12 +00003911 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003912 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3913 E = lhsQID->qual_end(); I != E; ++I) {
3914 ObjCProtocolDecl *lhsProto = *I;
3915 bool match = false;
3916
3917 // when comparing an id<P> on lhs with a static type on rhs,
3918 // see if static class implements all of id's protocols, directly or
3919 // through its super class and categories.
3920 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3921 E = rhsOPT->qual_end(); J != E; ++J) {
3922 ObjCProtocolDecl *rhsProto = *J;
3923 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3924 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3925 match = true;
3926 break;
3927 }
3928 }
Mike Stump1eb44332009-09-09 15:08:12 +00003929 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003930 // make sure we check the class hierarchy.
3931 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3932 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3933 E = lhsQID->qual_end(); I != E; ++I) {
3934 // when comparing an id<P> on lhs with a static type on rhs,
3935 // see if static class implements all of id's protocols, directly or
3936 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003937 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003938 match = true;
3939 break;
3940 }
3941 }
3942 }
3943 if (!match)
3944 return false;
3945 }
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Steve Naroff4084c302009-07-23 01:01:38 +00003947 return true;
3948 }
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Steve Naroff4084c302009-07-23 01:01:38 +00003950 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3951 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3952
Mike Stump1eb44332009-09-09 15:08:12 +00003953 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003954 lhs->getAsObjCInterfacePointerType()) {
3955 if (lhsOPT->qual_empty()) {
3956 bool match = false;
3957 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3958 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3959 E = rhsQID->qual_end(); I != E; ++I) {
3960 // when comparing an id<P> on lhs with a static type on rhs,
3961 // see if static class implements all of id's protocols, directly or
3962 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003963 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003964 match = true;
3965 break;
3966 }
3967 }
3968 if (!match)
3969 return false;
3970 }
3971 return true;
3972 }
Mike Stump1eb44332009-09-09 15:08:12 +00003973 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003974 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3975 E = lhsOPT->qual_end(); I != E; ++I) {
3976 ObjCProtocolDecl *lhsProto = *I;
3977 bool match = false;
3978
3979 // when comparing an id<P> on lhs with a static type on rhs,
3980 // see if static class implements all of id's protocols, directly or
3981 // through its super class and categories.
3982 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3983 E = rhsQID->qual_end(); J != E; ++J) {
3984 ObjCProtocolDecl *rhsProto = *J;
3985 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3986 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3987 match = true;
3988 break;
3989 }
3990 }
3991 if (!match)
3992 return false;
3993 }
3994 return true;
3995 }
3996 return false;
3997}
3998
Eli Friedman3d815e72008-08-22 00:56:42 +00003999/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004000/// compatible for assignment from RHS to LHS. This handles validation of any
4001/// protocol qualifiers on the LHS or RHS.
4002///
Steve Naroff14108da2009-07-10 23:34:53 +00004003bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4004 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004005 // If either type represents the built-in 'id' or 'Class' types, return true.
4006 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004007 return true;
4008
Steve Naroff4084c302009-07-23 01:01:38 +00004009 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004010 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4011 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004012 false);
4013
Steve Naroff14108da2009-07-10 23:34:53 +00004014 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4015 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004016 if (LHS && RHS) // We have 2 user-defined types.
4017 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Steve Naroff4084c302009-07-23 01:01:38 +00004019 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004020}
4021
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004022/// getIntersectionOfProtocols - This routine finds the intersection of set
4023/// of protocols inherited from two distinct objective-c pointer objects.
4024/// It is used to build composite qualifier list of the composite type of
4025/// the conditional expression involving two objective-c pointer objects.
4026static
4027void getIntersectionOfProtocols(ASTContext &Context,
4028 const ObjCObjectPointerType *LHSOPT,
4029 const ObjCObjectPointerType *RHSOPT,
4030 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4031
4032 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4033 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4034
4035 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4036 unsigned LHSNumProtocols = LHS->getNumProtocols();
4037 if (LHSNumProtocols > 0)
4038 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4039 else {
4040 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4041 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4042 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4043 LHSInheritedProtocols.end());
4044 }
4045
4046 unsigned RHSNumProtocols = RHS->getNumProtocols();
4047 if (RHSNumProtocols > 0) {
4048 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4049 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4050 if (InheritedProtocolSet.count(RHSProtocols[i]))
4051 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4052 }
4053 else {
4054 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4055 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4056 // FIXME. This may cause duplication of protocols in the list, but should
4057 // be harmless.
4058 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4059 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4060 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4061 }
4062}
4063
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004064/// areCommonBaseCompatible - Returns common base class of the two classes if
4065/// one found. Note that this is O'2 algorithm. But it will be called as the
4066/// last type comparison in a ?-exp of ObjC pointer types before a
4067/// warning is issued. So, its invokation is extremely rare.
4068QualType ASTContext::areCommonBaseCompatible(
4069 const ObjCObjectPointerType *LHSOPT,
4070 const ObjCObjectPointerType *RHSOPT) {
4071 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4072 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4073 if (!LHS || !RHS)
4074 return QualType();
4075
4076 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4077 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4078 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004079 if (canAssignObjCInterfaces(LHS, RHS)) {
4080 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4081 getIntersectionOfProtocols(*this,
4082 LHSOPT, RHSOPT, IntersectionOfProtocols);
4083 if (IntersectionOfProtocols.empty())
4084 LHSTy = getObjCObjectPointerType(LHSTy);
4085 else
4086 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4087 IntersectionOfProtocols.size());
4088 return LHSTy;
4089 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004090 }
4091
4092 return QualType();
4093}
4094
Eli Friedman3d815e72008-08-22 00:56:42 +00004095bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4096 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004097 // Verify that the base decls are compatible: the RHS must be a subclass of
4098 // the LHS.
4099 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4100 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004101
Chris Lattner6ac46a42008-04-07 06:51:04 +00004102 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4103 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004104 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004105 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Chris Lattner6ac46a42008-04-07 06:51:04 +00004107 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4108 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004109 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004110 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004112 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4113 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004114 LHSPI != LHSPE; LHSPI++) {
4115 bool RHSImplementsProtocol = false;
4116
4117 // If the RHS doesn't implement the protocol on the left, the types
4118 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004119 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004120 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004121 RHSPI != RHSPE; RHSPI++) {
4122 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004123 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004124 break;
4125 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004126 }
4127 // FIXME: For better diagnostics, consider passing back the protocol name.
4128 if (!RHSImplementsProtocol)
4129 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004130 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004131 // The RHS implements all protocols listed on the LHS.
4132 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004133}
4134
Steve Naroff389bf462009-02-12 17:52:19 +00004135bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4136 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004137 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4138 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Steve Naroff14108da2009-07-10 23:34:53 +00004140 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004141 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004142
4143 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4144 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004145}
4146
Mike Stump1eb44332009-09-09 15:08:12 +00004147/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004148/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004149/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004150/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004151bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4152 return !mergeTypes(LHS, RHS).isNull();
4153}
4154
4155QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004156 const FunctionType *lbase = lhs->getAs<FunctionType>();
4157 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004158 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4159 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004160 bool allLTypes = true;
4161 bool allRTypes = true;
4162
4163 // Check return type
4164 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4165 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004166 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4167 allLTypes = false;
4168 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4169 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004170 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004171 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4172 if (NoReturn != lbase->getNoReturnAttr())
4173 allLTypes = false;
4174 if (NoReturn != rbase->getNoReturnAttr())
4175 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004176
Eli Friedman3d815e72008-08-22 00:56:42 +00004177 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004178 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4179 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004180 unsigned lproto_nargs = lproto->getNumArgs();
4181 unsigned rproto_nargs = rproto->getNumArgs();
4182
4183 // Compatible functions must have the same number of arguments
4184 if (lproto_nargs != rproto_nargs)
4185 return QualType();
4186
4187 // Variadic and non-variadic functions aren't compatible
4188 if (lproto->isVariadic() != rproto->isVariadic())
4189 return QualType();
4190
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004191 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4192 return QualType();
4193
Eli Friedman3d815e72008-08-22 00:56:42 +00004194 // Check argument compatibility
4195 llvm::SmallVector<QualType, 10> types;
4196 for (unsigned i = 0; i < lproto_nargs; i++) {
4197 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4198 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4199 QualType argtype = mergeTypes(largtype, rargtype);
4200 if (argtype.isNull()) return QualType();
4201 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004202 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4203 allLTypes = false;
4204 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4205 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004206 }
4207 if (allLTypes) return lhs;
4208 if (allRTypes) return rhs;
4209 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004210 lproto->isVariadic(), lproto->getTypeQuals(),
4211 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004212 }
4213
4214 if (lproto) allRTypes = false;
4215 if (rproto) allLTypes = false;
4216
Douglas Gregor72564e72009-02-26 23:50:07 +00004217 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004218 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004219 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004220 if (proto->isVariadic()) return QualType();
4221 // Check that the types are compatible with the types that
4222 // would result from default argument promotions (C99 6.7.5.3p15).
4223 // The only types actually affected are promotable integer
4224 // types and floats, which would be passed as a different
4225 // type depending on whether the prototype is visible.
4226 unsigned proto_nargs = proto->getNumArgs();
4227 for (unsigned i = 0; i < proto_nargs; ++i) {
4228 QualType argTy = proto->getArgType(i);
4229 if (argTy->isPromotableIntegerType() ||
4230 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4231 return QualType();
4232 }
4233
4234 if (allLTypes) return lhs;
4235 if (allRTypes) return rhs;
4236 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004237 proto->getNumArgs(), proto->isVariadic(),
4238 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004239 }
4240
4241 if (allLTypes) return lhs;
4242 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004243 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004244}
4245
4246QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004247 // C++ [expr]: If an expression initially has the type "reference to T", the
4248 // type is adjusted to "T" prior to any further analysis, the expression
4249 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004250 // expression is an lvalue unless the reference is an rvalue reference and
4251 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004252 // FIXME: C++ shouldn't be going through here! The rules are different
4253 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004254 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4255 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004256 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004257 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004258 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004259 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004260
Eli Friedman3d815e72008-08-22 00:56:42 +00004261 QualType LHSCan = getCanonicalType(LHS),
4262 RHSCan = getCanonicalType(RHS);
4263
4264 // If two types are identical, they are compatible.
4265 if (LHSCan == RHSCan)
4266 return LHS;
4267
John McCall0953e762009-09-24 19:53:00 +00004268 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004269 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4270 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004271 if (LQuals != RQuals) {
4272 // If any of these qualifiers are different, we have a type
4273 // mismatch.
4274 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4275 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4276 return QualType();
4277
4278 // Exactly one GC qualifier difference is allowed: __strong is
4279 // okay if the other type has no GC qualifier but is an Objective
4280 // C object pointer (i.e. implicitly strong by default). We fix
4281 // this by pretending that the unqualified type was actually
4282 // qualified __strong.
4283 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4284 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4285 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4286
4287 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4288 return QualType();
4289
4290 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4291 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4292 }
4293 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4294 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4295 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004296 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004297 }
4298
4299 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004300
Eli Friedman852d63b2009-06-01 01:22:52 +00004301 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4302 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004303
Chris Lattner1adb8832008-01-14 05:45:46 +00004304 // We want to consider the two function types to be the same for these
4305 // comparisons, just force one to the other.
4306 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4307 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004308
4309 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004310 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4311 LHSClass = Type::ConstantArray;
4312 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4313 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004314
Nate Begeman213541a2008-04-18 23:10:10 +00004315 // Canonicalize ExtVector -> Vector.
4316 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4317 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004318
Chris Lattnera36a61f2008-04-07 05:43:21 +00004319 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004320 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004321 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004322 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004323 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004324 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4325 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004326 }
John McCall183700f2009-09-21 23:43:11 +00004327 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004328 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4329 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004330 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004331
Eli Friedman3d815e72008-08-22 00:56:42 +00004332 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004333 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004334
Steve Naroff4a746782008-01-09 22:43:08 +00004335 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004336 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004337#define TYPE(Class, Base)
4338#define ABSTRACT_TYPE(Class, Base)
4339#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4340#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4341#include "clang/AST/TypeNodes.def"
4342 assert(false && "Non-canonical and dependent types shouldn't get here");
4343 return QualType();
4344
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004345 case Type::LValueReference:
4346 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004347 case Type::MemberPointer:
4348 assert(false && "C++ should never be in mergeTypes");
4349 return QualType();
4350
4351 case Type::IncompleteArray:
4352 case Type::VariableArray:
4353 case Type::FunctionProto:
4354 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004355 assert(false && "Types are eliminated above");
4356 return QualType();
4357
Chris Lattner1adb8832008-01-14 05:45:46 +00004358 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004359 {
4360 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004361 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4362 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004363 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4364 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004365 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004366 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004367 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004368 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004369 return getPointerType(ResultType);
4370 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004371 case Type::BlockPointer:
4372 {
4373 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004374 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4375 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004376 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4377 if (ResultType.isNull()) return QualType();
4378 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4379 return LHS;
4380 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4381 return RHS;
4382 return getBlockPointerType(ResultType);
4383 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004384 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004385 {
4386 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4387 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4388 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4389 return QualType();
4390
4391 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4392 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4393 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4394 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004395 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4396 return LHS;
4397 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4398 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004399 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4400 ArrayType::ArraySizeModifier(), 0);
4401 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4402 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004403 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4404 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004405 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4406 return LHS;
4407 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4408 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004409 if (LVAT) {
4410 // FIXME: This isn't correct! But tricky to implement because
4411 // the array's size has to be the size of LHS, but the type
4412 // has to be different.
4413 return LHS;
4414 }
4415 if (RVAT) {
4416 // FIXME: This isn't correct! But tricky to implement because
4417 // the array's size has to be the size of RHS, but the type
4418 // has to be different.
4419 return RHS;
4420 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004421 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4422 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004423 return getIncompleteArrayType(ResultType,
4424 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004425 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004426 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004427 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004428 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004429 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004430 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004431 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004432 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004433 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004434 case Type::Complex:
4435 // Distinct complex types are incompatible.
4436 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004437 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004438 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004439 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004440 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004441 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004442 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004443 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004444 // FIXME: This should be type compatibility, e.g. whether
4445 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004446 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4447 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004448 if (LHSIface && RHSIface &&
4449 canAssignObjCInterfaces(LHSIface, RHSIface))
4450 return LHS;
4451
Eli Friedman3d815e72008-08-22 00:56:42 +00004452 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004453 }
Steve Naroff14108da2009-07-10 23:34:53 +00004454 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004455 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4456 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004457 return LHS;
4458
Steve Naroffbc76dd02008-12-10 22:14:21 +00004459 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004460 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004461 case Type::FixedWidthInt:
4462 // Distinct fixed-width integers are not compatible.
4463 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004464 case Type::TemplateSpecialization:
4465 assert(false && "Dependent types have no size");
4466 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004467 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004468
4469 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004470}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004471
Chris Lattner5426bf62008-04-07 07:01:58 +00004472//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004473// Integer Predicates
4474//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004475
Eli Friedmanad74a752008-06-28 06:23:08 +00004476unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004477 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004478 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004479 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004480 return FWIT->getWidth();
4481 }
4482 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004483 return (unsigned)getTypeSize(T);
4484}
4485
4486QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4487 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004488
4489 // Turn <4 x signed int> -> <4 x unsigned int>
4490 if (const VectorType *VTy = T->getAs<VectorType>())
4491 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4492 VTy->getNumElements());
4493
4494 // For enums, we return the unsigned version of the base type.
4495 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004496 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004497
4498 const BuiltinType *BTy = T->getAs<BuiltinType>();
4499 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004500 switch (BTy->getKind()) {
4501 case BuiltinType::Char_S:
4502 case BuiltinType::SChar:
4503 return UnsignedCharTy;
4504 case BuiltinType::Short:
4505 return UnsignedShortTy;
4506 case BuiltinType::Int:
4507 return UnsignedIntTy;
4508 case BuiltinType::Long:
4509 return UnsignedLongTy;
4510 case BuiltinType::LongLong:
4511 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004512 case BuiltinType::Int128:
4513 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004514 default:
4515 assert(0 && "Unexpected signed integer type");
4516 return QualType();
4517 }
4518}
4519
Douglas Gregor2cf26342009-04-09 22:27:44 +00004520ExternalASTSource::~ExternalASTSource() { }
4521
4522void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004523
4524
4525//===----------------------------------------------------------------------===//
4526// Builtin Type Computation
4527//===----------------------------------------------------------------------===//
4528
4529/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4530/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004531static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004532 ASTContext::GetBuiltinTypeError &Error,
4533 bool AllowTypeModifiers = true) {
4534 // Modifiers.
4535 int HowLong = 0;
4536 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004537
Chris Lattner86df27b2009-06-14 00:45:47 +00004538 // Read the modifiers first.
4539 bool Done = false;
4540 while (!Done) {
4541 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004542 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004543 case 'S':
4544 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4545 assert(!Signed && "Can't use 'S' modifier multiple times!");
4546 Signed = true;
4547 break;
4548 case 'U':
4549 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4550 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4551 Unsigned = true;
4552 break;
4553 case 'L':
4554 assert(HowLong <= 2 && "Can't have LLLL modifier");
4555 ++HowLong;
4556 break;
4557 }
4558 }
4559
4560 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004561
Chris Lattner86df27b2009-06-14 00:45:47 +00004562 // Read the base type.
4563 switch (*Str++) {
4564 default: assert(0 && "Unknown builtin type letter!");
4565 case 'v':
4566 assert(HowLong == 0 && !Signed && !Unsigned &&
4567 "Bad modifiers used with 'v'!");
4568 Type = Context.VoidTy;
4569 break;
4570 case 'f':
4571 assert(HowLong == 0 && !Signed && !Unsigned &&
4572 "Bad modifiers used with 'f'!");
4573 Type = Context.FloatTy;
4574 break;
4575 case 'd':
4576 assert(HowLong < 2 && !Signed && !Unsigned &&
4577 "Bad modifiers used with 'd'!");
4578 if (HowLong)
4579 Type = Context.LongDoubleTy;
4580 else
4581 Type = Context.DoubleTy;
4582 break;
4583 case 's':
4584 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4585 if (Unsigned)
4586 Type = Context.UnsignedShortTy;
4587 else
4588 Type = Context.ShortTy;
4589 break;
4590 case 'i':
4591 if (HowLong == 3)
4592 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4593 else if (HowLong == 2)
4594 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4595 else if (HowLong == 1)
4596 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4597 else
4598 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4599 break;
4600 case 'c':
4601 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4602 if (Signed)
4603 Type = Context.SignedCharTy;
4604 else if (Unsigned)
4605 Type = Context.UnsignedCharTy;
4606 else
4607 Type = Context.CharTy;
4608 break;
4609 case 'b': // boolean
4610 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4611 Type = Context.BoolTy;
4612 break;
4613 case 'z': // size_t.
4614 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4615 Type = Context.getSizeType();
4616 break;
4617 case 'F':
4618 Type = Context.getCFConstantStringType();
4619 break;
4620 case 'a':
4621 Type = Context.getBuiltinVaListType();
4622 assert(!Type.isNull() && "builtin va list type not initialized!");
4623 break;
4624 case 'A':
4625 // This is a "reference" to a va_list; however, what exactly
4626 // this means depends on how va_list is defined. There are two
4627 // different kinds of va_list: ones passed by value, and ones
4628 // passed by reference. An example of a by-value va_list is
4629 // x86, where va_list is a char*. An example of by-ref va_list
4630 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4631 // we want this argument to be a char*&; for x86-64, we want
4632 // it to be a __va_list_tag*.
4633 Type = Context.getBuiltinVaListType();
4634 assert(!Type.isNull() && "builtin va list type not initialized!");
4635 if (Type->isArrayType()) {
4636 Type = Context.getArrayDecayedType(Type);
4637 } else {
4638 Type = Context.getLValueReferenceType(Type);
4639 }
4640 break;
4641 case 'V': {
4642 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004643 unsigned NumElements = strtoul(Str, &End, 10);
4644 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004645
Chris Lattner86df27b2009-06-14 00:45:47 +00004646 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004647
Chris Lattner86df27b2009-06-14 00:45:47 +00004648 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4649 Type = Context.getVectorType(ElementType, NumElements);
4650 break;
4651 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004652 case 'X': {
4653 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4654 Type = Context.getComplexType(ElementType);
4655 break;
4656 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004657 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004658 Type = Context.getFILEType();
4659 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004660 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004661 return QualType();
4662 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004663 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004664 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004665 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004666 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004667 else
4668 Type = Context.getjmp_bufType();
4669
Mike Stumpfd612db2009-07-28 23:47:15 +00004670 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004671 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004672 return QualType();
4673 }
4674 break;
Mike Stump782fa302009-07-28 02:25:19 +00004675 }
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Chris Lattner86df27b2009-06-14 00:45:47 +00004677 if (!AllowTypeModifiers)
4678 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004679
Chris Lattner86df27b2009-06-14 00:45:47 +00004680 Done = false;
4681 while (!Done) {
4682 switch (*Str++) {
4683 default: Done = true; --Str; break;
4684 case '*':
4685 Type = Context.getPointerType(Type);
4686 break;
4687 case '&':
4688 Type = Context.getLValueReferenceType(Type);
4689 break;
4690 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4691 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004692 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004693 break;
4694 }
4695 }
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Chris Lattner86df27b2009-06-14 00:45:47 +00004697 return Type;
4698}
4699
4700/// GetBuiltinType - Return the type for the specified builtin.
4701QualType ASTContext::GetBuiltinType(unsigned id,
4702 GetBuiltinTypeError &Error) {
4703 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Chris Lattner86df27b2009-06-14 00:45:47 +00004705 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Chris Lattner86df27b2009-06-14 00:45:47 +00004707 Error = GE_None;
4708 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4709 if (Error != GE_None)
4710 return QualType();
4711 while (TypeStr[0] && TypeStr[0] != '.') {
4712 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4713 if (Error != GE_None)
4714 return QualType();
4715
4716 // Do array -> pointer decay. The builtin should use the decayed type.
4717 if (Ty->isArrayType())
4718 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004719
Chris Lattner86df27b2009-06-14 00:45:47 +00004720 ArgTypes.push_back(Ty);
4721 }
4722
4723 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4724 "'.' should only occur at end of builtin type list!");
4725
4726 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4727 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4728 return getFunctionNoProtoType(ResType);
4729 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4730 TypeStr[0] == '.', 0);
4731}
Eli Friedmana95d7572009-08-19 07:44:53 +00004732
4733QualType
4734ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4735 // Perform the usual unary conversions. We do this early so that
4736 // integral promotions to "int" can allow us to exit early, in the
4737 // lhs == rhs check. Also, for conversion purposes, we ignore any
4738 // qualifiers. For example, "const float" and "float" are
4739 // equivalent.
4740 if (lhs->isPromotableIntegerType())
4741 lhs = getPromotedIntegerType(lhs);
4742 else
4743 lhs = lhs.getUnqualifiedType();
4744 if (rhs->isPromotableIntegerType())
4745 rhs = getPromotedIntegerType(rhs);
4746 else
4747 rhs = rhs.getUnqualifiedType();
4748
4749 // If both types are identical, no conversion is needed.
4750 if (lhs == rhs)
4751 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Eli Friedmana95d7572009-08-19 07:44:53 +00004753 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4754 // The caller can deal with this (e.g. pointer + int).
4755 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4756 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004757
4758 // At this point, we have two different arithmetic types.
4759
Eli Friedmana95d7572009-08-19 07:44:53 +00004760 // Handle complex types first (C99 6.3.1.8p1).
4761 if (lhs->isComplexType() || rhs->isComplexType()) {
4762 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004763 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004764 // convert the rhs to the lhs complex type.
4765 return lhs;
4766 }
Mike Stump1eb44332009-09-09 15:08:12 +00004767 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004768 // convert the lhs to the rhs complex type.
4769 return rhs;
4770 }
4771 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004772 // When both operands are complex, the shorter operand is converted to the
4773 // type of the longer, and that is the type of the result. This corresponds
4774 // to what is done when combining two real floating-point operands.
4775 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004776 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004777 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004778 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004779 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004780 // "double _Complex" is promoted to "long double _Complex".
4781 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004782
4783 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004784 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004785 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004786 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004787 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004788 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4789 // domains match. This is a requirement for our implementation, C99
4790 // does not require this promotion.
4791 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4792 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4793 return rhs;
4794 } else { // handle "_Complex double, double".
4795 return lhs;
4796 }
4797 }
4798 return lhs; // The domain/size match exactly.
4799 }
4800 // Now handle "real" floating types (i.e. float, double, long double).
4801 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4802 // if we have an integer operand, the result is the real floating type.
4803 if (rhs->isIntegerType()) {
4804 // convert rhs to the lhs floating point type.
4805 return lhs;
4806 }
4807 if (rhs->isComplexIntegerType()) {
4808 // convert rhs to the complex floating point type.
4809 return getComplexType(lhs);
4810 }
4811 if (lhs->isIntegerType()) {
4812 // convert lhs to the rhs floating point type.
4813 return rhs;
4814 }
Mike Stump1eb44332009-09-09 15:08:12 +00004815 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004816 // convert lhs to the complex floating point type.
4817 return getComplexType(rhs);
4818 }
4819 // We have two real floating types, float/complex combos were handled above.
4820 // Convert the smaller operand to the bigger result.
4821 int result = getFloatingTypeOrder(lhs, rhs);
4822 if (result > 0) // convert the rhs
4823 return lhs;
4824 assert(result < 0 && "illegal float comparison");
4825 return rhs; // convert the lhs
4826 }
4827 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4828 // Handle GCC complex int extension.
4829 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4830 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4831
4832 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004833 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004834 rhsComplexInt->getElementType()) >= 0)
4835 return lhs; // convert the rhs
4836 return rhs;
4837 } else if (lhsComplexInt && rhs->isIntegerType()) {
4838 // convert the rhs to the lhs complex type.
4839 return lhs;
4840 } else if (rhsComplexInt && lhs->isIntegerType()) {
4841 // convert the lhs to the rhs complex type.
4842 return rhs;
4843 }
4844 }
4845 // Finally, we have two differing integer types.
4846 // The rules for this case are in C99 6.3.1.8
4847 int compare = getIntegerTypeOrder(lhs, rhs);
4848 bool lhsSigned = lhs->isSignedIntegerType(),
4849 rhsSigned = rhs->isSignedIntegerType();
4850 QualType destType;
4851 if (lhsSigned == rhsSigned) {
4852 // Same signedness; use the higher-ranked type
4853 destType = compare >= 0 ? lhs : rhs;
4854 } else if (compare != (lhsSigned ? 1 : -1)) {
4855 // The unsigned type has greater than or equal rank to the
4856 // signed type, so use the unsigned type
4857 destType = lhsSigned ? rhs : lhs;
4858 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4859 // The two types are different widths; if we are here, that
4860 // means the signed type is larger than the unsigned type, so
4861 // use the signed type.
4862 destType = lhsSigned ? lhs : rhs;
4863 } else {
4864 // The signed type is higher-ranked than the unsigned type,
4865 // but isn't actually any bigger (like unsigned int and long
4866 // on most 32-bit systems). Use the unsigned type corresponding
4867 // to the signed type.
4868 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4869 }
4870 return destType;
4871}