blob: aced8c7623f6c1ef815e9d6c1d5c00ccb0763df5 [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>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000524 Align = std::max(Align, AA->getAlignment());
525
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>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000764 Align = Aligned->getAlignment();
765 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
766 } else
767 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000768 break;
Chris Lattner71763312008-04-06 22:05:18 +0000769 }
Douglas Gregor18857642009-04-30 17:32:17 +0000770
771 case Type::TypeOfExpr:
772 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
773 .getTypePtr());
774
775 case Type::TypeOf:
776 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
777
Anders Carlsson395b4752009-06-24 19:06:50 +0000778 case Type::Decltype:
779 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
780 .getTypePtr());
781
Douglas Gregor18857642009-04-30 17:32:17 +0000782 case Type::QualifiedName:
783 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregor18857642009-04-30 17:32:17 +0000785 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000786 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000787 "Cannot request the size of a dependent type");
788 // FIXME: this is likely to be wrong once we support template
789 // aliases, since a template alias could refer to a typedef that
790 // has an __aligned__ attribute on it.
791 return getTypeInfo(getCanonicalType(T));
792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Chris Lattner464175b2007-07-18 17:52:12 +0000794 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000795 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000796}
797
Chris Lattner34ebde42009-01-27 18:08:34 +0000798/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
799/// type for the current target in bits. This can be different than the ABI
800/// alignment in cases where it is beneficial for performance to overalign
801/// a data type.
802unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
803 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000804
805 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000806 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000807 T = CT->getElementType().getTypePtr();
808 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
809 T->isSpecificBuiltinType(BuiltinType::LongLong))
810 return std::max(ABIAlign, (unsigned)getTypeSize(T));
811
Chris Lattner34ebde42009-01-27 18:08:34 +0000812 return ABIAlign;
813}
814
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000815static void CollectLocalObjCIvars(ASTContext *Ctx,
816 const ObjCInterfaceDecl *OI,
817 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000818 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
819 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000820 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000821 if (!IVDecl->isInvalidDecl())
822 Fields.push_back(cast<FieldDecl>(IVDecl));
823 }
824}
825
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000826void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
827 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
828 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
829 CollectObjCIvars(SuperClass, Fields);
830 CollectLocalObjCIvars(this, OI, Fields);
831}
832
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000833/// ShallowCollectObjCIvars -
834/// Collect all ivars, including those synthesized, in the current class.
835///
836void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
837 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
838 bool CollectSynthesized) {
839 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
840 E = OI->ivar_end(); I != E; ++I) {
841 Ivars.push_back(*I);
842 }
843 if (CollectSynthesized)
844 CollectSynthesizedIvars(OI, Ivars);
845}
846
Fariborz Jahanian98200742009-05-12 18:14:29 +0000847void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
848 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000849 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
850 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000851 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
852 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Fariborz Jahanian98200742009-05-12 18:14:29 +0000854 // Also look into nested protocols.
855 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
856 E = PD->protocol_end(); P != E; ++P)
857 CollectProtocolSynthesizedIvars(*P, Ivars);
858}
859
860/// CollectSynthesizedIvars -
861/// This routine collect synthesized ivars for the designated class.
862///
863void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
864 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000865 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
866 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000867 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
868 Ivars.push_back(Ivar);
869 }
870 // Also look into interface's protocol list for properties declared
871 // in the protocol and whose ivars are synthesized.
872 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
873 PE = OI->protocol_end(); P != PE; ++P) {
874 ObjCProtocolDecl *PD = (*P);
875 CollectProtocolSynthesizedIvars(PD, Ivars);
876 }
877}
878
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000879/// CollectInheritedProtocols - Collect all protocols in current class and
880/// those inherited by it.
881void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
882 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
883 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
884 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
885 PE = OI->protocol_end(); P != PE; ++P) {
886 ObjCProtocolDecl *Proto = (*P);
887 Protocols.push_back(Proto);
888 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
889 PE = Proto->protocol_end(); P != PE; ++P)
890 CollectInheritedProtocols(*P, Protocols);
891 }
892
893 // Categories of this Interface.
894 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
895 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
896 CollectInheritedProtocols(CDeclChain, Protocols);
897 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
898 while (SD) {
899 CollectInheritedProtocols(SD, Protocols);
900 SD = SD->getSuperClass();
901 }
902 return;
903 }
904 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
905 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
906 PE = OC->protocol_end(); P != PE; ++P) {
907 ObjCProtocolDecl *Proto = (*P);
908 Protocols.push_back(Proto);
909 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
910 PE = Proto->protocol_end(); P != PE; ++P)
911 CollectInheritedProtocols(*P, Protocols);
912 }
913 return;
914 }
915 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
916 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
917 PE = OP->protocol_end(); P != PE; ++P) {
918 ObjCProtocolDecl *Proto = (*P);
919 Protocols.push_back(Proto);
920 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
921 PE = Proto->protocol_end(); P != PE; ++P)
922 CollectInheritedProtocols(*P, Protocols);
923 }
924 return;
925 }
926}
927
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000928unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
929 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000930 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
931 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000932 if ((*I)->getPropertyIvarDecl())
933 ++count;
934
935 // Also look into nested protocols.
936 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
937 E = PD->protocol_end(); P != E; ++P)
938 count += CountProtocolSynthesizedIvars(*P);
939 return count;
940}
941
Mike Stump1eb44332009-09-09 15:08:12 +0000942unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000943 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000944 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
945 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000946 if ((*I)->getPropertyIvarDecl())
947 ++count;
948 }
949 // Also look into interface's protocol list for properties declared
950 // in the protocol and whose ivars are synthesized.
951 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
952 PE = OI->protocol_end(); P != PE; ++P) {
953 ObjCProtocolDecl *PD = (*P);
954 count += CountProtocolSynthesizedIvars(PD);
955 }
956 return count;
957}
958
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000959/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
960ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
961 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
962 I = ObjCImpls.find(D);
963 if (I != ObjCImpls.end())
964 return cast<ObjCImplementationDecl>(I->second);
965 return 0;
966}
967/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
968ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
969 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
970 I = ObjCImpls.find(D);
971 if (I != ObjCImpls.end())
972 return cast<ObjCCategoryImplDecl>(I->second);
973 return 0;
974}
975
976/// \brief Set the implementation of ObjCInterfaceDecl.
977void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
978 ObjCImplementationDecl *ImplD) {
979 assert(IFaceD && ImplD && "Passed null params");
980 ObjCImpls[IFaceD] = ImplD;
981}
982/// \brief Set the implementation of ObjCCategoryDecl.
983void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
984 ObjCCategoryImplDecl *ImplD) {
985 assert(CatD && ImplD && "Passed null params");
986 ObjCImpls[CatD] = ImplD;
987}
988
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000989/// \brief Allocate an uninitialized DeclaratorInfo.
990///
991/// The caller should initialize the memory held by DeclaratorInfo using
992/// the TypeLoc wrappers.
993///
994/// \param T the type that will be the basis for type source info. This type
995/// should refer to how the declarator was written in source code, not to
996/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +0000997DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
998 unsigned DataSize) {
999 if (!DataSize)
1000 DataSize = TypeLoc::getFullDataSizeForType(T);
1001 else
1002 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1003 "incorrect data size provided to CreateDeclaratorInfo!");
1004
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001005 DeclaratorInfo *DInfo =
1006 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1007 new (DInfo) DeclaratorInfo(T);
1008 return DInfo;
1009}
1010
John McCalla4eb74d2009-10-23 21:14:09 +00001011DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1012 SourceLocation L) {
1013 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1014 DI->getTypeLoc().initialize(L);
1015 return DI;
1016}
1017
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001018/// getInterfaceLayoutImpl - Get or compute information about the
1019/// layout of the given interface.
1020///
1021/// \param Impl - If given, also include the layout of the interface's
1022/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001023const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001024ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1025 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001026 assert(!D->isForwardDecl() && "Invalid interface decl!");
1027
Devang Patel44a3dde2008-06-04 21:54:36 +00001028 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001029 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001030 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1031 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1032 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001033
Daniel Dunbar453addb2009-05-03 11:16:44 +00001034 // Add in synthesized ivar count if laying out an implementation.
1035 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001036 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001037 unsigned SynthCount = CountSynthesizedIvars(D);
1038 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001039 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001040 // entry. Note we can't cache this because we simply free all
1041 // entries later; however we shouldn't look up implementations
1042 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001043 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001044 return getObjCLayout(D, 0);
1045 }
1046
Mike Stump1eb44332009-09-09 15:08:12 +00001047 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001048 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1049 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Devang Patel44a3dde2008-06-04 21:54:36 +00001051 return *NewEntry;
1052}
1053
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001054const ASTRecordLayout &
1055ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1056 return getObjCLayout(D, 0);
1057}
1058
1059const ASTRecordLayout &
1060ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1061 return getObjCLayout(D->getClassInterface(), D);
1062}
1063
Devang Patel88a981b2007-11-01 19:11:01 +00001064/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001065/// specified record (struct/union/class), which indicates its size and field
1066/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001067const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001068 D = D->getDefinition(*this);
1069 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001070
Chris Lattner464175b2007-07-18 17:52:12 +00001071 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001072 // Note that we can't save a reference to the entry because this function
1073 // is recursive.
1074 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001075 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001076
Mike Stump1eb44332009-09-09 15:08:12 +00001077 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001078 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001079 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Chris Lattner5d2a6302007-07-18 18:26:58 +00001081 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001082}
1083
Chris Lattnera7674d82007-07-13 22:13:22 +00001084//===----------------------------------------------------------------------===//
1085// Type creation/memoization methods
1086//===----------------------------------------------------------------------===//
1087
John McCall0953e762009-09-24 19:53:00 +00001088QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1089 unsigned Fast = Quals.getFastQualifiers();
1090 Quals.removeFastQualifiers();
1091
1092 // Check if we've already instantiated this type.
1093 llvm::FoldingSetNodeID ID;
1094 ExtQuals::Profile(ID, TypeNode, Quals);
1095 void *InsertPos = 0;
1096 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1097 assert(EQ->getQualifiers() == Quals);
1098 QualType T = QualType(EQ, Fast);
1099 return T;
1100 }
1101
John McCall6b304a02009-09-24 23:30:46 +00001102 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001103 ExtQualNodes.InsertNode(New, InsertPos);
1104 QualType T = QualType(New, Fast);
1105 return T;
1106}
1107
1108QualType ASTContext::getVolatileType(QualType T) {
1109 QualType CanT = getCanonicalType(T);
1110 if (CanT.isVolatileQualified()) return T;
1111
1112 QualifierCollector Quals;
1113 const Type *TypeNode = Quals.strip(T);
1114 Quals.addVolatile();
1115
1116 return getExtQualType(TypeNode, Quals);
1117}
1118
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001119QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001120 QualType CanT = getCanonicalType(T);
1121 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001122 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001123
John McCall0953e762009-09-24 19:53:00 +00001124 // If we are composing extended qualifiers together, merge together
1125 // into one ExtQuals node.
1126 QualifierCollector Quals;
1127 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
John McCall0953e762009-09-24 19:53:00 +00001129 // If this type already has an address space specified, it cannot get
1130 // another one.
1131 assert(!Quals.hasAddressSpace() &&
1132 "Type cannot be in multiple addr spaces!");
1133 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001134
John McCall0953e762009-09-24 19:53:00 +00001135 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001136}
1137
Chris Lattnerb7d25532009-02-18 22:53:11 +00001138QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001139 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001140 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001141 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001142 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001144 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001145 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001146 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001147 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1148 return getPointerType(ResultType);
1149 }
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
John McCall0953e762009-09-24 19:53:00 +00001152 // If we are composing extended qualifiers together, merge together
1153 // into one ExtQuals node.
1154 QualifierCollector Quals;
1155 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
John McCall0953e762009-09-24 19:53:00 +00001157 // If this type already has an ObjCGC specified, it cannot get
1158 // another one.
1159 assert(!Quals.hasObjCGCAttr() &&
1160 "Type cannot have multiple ObjCGCs!");
1161 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
John McCall0953e762009-09-24 19:53:00 +00001163 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001164}
Chris Lattnera7674d82007-07-13 22:13:22 +00001165
Mike Stump24556362009-07-25 21:26:53 +00001166QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001167 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001168 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001169 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001170 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001171 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001172 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001173 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001174 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001175 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001176 } else {
1177 assert (T->isFunctionType()
1178 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001180 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1181 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001182 } else {
1183 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1184 ResultType
1185 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1186 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1187 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1188 F->getNumExceptions(), F->exception_begin(), true);
1189 }
Mike Stump24556362009-07-25 21:26:53 +00001190 }
John McCall0953e762009-09-24 19:53:00 +00001191
Douglas Gregora4923eb2009-11-16 21:35:15 +00001192 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001193}
1194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195/// getComplexType - Return the uniqued reference to the type for a complex
1196/// number with the specified element type.
1197QualType ASTContext::getComplexType(QualType T) {
1198 // Unique pointers, to guarantee there is only one pointer of a particular
1199 // structure.
1200 llvm::FoldingSetNodeID ID;
1201 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 void *InsertPos = 0;
1204 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1205 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 // If the pointee type isn't canonical, this won't be a canonical type either,
1208 // so fill in the canonical type field.
1209 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001210 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001211 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 // Get the new insert position for the node we care about.
1214 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001215 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 }
John McCall6b304a02009-09-24 23:30:46 +00001217 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 Types.push_back(New);
1219 ComplexTypes.InsertNode(New, InsertPos);
1220 return QualType(New, 0);
1221}
1222
Eli Friedmanf98aba32009-02-13 02:31:07 +00001223QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1224 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1225 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1226 FixedWidthIntType *&Entry = Map[Width];
1227 if (!Entry)
1228 Entry = new FixedWidthIntType(Width, Signed);
1229 return QualType(Entry, 0);
1230}
Reid Spencer5f016e22007-07-11 17:01:13 +00001231
1232/// getPointerType - Return the uniqued reference to the type for a pointer to
1233/// the specified type.
1234QualType ASTContext::getPointerType(QualType T) {
1235 // Unique pointers, to guarantee there is only one pointer of a particular
1236 // structure.
1237 llvm::FoldingSetNodeID ID;
1238 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 void *InsertPos = 0;
1241 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1242 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 // If the pointee type isn't canonical, this won't be a canonical type either,
1245 // so fill in the canonical type field.
1246 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001247 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001248 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 // Get the new insert position for the node we care about.
1251 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001252 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 }
John McCall6b304a02009-09-24 23:30:46 +00001254 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 Types.push_back(New);
1256 PointerTypes.InsertNode(New, InsertPos);
1257 return QualType(New, 0);
1258}
1259
Mike Stump1eb44332009-09-09 15:08:12 +00001260/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001261/// a pointer to the specified block.
1262QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001263 assert(T->isFunctionType() && "block of function types only");
1264 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001265 // structure.
1266 llvm::FoldingSetNodeID ID;
1267 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Steve Naroff5618bd42008-08-27 16:04:49 +00001269 void *InsertPos = 0;
1270 if (BlockPointerType *PT =
1271 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1272 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
1274 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001275 // type either so fill in the canonical type field.
1276 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001277 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001278 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Steve Naroff5618bd42008-08-27 16:04:49 +00001280 // Get the new insert position for the node we care about.
1281 BlockPointerType *NewIP =
1282 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001283 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001284 }
John McCall6b304a02009-09-24 23:30:46 +00001285 BlockPointerType *New
1286 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001287 Types.push_back(New);
1288 BlockPointerTypes.InsertNode(New, InsertPos);
1289 return QualType(New, 0);
1290}
1291
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001292/// getLValueReferenceType - Return the uniqued reference to the type for an
1293/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001294QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 // Unique pointers, to guarantee there is only one pointer of a particular
1296 // structure.
1297 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001298 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
1300 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001301 if (LValueReferenceType *RT =
1302 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001304
John McCall54e14c42009-10-22 22:37:11 +00001305 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // If the referencee type isn't canonical, this won't be a canonical type
1308 // either, so fill in the canonical type field.
1309 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001310 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1311 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1312 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001313
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315 LValueReferenceType *NewIP =
1316 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001317 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 }
1319
John McCall6b304a02009-09-24 23:30:46 +00001320 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001321 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1322 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001324 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001325
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001326 return QualType(New, 0);
1327}
1328
1329/// getRValueReferenceType - Return the uniqued reference to the type for an
1330/// rvalue reference to the specified type.
1331QualType ASTContext::getRValueReferenceType(QualType T) {
1332 // Unique pointers, to guarantee there is only one pointer of a particular
1333 // structure.
1334 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001335 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001336
1337 void *InsertPos = 0;
1338 if (RValueReferenceType *RT =
1339 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1340 return QualType(RT, 0);
1341
John McCall54e14c42009-10-22 22:37:11 +00001342 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1343
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001344 // If the referencee type isn't canonical, this won't be a canonical type
1345 // either, so fill in the canonical type field.
1346 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001347 if (InnerRef || !T.isCanonical()) {
1348 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1349 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001350
1351 // Get the new insert position for the node we care about.
1352 RValueReferenceType *NewIP =
1353 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1354 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1355 }
1356
John McCall6b304a02009-09-24 23:30:46 +00001357 RValueReferenceType *New
1358 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001359 Types.push_back(New);
1360 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 return QualType(New, 0);
1362}
1363
Sebastian Redlf30208a2009-01-24 21:16:55 +00001364/// getMemberPointerType - Return the uniqued reference to the type for a
1365/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001366QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001367 // Unique pointers, to guarantee there is only one pointer of a particular
1368 // structure.
1369 llvm::FoldingSetNodeID ID;
1370 MemberPointerType::Profile(ID, T, Cls);
1371
1372 void *InsertPos = 0;
1373 if (MemberPointerType *PT =
1374 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1375 return QualType(PT, 0);
1376
1377 // If the pointee or class type isn't canonical, this won't be a canonical
1378 // type either, so fill in the canonical type field.
1379 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001380 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001381 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1382
1383 // Get the new insert position for the node we care about.
1384 MemberPointerType *NewIP =
1385 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1386 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1387 }
John McCall6b304a02009-09-24 23:30:46 +00001388 MemberPointerType *New
1389 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001390 Types.push_back(New);
1391 MemberPointerTypes.InsertNode(New, InsertPos);
1392 return QualType(New, 0);
1393}
1394
Mike Stump1eb44332009-09-09 15:08:12 +00001395/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001396/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001397QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001398 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001399 ArrayType::ArraySizeModifier ASM,
1400 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001401 assert((EltTy->isDependentType() ||
1402 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001403 "Constant array of VLAs is illegal!");
1404
Chris Lattner38aeec72009-05-13 04:12:56 +00001405 // Convert the array size into a canonical width matching the pointer size for
1406 // the target.
1407 llvm::APInt ArySize(ArySizeIn);
1408 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001411 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001414 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001415 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 // If the element type isn't canonical, this won't be a canonical type either,
1419 // so fill in the canonical type field.
1420 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001421 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001422 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001423 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001425 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001426 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001427 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
John McCall6b304a02009-09-24 23:30:46 +00001430 ConstantArrayType *New = new(*this,TypeAlignment)
1431 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001432 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 Types.push_back(New);
1434 return QualType(New, 0);
1435}
1436
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001437/// getVariableArrayType - Returns a non-unique reference to the type for a
1438/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001439QualType ASTContext::getVariableArrayType(QualType EltTy,
1440 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001441 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001442 unsigned EltTypeQuals,
1443 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001444 // Since we don't unique expressions, it isn't possible to unique VLA's
1445 // that have an expression provided for their size.
1446
John McCall6b304a02009-09-24 23:30:46 +00001447 VariableArrayType *New = new(*this, TypeAlignment)
1448 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001449
1450 VariableArrayTypes.push_back(New);
1451 Types.push_back(New);
1452 return QualType(New, 0);
1453}
1454
Douglas Gregor898574e2008-12-05 23:32:09 +00001455/// getDependentSizedArrayType - Returns a non-unique reference to
1456/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001457/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001458QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1459 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001460 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001461 unsigned EltTypeQuals,
1462 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001463 assert((!NumElts || NumElts->isTypeDependent() ||
1464 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001465 "Size must be type- or value-dependent!");
1466
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001467 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001468 DependentSizedArrayType *Canon = 0;
1469
1470 if (NumElts) {
1471 // Dependently-sized array types that do not have a specified
1472 // number of elements will have their sizes deduced from an
1473 // initializer.
1474 llvm::FoldingSetNodeID ID;
1475 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1476 EltTypeQuals, NumElts);
1477
1478 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1479 }
1480
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001481 DependentSizedArrayType *New;
1482 if (Canon) {
1483 // We already have a canonical version of this array type; use it as
1484 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001485 New = new (*this, TypeAlignment)
1486 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1487 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001488 } else {
1489 QualType CanonEltTy = getCanonicalType(EltTy);
1490 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001491 New = new (*this, TypeAlignment)
1492 DependentSizedArrayType(*this, EltTy, QualType(),
1493 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001494
1495 if (NumElts)
1496 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001497 } else {
1498 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1499 ASM, EltTypeQuals,
1500 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001501 New = new (*this, TypeAlignment)
1502 DependentSizedArrayType(*this, EltTy, Canon,
1503 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001504 }
1505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Douglas Gregor898574e2008-12-05 23:32:09 +00001507 Types.push_back(New);
1508 return QualType(New, 0);
1509}
1510
Eli Friedmanc5773c42008-02-15 18:16:39 +00001511QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1512 ArrayType::ArraySizeModifier ASM,
1513 unsigned EltTypeQuals) {
1514 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001515 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001516
1517 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001518 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001519 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1520 return QualType(ATP, 0);
1521
1522 // If the element type isn't canonical, this won't be a canonical type
1523 // either, so fill in the canonical type field.
1524 QualType Canonical;
1525
John McCall467b27b2009-10-22 20:10:53 +00001526 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001527 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001528 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001529
1530 // Get the new insert position for the node we care about.
1531 IncompleteArrayType *NewIP =
1532 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001533 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001534 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001535
John McCall6b304a02009-09-24 23:30:46 +00001536 IncompleteArrayType *New = new (*this, TypeAlignment)
1537 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001538
1539 IncompleteArrayTypes.InsertNode(New, InsertPos);
1540 Types.push_back(New);
1541 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001542}
1543
Steve Naroff73322922007-07-18 18:00:27 +00001544/// getVectorType - Return the unique reference to a vector type of
1545/// the specified element type and size. VectorType must be a built-in type.
1546QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Chris Lattnerf52ab252008-04-06 22:59:24 +00001549 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001550 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // Check if we've already instantiated a vector of this type.
1553 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001554 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 void *InsertPos = 0;
1556 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1557 return QualType(VTP, 0);
1558
1559 // If the element type isn't canonical, this won't be a canonical type either,
1560 // so fill in the canonical type field.
1561 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001562 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001563 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 // Get the new insert position for the node we care about.
1566 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001567 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 }
John McCall6b304a02009-09-24 23:30:46 +00001569 VectorType *New = new (*this, TypeAlignment)
1570 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 VectorTypes.InsertNode(New, InsertPos);
1572 Types.push_back(New);
1573 return QualType(New, 0);
1574}
1575
Nate Begeman213541a2008-04-18 23:10:10 +00001576/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001577/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001578QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001579 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Chris Lattnerf52ab252008-04-06 22:59:24 +00001581 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001582 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Steve Naroff73322922007-07-18 18:00:27 +00001584 // Check if we've already instantiated a vector of this type.
1585 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001586 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001587 void *InsertPos = 0;
1588 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1589 return QualType(VTP, 0);
1590
1591 // If the element type isn't canonical, this won't be a canonical type either,
1592 // so fill in the canonical type field.
1593 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001594 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001595 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Steve Naroff73322922007-07-18 18:00:27 +00001597 // Get the new insert position for the node we care about.
1598 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001599 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001600 }
John McCall6b304a02009-09-24 23:30:46 +00001601 ExtVectorType *New = new (*this, TypeAlignment)
1602 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001603 VectorTypes.InsertNode(New, InsertPos);
1604 Types.push_back(New);
1605 return QualType(New, 0);
1606}
1607
Mike Stump1eb44332009-09-09 15:08:12 +00001608QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001609 Expr *SizeExpr,
1610 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001611 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001612 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001613 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001615 void *InsertPos = 0;
1616 DependentSizedExtVectorType *Canon
1617 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1618 DependentSizedExtVectorType *New;
1619 if (Canon) {
1620 // We already have a canonical version of this array type; use it as
1621 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001622 New = new (*this, TypeAlignment)
1623 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1624 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001625 } else {
1626 QualType CanonVecTy = getCanonicalType(vecType);
1627 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001628 New = new (*this, TypeAlignment)
1629 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1630 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001631 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1632 } else {
1633 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1634 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001635 New = new (*this, TypeAlignment)
1636 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001637 }
1638 }
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001640 Types.push_back(New);
1641 return QualType(New, 0);
1642}
1643
Douglas Gregor72564e72009-02-26 23:50:07 +00001644/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001645///
Mike Stump24556362009-07-25 21:26:53 +00001646QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 // Unique functions, to guarantee there is only one function of a particular
1648 // structure.
1649 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001650 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001653 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001654 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001658 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001659 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001662 FunctionNoProtoType *NewIP =
1663 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001664 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
John McCall6b304a02009-09-24 23:30:46 +00001667 FunctionNoProtoType *New = new (*this, TypeAlignment)
1668 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001670 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 return QualType(New, 0);
1672}
1673
1674/// getFunctionType - Return a normal function type with a typed argument
1675/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001676QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001677 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001678 unsigned TypeQuals, bool hasExceptionSpec,
1679 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001680 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 // Unique functions, to guarantee there is only one function of a particular
1682 // structure.
1683 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001684 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001685 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001686 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001687
1688 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001689 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001690 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001692
1693 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001694 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001696 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 isCanonical = false;
1698
1699 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001700 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 QualType Canonical;
1702 if (!isCanonical) {
1703 llvm::SmallVector<QualType, 16> CanonicalArgs;
1704 CanonicalArgs.reserve(NumArgs);
1705 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001706 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001707
Chris Lattnerf52ab252008-04-06 22:59:24 +00001708 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001709 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001710 isVariadic, TypeQuals, false,
1711 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001712
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001714 FunctionProtoType *NewIP =
1715 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001716 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001718
Douglas Gregor72564e72009-02-26 23:50:07 +00001719 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001720 // for two variable size arrays (for parameter and exception types) at the
1721 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001722 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001723 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1724 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001725 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001726 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001727 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001728 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001730 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 return QualType(FTP, 0);
1732}
1733
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001734/// getTypeDeclType - Return the unique reference to the type for the
1735/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001736QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001737 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001738 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001740 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001741 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001742 else if (isa<TemplateTypeParmDecl>(Decl)) {
1743 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001744 } else if (ObjCInterfaceDecl *ObjCInterface
1745 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001746 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001747
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001748 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001749 if (PrevDecl)
1750 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001751 else
John McCall6b304a02009-09-24 23:30:46 +00001752 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001753 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001754 if (PrevDecl)
1755 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001756 else
John McCall6b304a02009-09-24 23:30:46 +00001757 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001758 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001759 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001760
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001761 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001762 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001763}
1764
Reid Spencer5f016e22007-07-11 17:01:13 +00001765/// getTypedefType - Return the unique reference to the type for the
1766/// specified typename decl.
1767QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1768 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Chris Lattnerf52ab252008-04-06 22:59:24 +00001770 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001771 Decl->TypeForDecl = new(*this, TypeAlignment)
1772 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 Types.push_back(Decl->TypeForDecl);
1774 return QualType(Decl->TypeForDecl, 0);
1775}
1776
John McCall49a832b2009-10-18 09:09:24 +00001777/// \brief Retrieve a substitution-result type.
1778QualType
1779ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1780 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001781 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001782 && "replacement types must always be canonical");
1783
1784 llvm::FoldingSetNodeID ID;
1785 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1786 void *InsertPos = 0;
1787 SubstTemplateTypeParmType *SubstParm
1788 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1789
1790 if (!SubstParm) {
1791 SubstParm = new (*this, TypeAlignment)
1792 SubstTemplateTypeParmType(Parm, Replacement);
1793 Types.push_back(SubstParm);
1794 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1795 }
1796
1797 return QualType(SubstParm, 0);
1798}
1799
Douglas Gregorfab9d672009-02-05 23:33:38 +00001800/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001801/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001802/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001803QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001804 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001805 IdentifierInfo *Name) {
1806 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001807 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001808 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001809 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001810 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1811
1812 if (TypeParm)
1813 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001815 if (Name) {
1816 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001817 TypeParm = new (*this, TypeAlignment)
1818 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001819 } else
John McCall6b304a02009-09-24 23:30:46 +00001820 TypeParm = new (*this, TypeAlignment)
1821 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001822
1823 Types.push_back(TypeParm);
1824 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1825
1826 return QualType(TypeParm, 0);
1827}
1828
Mike Stump1eb44332009-09-09 15:08:12 +00001829QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001830ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall833ca992009-10-29 08:12:44 +00001831 const TemplateArgumentLoc *Args,
1832 unsigned NumArgs,
1833 QualType Canon) {
1834 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1835 ArgVec.reserve(NumArgs);
1836 for (unsigned i = 0; i != NumArgs; ++i)
1837 ArgVec.push_back(Args[i].getArgument());
1838
1839 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1840}
1841
1842QualType
1843ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001844 const TemplateArgument *Args,
1845 unsigned NumArgs,
1846 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001847 if (!Canon.isNull())
1848 Canon = getCanonicalType(Canon);
1849 else {
1850 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001851 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1852 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1853 CanonArgs.reserve(NumArgs);
1854 for (unsigned I = 0; I != NumArgs; ++I)
1855 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1856
1857 // Determine whether this canonical template specialization type already
1858 // exists.
1859 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001860 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001861 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001862
1863 void *InsertPos = 0;
1864 TemplateSpecializationType *Spec
1865 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor1275ae02009-07-28 23:00:59 +00001867 if (!Spec) {
1868 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001870 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001871 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001872 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001873 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001874 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001875 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001876 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregorb88e8882009-07-30 17:40:51 +00001879 if (Canon.isNull())
1880 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001881 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001882 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001883 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001884
Douglas Gregor1275ae02009-07-28 23:00:59 +00001885 // Allocate the (non-canonical) template specialization type, but don't
1886 // try to unique it: these types typically have location information that
1887 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001888 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001889 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001890 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001891 TemplateSpecializationType *Spec
1892 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001893 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor55f6b142009-02-09 18:46:07 +00001895 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001896 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001897}
1898
Mike Stump1eb44332009-09-09 15:08:12 +00001899QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001900ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001901 QualType NamedType) {
1902 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001903 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001904
1905 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001906 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001907 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1908 if (T)
1909 return QualType(T, 0);
1910
Mike Stump1eb44332009-09-09 15:08:12 +00001911 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001912 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001913 Types.push_back(T);
1914 QualifiedNameTypes.InsertNode(T, InsertPos);
1915 return QualType(T, 0);
1916}
1917
Mike Stump1eb44332009-09-09 15:08:12 +00001918QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001919 const IdentifierInfo *Name,
1920 QualType Canon) {
1921 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1922
1923 if (Canon.isNull()) {
1924 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1925 if (CanonNNS != NNS)
1926 Canon = getTypenameType(CanonNNS, Name);
1927 }
1928
1929 llvm::FoldingSetNodeID ID;
1930 TypenameType::Profile(ID, NNS, Name);
1931
1932 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001933 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001934 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1935 if (T)
1936 return QualType(T, 0);
1937
1938 T = new (*this) TypenameType(NNS, Name, Canon);
1939 Types.push_back(T);
1940 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001941 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001942}
1943
Mike Stump1eb44332009-09-09 15:08:12 +00001944QualType
1945ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001946 const TemplateSpecializationType *TemplateId,
1947 QualType Canon) {
1948 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1949
1950 if (Canon.isNull()) {
1951 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1952 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1953 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1954 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001955 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001956 assert(CanonTemplateId &&
1957 "Canonical type must also be a template specialization type");
1958 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1959 }
1960 }
1961
1962 llvm::FoldingSetNodeID ID;
1963 TypenameType::Profile(ID, NNS, TemplateId);
1964
1965 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001966 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001967 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1968 if (T)
1969 return QualType(T, 0);
1970
1971 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1972 Types.push_back(T);
1973 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001974 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001975}
1976
John McCall7da24312009-09-05 00:15:47 +00001977QualType
1978ASTContext::getElaboratedType(QualType UnderlyingType,
1979 ElaboratedType::TagKind Tag) {
1980 llvm::FoldingSetNodeID ID;
1981 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
John McCall7da24312009-09-05 00:15:47 +00001983 void *InsertPos = 0;
1984 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1985 if (T)
1986 return QualType(T, 0);
1987
1988 QualType Canon = getCanonicalType(UnderlyingType);
1989
1990 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1991 Types.push_back(T);
1992 ElaboratedTypes.InsertNode(T, InsertPos);
1993 return QualType(T, 0);
1994}
1995
Chris Lattner88cb27a2008-04-07 04:56:42 +00001996/// CmpProtocolNames - Comparison predicate for sorting protocols
1997/// alphabetically.
1998static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1999 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002000 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002001}
2002
John McCall54e14c42009-10-22 22:37:11 +00002003static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2004 unsigned NumProtocols) {
2005 if (NumProtocols == 0) return true;
2006
2007 for (unsigned i = 1; i != NumProtocols; ++i)
2008 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2009 return false;
2010 return true;
2011}
2012
2013static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002014 unsigned &NumProtocols) {
2015 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Chris Lattner88cb27a2008-04-07 04:56:42 +00002017 // Sort protocols, keyed by name.
2018 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2019
2020 // Remove duplicates.
2021 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2022 NumProtocols = ProtocolsEnd-Protocols;
2023}
2024
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002025/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2026/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002027QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002028 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002029 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002030 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002031 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002032
2033 void *InsertPos = 0;
2034 if (ObjCObjectPointerType *QT =
2035 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2036 return QualType(QT, 0);
2037
John McCall54e14c42009-10-22 22:37:11 +00002038 // Sort the protocol list alphabetically to canonicalize it.
2039 QualType Canonical;
2040 if (!InterfaceT.isCanonical() ||
2041 !areSortedAndUniqued(Protocols, NumProtocols)) {
2042 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2043 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2044 unsigned UniqueCount = NumProtocols;
2045
2046 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2047 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2048
2049 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2050 &Sorted[0], UniqueCount);
2051 } else {
2052 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2053 Protocols, NumProtocols);
2054 }
2055
2056 // Regenerate InsertPos.
2057 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2058 }
2059
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002060 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002061 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002062 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002064 Types.push_back(QType);
2065 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2066 return QualType(QType, 0);
2067}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002068
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002069/// getObjCInterfaceType - Return the unique reference to the type for the
2070/// specified ObjC interface decl. The list of protocols is optional.
2071QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002072 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002073 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002074 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002076 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002077 if (ObjCInterfaceType *QT =
2078 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002079 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002080
John McCall54e14c42009-10-22 22:37:11 +00002081 // Sort the protocol list alphabetically to canonicalize it.
2082 QualType Canonical;
2083 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2084 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2085 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2086
2087 unsigned UniqueCount = NumProtocols;
2088 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2089
2090 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2091
2092 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2093 }
2094
John McCall6b304a02009-09-24 23:30:46 +00002095 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002096 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002097 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002098
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002099 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002100 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002101 return QualType(QType, 0);
2102}
2103
Douglas Gregor72564e72009-02-26 23:50:07 +00002104/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2105/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002106/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002107/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002108/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002109QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002110 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002111 if (tofExpr->isTypeDependent()) {
2112 llvm::FoldingSetNodeID ID;
2113 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Douglas Gregorb1975722009-07-30 23:18:24 +00002115 void *InsertPos = 0;
2116 DependentTypeOfExprType *Canon
2117 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2118 if (Canon) {
2119 // We already have a "canonical" version of an identical, dependent
2120 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002121 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002122 QualType((TypeOfExprType*)Canon, 0));
2123 }
2124 else {
2125 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002126 Canon
2127 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002128 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2129 toe = Canon;
2130 }
2131 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002132 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002133 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002134 }
Steve Naroff9752f252007-08-01 18:02:17 +00002135 Types.push_back(toe);
2136 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002137}
2138
Steve Naroff9752f252007-08-01 18:02:17 +00002139/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2140/// TypeOfType AST's. The only motivation to unique these nodes would be
2141/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002142/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002143/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002144QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002145 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002146 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002147 Types.push_back(tot);
2148 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002149}
2150
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002151/// getDecltypeForExpr - Given an expr, will return the decltype for that
2152/// expression, according to the rules in C++0x [dcl.type.simple]p4
2153static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002154 if (e->isTypeDependent())
2155 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002157 // If e is an id expression or a class member access, decltype(e) is defined
2158 // as the type of the entity named by e.
2159 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2160 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2161 return VD->getType();
2162 }
2163 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2164 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2165 return FD->getType();
2166 }
2167 // If e is a function call or an invocation of an overloaded operator,
2168 // (parentheses around e are ignored), decltype(e) is defined as the
2169 // return type of that function.
2170 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2171 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002173 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002174
2175 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002176 // defined as T&, otherwise decltype(e) is defined as T.
2177 if (e->isLvalue(Context) == Expr::LV_Valid)
2178 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002180 return T;
2181}
2182
Anders Carlsson395b4752009-06-24 19:06:50 +00002183/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2184/// DecltypeType AST's. The only motivation to unique these nodes would be
2185/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002186/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002187/// on canonical type's (which are always unique).
2188QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002189 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002190 if (e->isTypeDependent()) {
2191 llvm::FoldingSetNodeID ID;
2192 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002194 void *InsertPos = 0;
2195 DependentDecltypeType *Canon
2196 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2197 if (Canon) {
2198 // We already have a "canonical" version of an equivalent, dependent
2199 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002200 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002201 QualType((DecltypeType*)Canon, 0));
2202 }
2203 else {
2204 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002205 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002206 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2207 dt = Canon;
2208 }
2209 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002210 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002211 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002212 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002213 Types.push_back(dt);
2214 return QualType(dt, 0);
2215}
2216
Reid Spencer5f016e22007-07-11 17:01:13 +00002217/// getTagDeclType - Return the unique reference to the type for the
2218/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002219QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002220 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002221 // FIXME: What is the design on getTagDeclType when it requires casting
2222 // away const? mutable?
2223 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002224}
2225
Mike Stump1eb44332009-09-09 15:08:12 +00002226/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2227/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2228/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002229QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002230 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002231}
2232
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002233/// getSignedWCharType - Return the type of "signed wchar_t".
2234/// Used when in C++, as a GCC extension.
2235QualType ASTContext::getSignedWCharType() const {
2236 // FIXME: derive from "Target" ?
2237 return WCharTy;
2238}
2239
2240/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2241/// Used when in C++, as a GCC extension.
2242QualType ASTContext::getUnsignedWCharType() const {
2243 // FIXME: derive from "Target" ?
2244 return UnsignedIntTy;
2245}
2246
Chris Lattner8b9023b2007-07-13 03:05:23 +00002247/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2248/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2249QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002250 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002251}
2252
Chris Lattnere6327742008-04-02 05:18:44 +00002253//===----------------------------------------------------------------------===//
2254// Type Operators
2255//===----------------------------------------------------------------------===//
2256
John McCall54e14c42009-10-22 22:37:11 +00002257CanQualType ASTContext::getCanonicalParamType(QualType T) {
2258 // Push qualifiers into arrays, and then discard any remaining
2259 // qualifiers.
2260 T = getCanonicalType(T);
2261 const Type *Ty = T.getTypePtr();
2262
2263 QualType Result;
2264 if (isa<ArrayType>(Ty)) {
2265 Result = getArrayDecayedType(QualType(Ty,0));
2266 } else if (isa<FunctionType>(Ty)) {
2267 Result = getPointerType(QualType(Ty, 0));
2268 } else {
2269 Result = QualType(Ty, 0);
2270 }
2271
2272 return CanQualType::CreateUnsafe(Result);
2273}
2274
Chris Lattner77c96472008-04-06 22:41:35 +00002275/// getCanonicalType - Return the canonical (structural) type corresponding to
2276/// the specified potentially non-canonical type. The non-canonical version
2277/// of a type may have many "decorated" versions of types. Decorators can
2278/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2279/// to be free of any of these, allowing two canonical types to be compared
2280/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002281CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002282 QualifierCollector Quals;
2283 const Type *Ptr = Quals.strip(T);
2284 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002285
John McCall0953e762009-09-24 19:53:00 +00002286 // The canonical internal type will be the canonical type *except*
2287 // that we push type qualifiers down through array types.
2288
2289 // If there are no new qualifiers to push down, stop here.
2290 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002291 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002292
John McCall0953e762009-09-24 19:53:00 +00002293 // If the type qualifiers are on an array type, get the canonical
2294 // type of the array with the qualifiers applied to the element
2295 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002296 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2297 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002298 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002300 // Get the canonical version of the element with the extra qualifiers on it.
2301 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002302 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002303 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002305 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002306 return CanQualType::CreateUnsafe(
2307 getConstantArrayType(NewEltTy, CAT->getSize(),
2308 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002309 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002310 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002311 return CanQualType::CreateUnsafe(
2312 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002313 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Douglas Gregor898574e2008-12-05 23:32:09 +00002315 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002316 return CanQualType::CreateUnsafe(
2317 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002318 DSAT->getSizeExpr() ?
2319 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002320 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002321 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002322 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002323
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002324 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002325 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002326 VAT->getSizeExpr() ?
2327 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002328 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002329 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002330 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002331}
2332
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002333TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2334 // If this template name refers to a template, the canonical
2335 // template name merely stores the template itself.
2336 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002337 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002338
Mike Stump1eb44332009-09-09 15:08:12 +00002339 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002340 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002341 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2342 OverloadedFunctionDecl *CanonOvl = 0;
2343 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2344 FEnd = Ovl->function_end();
2345 F != FEnd; ++F) {
2346 Decl *Canon = F->get()->getCanonicalDecl();
2347 if (CanonOvl || Canon != F->get()) {
2348 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002349 CanonOvl = OverloadedFunctionDecl::Create(*this,
2350 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002351 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002353 CanonOvl->addOverload(
2354 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2355 }
2356 }
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002358 return TemplateName(CanonOvl? CanonOvl : Ovl);
2359 }
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002361 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2362 assert(DTN && "Non-dependent template names must refer to template decls.");
2363 return DTN->CanonicalTemplateName;
2364}
2365
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002366bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2367 X = getCanonicalTemplateName(X);
2368 Y = getCanonicalTemplateName(Y);
2369 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2370}
2371
Mike Stump1eb44332009-09-09 15:08:12 +00002372TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002373ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2374 switch (Arg.getKind()) {
2375 case TemplateArgument::Null:
2376 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Douglas Gregor1275ae02009-07-28 23:00:59 +00002378 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002379 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor1275ae02009-07-28 23:00:59 +00002381 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002382 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Douglas Gregor788cd062009-11-11 01:00:40 +00002384 case TemplateArgument::Template:
2385 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2386
Douglas Gregor1275ae02009-07-28 23:00:59 +00002387 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002388 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002389 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Douglas Gregor1275ae02009-07-28 23:00:59 +00002391 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002392 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Douglas Gregor1275ae02009-07-28 23:00:59 +00002394 case TemplateArgument::Pack: {
2395 // FIXME: Allocate in ASTContext
2396 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2397 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002398 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002399 AEnd = Arg.pack_end();
2400 A != AEnd; (void)++A, ++Idx)
2401 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor1275ae02009-07-28 23:00:59 +00002403 TemplateArgument Result;
2404 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2405 return Result;
2406 }
2407 }
2408
2409 // Silence GCC warning
2410 assert(false && "Unhandled template argument kind");
2411 return TemplateArgument();
2412}
2413
Douglas Gregord57959a2009-03-27 23:10:48 +00002414NestedNameSpecifier *
2415ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002416 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002417 return 0;
2418
2419 switch (NNS->getKind()) {
2420 case NestedNameSpecifier::Identifier:
2421 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002422 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002423 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2424 NNS->getAsIdentifier());
2425
2426 case NestedNameSpecifier::Namespace:
2427 // A namespace is canonical; build a nested-name-specifier with
2428 // this namespace and no prefix.
2429 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2430
2431 case NestedNameSpecifier::TypeSpec:
2432 case NestedNameSpecifier::TypeSpecWithTemplate: {
2433 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002434 return NestedNameSpecifier::Create(*this, 0,
2435 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002436 T.getTypePtr());
2437 }
2438
2439 case NestedNameSpecifier::Global:
2440 // The global specifier is canonical and unique.
2441 return NNS;
2442 }
2443
2444 // Required to silence a GCC warning
2445 return 0;
2446}
2447
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002448
2449const ArrayType *ASTContext::getAsArrayType(QualType T) {
2450 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002451 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002452 // Handle the common positive case fast.
2453 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2454 return AT;
2455 }
Mike Stump1eb44332009-09-09 15:08:12 +00002456
John McCall0953e762009-09-24 19:53:00 +00002457 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002458 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002459 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002460 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002461
John McCall0953e762009-09-24 19:53:00 +00002462 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002463 // implements C99 6.7.3p8: "If the specification of an array type includes
2464 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002466 // If we get here, we either have type qualifiers on the type, or we have
2467 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002468 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002469
John McCall0953e762009-09-24 19:53:00 +00002470 QualifierCollector Qs;
2471 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002473 // If we have a simple case, just return now.
2474 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002475 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002476 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002478 // Otherwise, we have an array and we have qualifiers on it. Push the
2479 // qualifiers into the array element type and return a new array type.
2480 // Get the canonical version of the element with the extra qualifiers on it.
2481 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002482 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002484 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2485 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2486 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002487 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002488 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2489 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2490 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002491 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002492
Mike Stump1eb44332009-09-09 15:08:12 +00002493 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002494 = dyn_cast<DependentSizedArrayType>(ATy))
2495 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002496 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002497 DSAT->getSizeExpr() ?
2498 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002499 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002500 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002501 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002502
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002503 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002504 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002505 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002506 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002507 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002508 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002509 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002510}
2511
2512
Chris Lattnere6327742008-04-02 05:18:44 +00002513/// getArrayDecayedType - Return the properly qualified result of decaying the
2514/// specified array type to a pointer. This operation is non-trivial when
2515/// handling typedefs etc. The canonical type of "T" must be an array type,
2516/// this returns a pointer to a properly qualified element of the array.
2517///
2518/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2519QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002520 // Get the element type with 'getAsArrayType' so that we don't lose any
2521 // typedefs in the element type of the array. This also handles propagation
2522 // of type qualifiers from the array type into the element type if present
2523 // (C99 6.7.3p8).
2524 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2525 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002527 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002528
2529 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002530 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002531}
2532
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002533QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002534 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002535 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002536 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002537 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2538 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002539 } else {
John McCall0953e762009-09-24 19:53:00 +00002540 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002541 }
2542 }
2543}
2544
Anders Carlssonfbbce492009-09-25 01:23:32 +00002545QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2546 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002547
Anders Carlssonfbbce492009-09-25 01:23:32 +00002548 if (const ArrayType *AT = getAsArrayType(ElemTy))
2549 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Anders Carlsson6183a992008-12-21 03:44:36 +00002551 return ElemTy;
2552}
2553
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002554/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002555uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002556ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2557 uint64_t ElementCount = 1;
2558 do {
2559 ElementCount *= CA->getSize().getZExtValue();
2560 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2561 } while (CA);
2562 return ElementCount;
2563}
2564
Reid Spencer5f016e22007-07-11 17:01:13 +00002565/// getFloatingRank - Return a relative rank for floating point types.
2566/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002567static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002568 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002570
John McCall183700f2009-09-21 23:43:11 +00002571 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2572 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002573 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 case BuiltinType::Float: return FloatRank;
2575 case BuiltinType::Double: return DoubleRank;
2576 case BuiltinType::LongDouble: return LongDoubleRank;
2577 }
2578}
2579
Mike Stump1eb44332009-09-09 15:08:12 +00002580/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2581/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002582/// 'typeDomain' is a real floating point or complex type.
2583/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002584QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2585 QualType Domain) const {
2586 FloatingRank EltRank = getFloatingRank(Size);
2587 if (Domain->isComplexType()) {
2588 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002589 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002590 case FloatRank: return FloatComplexTy;
2591 case DoubleRank: return DoubleComplexTy;
2592 case LongDoubleRank: return LongDoubleComplexTy;
2593 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 }
Chris Lattner1361b112008-04-06 23:58:54 +00002595
2596 assert(Domain->isRealFloatingType() && "Unknown domain!");
2597 switch (EltRank) {
2598 default: assert(0 && "getFloatingRank(): illegal value for rank");
2599 case FloatRank: return FloatTy;
2600 case DoubleRank: return DoubleTy;
2601 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002602 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002603}
2604
Chris Lattner7cfeb082008-04-06 23:55:33 +00002605/// getFloatingTypeOrder - Compare the rank of the two specified floating
2606/// point types, ignoring the domain of the type (i.e. 'double' ==
2607/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002608/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002609int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2610 FloatingRank LHSR = getFloatingRank(LHS);
2611 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Chris Lattnera75cea32008-04-06 23:38:49 +00002613 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002614 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002615 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002616 return 1;
2617 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002618}
2619
Chris Lattnerf52ab252008-04-06 22:59:24 +00002620/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2621/// routine will assert if passed a built-in type that isn't an integer or enum,
2622/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002623unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002624 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002625 if (EnumType* ET = dyn_cast<EnumType>(T))
2626 T = ET->getDecl()->getIntegerType().getTypePtr();
2627
Eli Friedmana3426752009-07-05 23:44:27 +00002628 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2629 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2630
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002631 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2632 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2633
2634 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2635 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2636
Eli Friedmanf98aba32009-02-13 02:31:07 +00002637 // There are two things which impact the integer rank: the width, and
2638 // the ordering of builtins. The builtin ordering is encoded in the
2639 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002640 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002641 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002642
Chris Lattnerf52ab252008-04-06 22:59:24 +00002643 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002644 default: assert(0 && "getIntegerRank(): not a built-in integer");
2645 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002646 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002647 case BuiltinType::Char_S:
2648 case BuiltinType::Char_U:
2649 case BuiltinType::SChar:
2650 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002651 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002652 case BuiltinType::Short:
2653 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002654 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002655 case BuiltinType::Int:
2656 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002657 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002658 case BuiltinType::Long:
2659 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002660 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002661 case BuiltinType::LongLong:
2662 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002663 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002664 case BuiltinType::Int128:
2665 case BuiltinType::UInt128:
2666 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002667 }
2668}
2669
Eli Friedman04e83572009-08-20 04:21:42 +00002670/// \brief Whether this is a promotable bitfield reference according
2671/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2672///
2673/// \returns the type this bit-field will promote to, or NULL if no
2674/// promotion occurs.
2675QualType ASTContext::isPromotableBitField(Expr *E) {
2676 FieldDecl *Field = E->getBitField();
2677 if (!Field)
2678 return QualType();
2679
2680 QualType FT = Field->getType();
2681
2682 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2683 uint64_t BitWidth = BitWidthAP.getZExtValue();
2684 uint64_t IntSize = getTypeSize(IntTy);
2685 // GCC extension compatibility: if the bit-field size is less than or equal
2686 // to the size of int, it gets promoted no matter what its type is.
2687 // For instance, unsigned long bf : 4 gets promoted to signed int.
2688 if (BitWidth < IntSize)
2689 return IntTy;
2690
2691 if (BitWidth == IntSize)
2692 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2693
2694 // Types bigger than int are not subject to promotions, and therefore act
2695 // like the base type.
2696 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2697 // is ridiculous.
2698 return QualType();
2699}
2700
Eli Friedmana95d7572009-08-19 07:44:53 +00002701/// getPromotedIntegerType - Returns the type that Promotable will
2702/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2703/// integer type.
2704QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2705 assert(!Promotable.isNull());
2706 assert(Promotable->isPromotableIntegerType());
2707 if (Promotable->isSignedIntegerType())
2708 return IntTy;
2709 uint64_t PromotableSize = getTypeSize(Promotable);
2710 uint64_t IntSize = getTypeSize(IntTy);
2711 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2712 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2713}
2714
Mike Stump1eb44332009-09-09 15:08:12 +00002715/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002716/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002717/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002718int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002719 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2720 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002721 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Chris Lattnerf52ab252008-04-06 22:59:24 +00002723 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2724 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Chris Lattner7cfeb082008-04-06 23:55:33 +00002726 unsigned LHSRank = getIntegerRank(LHSC);
2727 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Chris Lattner7cfeb082008-04-06 23:55:33 +00002729 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2730 if (LHSRank == RHSRank) return 0;
2731 return LHSRank > RHSRank ? 1 : -1;
2732 }
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Chris Lattner7cfeb082008-04-06 23:55:33 +00002734 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2735 if (LHSUnsigned) {
2736 // If the unsigned [LHS] type is larger, return it.
2737 if (LHSRank >= RHSRank)
2738 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Chris Lattner7cfeb082008-04-06 23:55:33 +00002740 // If the signed type can represent all values of the unsigned type, it
2741 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002742 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002743 return -1;
2744 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002745
Chris Lattner7cfeb082008-04-06 23:55:33 +00002746 // If the unsigned [RHS] type is larger, return it.
2747 if (RHSRank >= LHSRank)
2748 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Chris Lattner7cfeb082008-04-06 23:55:33 +00002750 // If the signed type can represent all values of the unsigned type, it
2751 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002752 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002753 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002754}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002755
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002756static RecordDecl *
2757CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2758 SourceLocation L, IdentifierInfo *Id) {
2759 if (Ctx.getLangOptions().CPlusPlus)
2760 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2761 else
2762 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2763}
2764
Mike Stump1eb44332009-09-09 15:08:12 +00002765// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002766QualType ASTContext::getCFConstantStringType() {
2767 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002768 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002769 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2770 &Idents.get("NSConstantString"));
2771
Anders Carlssonf06273f2007-11-19 00:25:30 +00002772 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Anders Carlsson71993dd2007-08-17 05:31:46 +00002774 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002775 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002776 // int flags;
2777 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002778 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002779 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002780 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002781 FieldTypes[3] = LongTy;
2782
Anders Carlsson71993dd2007-08-17 05:31:46 +00002783 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002784 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002785 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002786 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002787 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002788 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002789 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002790 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002791 }
2792
2793 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Anders Carlsson71993dd2007-08-17 05:31:46 +00002796 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002797}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002798
Douglas Gregor319ac892009-04-23 22:29:11 +00002799void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002800 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002801 assert(Rec && "Invalid CFConstantStringType");
2802 CFConstantStringTypeDecl = Rec->getDecl();
2803}
2804
Mike Stump1eb44332009-09-09 15:08:12 +00002805QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002806 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002807 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002808 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2809 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002811 QualType FieldTypes[] = {
2812 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002813 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002814 getPointerType(UnsignedLongTy),
2815 getConstantArrayType(UnsignedLongTy,
2816 llvm::APInt(32, 5), ArrayType::Normal, 0)
2817 };
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Douglas Gregor44b43212008-12-11 16:49:14 +00002819 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002820 FieldDecl *Field = FieldDecl::Create(*this,
2821 ObjCFastEnumerationStateTypeDecl,
2822 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002823 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002824 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002825 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002826 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002827 }
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Douglas Gregor44b43212008-12-11 16:49:14 +00002829 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002830 }
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002832 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2833}
2834
Mike Stumpadaaad32009-10-20 02:12:22 +00002835QualType ASTContext::getBlockDescriptorType() {
2836 if (BlockDescriptorType)
2837 return getTagDeclType(BlockDescriptorType);
2838
2839 RecordDecl *T;
2840 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002841 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2842 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002843
2844 QualType FieldTypes[] = {
2845 UnsignedLongTy,
2846 UnsignedLongTy,
2847 };
2848
2849 const char *FieldNames[] = {
2850 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002851 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002852 };
2853
2854 for (size_t i = 0; i < 2; ++i) {
2855 FieldDecl *Field = FieldDecl::Create(*this,
2856 T,
2857 SourceLocation(),
2858 &Idents.get(FieldNames[i]),
2859 FieldTypes[i], /*DInfo=*/0,
2860 /*BitWidth=*/0,
2861 /*Mutable=*/false);
2862 T->addDecl(Field);
2863 }
2864
2865 T->completeDefinition(*this);
2866
2867 BlockDescriptorType = T;
2868
2869 return getTagDeclType(BlockDescriptorType);
2870}
2871
2872void ASTContext::setBlockDescriptorType(QualType T) {
2873 const RecordType *Rec = T->getAs<RecordType>();
2874 assert(Rec && "Invalid BlockDescriptorType");
2875 BlockDescriptorType = Rec->getDecl();
2876}
2877
Mike Stump083c25e2009-10-22 00:49:09 +00002878QualType ASTContext::getBlockDescriptorExtendedType() {
2879 if (BlockDescriptorExtendedType)
2880 return getTagDeclType(BlockDescriptorExtendedType);
2881
2882 RecordDecl *T;
2883 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002884 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2885 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002886
2887 QualType FieldTypes[] = {
2888 UnsignedLongTy,
2889 UnsignedLongTy,
2890 getPointerType(VoidPtrTy),
2891 getPointerType(VoidPtrTy)
2892 };
2893
2894 const char *FieldNames[] = {
2895 "reserved",
2896 "Size",
2897 "CopyFuncPtr",
2898 "DestroyFuncPtr"
2899 };
2900
2901 for (size_t i = 0; i < 4; ++i) {
2902 FieldDecl *Field = FieldDecl::Create(*this,
2903 T,
2904 SourceLocation(),
2905 &Idents.get(FieldNames[i]),
2906 FieldTypes[i], /*DInfo=*/0,
2907 /*BitWidth=*/0,
2908 /*Mutable=*/false);
2909 T->addDecl(Field);
2910 }
2911
2912 T->completeDefinition(*this);
2913
2914 BlockDescriptorExtendedType = T;
2915
2916 return getTagDeclType(BlockDescriptorExtendedType);
2917}
2918
2919void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2920 const RecordType *Rec = T->getAs<RecordType>();
2921 assert(Rec && "Invalid BlockDescriptorType");
2922 BlockDescriptorExtendedType = Rec->getDecl();
2923}
2924
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002925bool ASTContext::BlockRequiresCopying(QualType Ty) {
2926 if (Ty->isBlockPointerType())
2927 return true;
2928 if (isObjCNSObjectType(Ty))
2929 return true;
2930 if (Ty->isObjCObjectPointerType())
2931 return true;
2932 return false;
2933}
2934
2935QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2936 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002937 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002938 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002939 // unsigned int __flags;
2940 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002941 // void *__copy_helper; // as needed
2942 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002943 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002944 // } *
2945
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002946 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2947
2948 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002949 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002950 llvm::SmallString<36> Name;
2951 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2952 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002953 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002954 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2955 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002956 T->startDefinition();
2957 QualType Int32Ty = IntTy;
2958 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2959 QualType FieldTypes[] = {
2960 getPointerType(VoidPtrTy),
2961 getPointerType(getTagDeclType(T)),
2962 Int32Ty,
2963 Int32Ty,
2964 getPointerType(VoidPtrTy),
2965 getPointerType(VoidPtrTy),
2966 Ty
2967 };
2968
2969 const char *FieldNames[] = {
2970 "__isa",
2971 "__forwarding",
2972 "__flags",
2973 "__size",
2974 "__copy_helper",
2975 "__destroy_helper",
2976 DeclName,
2977 };
2978
2979 for (size_t i = 0; i < 7; ++i) {
2980 if (!HasCopyAndDispose && i >=4 && i <= 5)
2981 continue;
2982 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2983 &Idents.get(FieldNames[i]),
2984 FieldTypes[i], /*DInfo=*/0,
2985 /*BitWidth=*/0, /*Mutable=*/false);
2986 T->addDecl(Field);
2987 }
2988
2989 T->completeDefinition(*this);
2990
2991 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002992}
2993
2994
2995QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002996 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002997 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002998 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002999 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003000 llvm::SmallString<36> Name;
3001 llvm::raw_svector_ostream(Name) << "__block_literal_"
3002 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003003 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003004 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3005 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003006 QualType FieldTypes[] = {
3007 getPointerType(VoidPtrTy),
3008 IntTy,
3009 IntTy,
3010 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003011 (BlockHasCopyDispose ?
3012 getPointerType(getBlockDescriptorExtendedType()) :
3013 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003014 };
3015
3016 const char *FieldNames[] = {
3017 "__isa",
3018 "__flags",
3019 "__reserved",
3020 "__FuncPtr",
3021 "__descriptor"
3022 };
3023
3024 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003025 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003026 &Idents.get(FieldNames[i]),
3027 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003028 /*BitWidth=*/0, /*Mutable=*/false);
3029 T->addDecl(Field);
3030 }
3031
3032 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3033 const Expr *E = BlockDeclRefDecls[i];
3034 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3035 clang::IdentifierInfo *Name = 0;
3036 if (BDRE) {
3037 const ValueDecl *D = BDRE->getDecl();
3038 Name = &Idents.get(D->getName());
3039 }
3040 QualType FieldType = E->getType();
3041
3042 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003043 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3044 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003045
3046 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3047 Name, FieldType, /*DInfo=*/0,
3048 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003049 T->addDecl(Field);
3050 }
3051
3052 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003053
3054 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003055}
3056
Douglas Gregor319ac892009-04-23 22:29:11 +00003057void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003058 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003059 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3060 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3061}
3062
Anders Carlssone8c49532007-10-29 06:33:42 +00003063// This returns true if a type has been typedefed to BOOL:
3064// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003065static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003066 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003067 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3068 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003069
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003070 return false;
3071}
3072
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003073/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003074/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003075int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003076 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003078 // Make all integer and enum types at least as large as an int
3079 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003080 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003081 // Treat arrays as pointers, since that's how they're passed in.
3082 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003083 sz = getTypeSize(VoidPtrTy);
3084 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003085}
3086
David Chisnall5e530af2009-11-17 19:33:30 +00003087/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3088/// declaration.
3089void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3090 std::string& S) {
3091 const BlockDecl *Decl = Expr->getBlockDecl();
3092 QualType BlockTy =
3093 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3094 // Encode result type.
3095 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3096 // Compute size of all parameters.
3097 // Start with computing size of a pointer in number of bytes.
3098 // FIXME: There might(should) be a better way of doing this computation!
3099 SourceLocation Loc;
3100 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3101 int ParmOffset = PtrSize;
3102 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3103 E = Decl->param_end(); PI != E; ++PI) {
3104 QualType PType = (*PI)->getType();
3105 int sz = getObjCEncodingTypeSize(PType);
3106 assert (sz > 0 && "BlockExpr - Incomplete param type");
3107 ParmOffset += sz;
3108 }
3109 // Size of the argument frame
3110 S += llvm::utostr(ParmOffset);
3111 // Block pointer and offset.
3112 S += "@?0";
3113 ParmOffset = PtrSize;
3114
3115 // Argument types.
3116 ParmOffset = PtrSize;
3117 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3118 Decl->param_end(); PI != E; ++PI) {
3119 ParmVarDecl *PVDecl = *PI;
3120 QualType PType = PVDecl->getOriginalType();
3121 if (const ArrayType *AT =
3122 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3123 // Use array's original type only if it has known number of
3124 // elements.
3125 if (!isa<ConstantArrayType>(AT))
3126 PType = PVDecl->getType();
3127 } else if (PType->isFunctionType())
3128 PType = PVDecl->getType();
3129 getObjCEncodingForType(PType, S);
3130 S += llvm::utostr(ParmOffset);
3131 ParmOffset += getObjCEncodingTypeSize(PType);
3132 }
3133}
3134
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003135/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003136/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003137void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003138 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003139 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003140 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003142 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003143 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003144 // Compute size of all parameters.
3145 // Start with computing size of a pointer in number of bytes.
3146 // FIXME: There might(should) be a better way of doing this computation!
3147 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003148 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003149 // The first two arguments (self and _cmd) are pointers; account for
3150 // their size.
3151 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003152 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3153 E = Decl->param_end(); PI != E; ++PI) {
3154 QualType PType = (*PI)->getType();
3155 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003156 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003157 ParmOffset += sz;
3158 }
3159 S += llvm::utostr(ParmOffset);
3160 S += "@0:";
3161 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003163 // Argument types.
3164 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003165 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3166 E = Decl->param_end(); PI != E; ++PI) {
3167 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003168 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003169 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003170 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3171 // Use array's original type only if it has known number of
3172 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003173 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003174 PType = PVDecl->getType();
3175 } else if (PType->isFunctionType())
3176 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003177 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003178 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003179 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003180 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003181 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003182 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003183 }
3184}
3185
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003186/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003187/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003188/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3189/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003190/// Property attributes are stored as a comma-delimited C string. The simple
3191/// attributes readonly and bycopy are encoded as single characters. The
3192/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3193/// encoded as single characters, followed by an identifier. Property types
3194/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003195/// these attributes are defined by the following enumeration:
3196/// @code
3197/// enum PropertyAttributes {
3198/// kPropertyReadOnly = 'R', // property is read-only.
3199/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3200/// kPropertyByref = '&', // property is a reference to the value last assigned
3201/// kPropertyDynamic = 'D', // property is dynamic
3202/// kPropertyGetter = 'G', // followed by getter selector name
3203/// kPropertySetter = 'S', // followed by setter selector name
3204/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3205/// kPropertyType = 't' // followed by old-style type encoding.
3206/// kPropertyWeak = 'W' // 'weak' property
3207/// kPropertyStrong = 'P' // property GC'able
3208/// kPropertyNonAtomic = 'N' // property non-atomic
3209/// };
3210/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003211void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003212 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003213 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003214 // Collect information from the property implementation decl(s).
3215 bool Dynamic = false;
3216 ObjCPropertyImplDecl *SynthesizePID = 0;
3217
3218 // FIXME: Duplicated code due to poor abstraction.
3219 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003220 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003221 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3222 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003223 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003224 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003225 ObjCPropertyImplDecl *PID = *i;
3226 if (PID->getPropertyDecl() == PD) {
3227 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3228 Dynamic = true;
3229 } else {
3230 SynthesizePID = PID;
3231 }
3232 }
3233 }
3234 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003235 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003236 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003237 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003238 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003239 ObjCPropertyImplDecl *PID = *i;
3240 if (PID->getPropertyDecl() == PD) {
3241 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3242 Dynamic = true;
3243 } else {
3244 SynthesizePID = PID;
3245 }
3246 }
Mike Stump1eb44332009-09-09 15:08:12 +00003247 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003248 }
3249 }
3250
3251 // FIXME: This is not very efficient.
3252 S = "T";
3253
3254 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003255 // GCC has some special rules regarding encoding of properties which
3256 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003257 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003258 true /* outermost type */,
3259 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003260
3261 if (PD->isReadOnly()) {
3262 S += ",R";
3263 } else {
3264 switch (PD->getSetterKind()) {
3265 case ObjCPropertyDecl::Assign: break;
3266 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003267 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003268 }
3269 }
3270
3271 // It really isn't clear at all what this means, since properties
3272 // are "dynamic by default".
3273 if (Dynamic)
3274 S += ",D";
3275
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003276 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3277 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003279 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3280 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003281 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003282 }
3283
3284 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3285 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003286 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003287 }
3288
3289 if (SynthesizePID) {
3290 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3291 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003292 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003293 }
3294
3295 // FIXME: OBJCGC: weak & strong
3296}
3297
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003298/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003299/// Another legacy compatibility encoding: 32-bit longs are encoded as
3300/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003301/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3302///
3303void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003304 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003305 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003306 if (BT->getKind() == BuiltinType::ULong &&
3307 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003308 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003309 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003310 if (BT->getKind() == BuiltinType::Long &&
3311 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003312 PointeeTy = IntTy;
3313 }
3314 }
3315}
3316
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003317void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003318 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003319 // We follow the behavior of gcc, expanding structures which are
3320 // directly pointed to, and expanding embedded structures. Note that
3321 // these rules are sufficient to prevent recursive encoding of the
3322 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003323 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003324 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003325}
3326
Mike Stump1eb44332009-09-09 15:08:12 +00003327static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003328 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003329 const Expr *E = FD->getBitWidth();
3330 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3331 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003332 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003333 S += 'b';
3334 S += llvm::utostr(N);
3335}
3336
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003337// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003338void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3339 bool ExpandPointedToStructures,
3340 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003341 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003342 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003343 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003344 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003345 if (FD && FD->isBitField())
3346 return EncodeBitField(this, S, FD);
3347 char encoding;
3348 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003349 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003350 case BuiltinType::Void: encoding = 'v'; break;
3351 case BuiltinType::Bool: encoding = 'B'; break;
3352 case BuiltinType::Char_U:
3353 case BuiltinType::UChar: encoding = 'C'; break;
3354 case BuiltinType::UShort: encoding = 'S'; break;
3355 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003356 case BuiltinType::ULong:
3357 encoding =
3358 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003359 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003360 case BuiltinType::UInt128: encoding = 'T'; break;
3361 case BuiltinType::ULongLong: encoding = 'Q'; break;
3362 case BuiltinType::Char_S:
3363 case BuiltinType::SChar: encoding = 'c'; break;
3364 case BuiltinType::Short: encoding = 's'; break;
3365 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003366 case BuiltinType::Long:
3367 encoding =
3368 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003369 break;
3370 case BuiltinType::LongLong: encoding = 'q'; break;
3371 case BuiltinType::Int128: encoding = 't'; break;
3372 case BuiltinType::Float: encoding = 'f'; break;
3373 case BuiltinType::Double: encoding = 'd'; break;
3374 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003375 }
Mike Stump1eb44332009-09-09 15:08:12 +00003376
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003377 S += encoding;
3378 return;
3379 }
Mike Stump1eb44332009-09-09 15:08:12 +00003380
John McCall183700f2009-09-21 23:43:11 +00003381 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003382 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003383 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003384 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003385 return;
3386 }
Mike Stump1eb44332009-09-09 15:08:12 +00003387
Ted Kremenek6217b802009-07-29 21:53:49 +00003388 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003389 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003390 bool isReadOnly = false;
3391 // For historical/compatibility reasons, the read-only qualifier of the
3392 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3393 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003394 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003395 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003396 if (OutermostType && T.isConstQualified()) {
3397 isReadOnly = true;
3398 S += 'r';
3399 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003400 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003401 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003402 while (P->getAs<PointerType>())
3403 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003404 if (P.isConstQualified()) {
3405 isReadOnly = true;
3406 S += 'r';
3407 }
3408 }
3409 if (isReadOnly) {
3410 // Another legacy compatibility encoding. Some ObjC qualifier and type
3411 // combinations need to be rearranged.
3412 // Rewrite "in const" from "nr" to "rn"
3413 const char * s = S.c_str();
3414 int len = S.length();
3415 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3416 std::string replace = "rn";
3417 S.replace(S.end()-2, S.end(), replace);
3418 }
3419 }
Steve Naroff14108da2009-07-10 23:34:53 +00003420 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003421 S += ':';
3422 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003423 }
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003425 if (PointeeTy->isCharType()) {
3426 // char pointer types should be encoded as '*' unless it is a
3427 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003428 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003429 S += '*';
3430 return;
3431 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003432 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003433 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3434 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3435 S += '#';
3436 return;
3437 }
3438 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3439 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3440 S += '@';
3441 return;
3442 }
3443 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003444 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003445 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003446 getLegacyIntegralTypeEncoding(PointeeTy);
3447
Mike Stump1eb44332009-09-09 15:08:12 +00003448 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003449 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003450 return;
3451 }
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003453 if (const ArrayType *AT =
3454 // Ignore type qualifiers etc.
3455 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003456 if (isa<IncompleteArrayType>(AT)) {
3457 // Incomplete arrays are encoded as a pointer to the array element.
3458 S += '^';
3459
Mike Stump1eb44332009-09-09 15:08:12 +00003460 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003461 false, ExpandStructures, FD);
3462 } else {
3463 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Anders Carlsson559a8332009-02-22 01:38:57 +00003465 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3466 S += llvm::utostr(CAT->getSize().getZExtValue());
3467 else {
3468 //Variable length arrays are encoded as a regular array with 0 elements.
3469 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3470 S += '0';
3471 }
Mike Stump1eb44332009-09-09 15:08:12 +00003472
3473 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003474 false, ExpandStructures, FD);
3475 S += ']';
3476 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003477 return;
3478 }
Mike Stump1eb44332009-09-09 15:08:12 +00003479
John McCall183700f2009-09-21 23:43:11 +00003480 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003481 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003482 return;
3483 }
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Ted Kremenek6217b802009-07-29 21:53:49 +00003485 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003486 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003487 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003488 // Anonymous structures print as '?'
3489 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3490 S += II->getName();
3491 } else {
3492 S += '?';
3493 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003494 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003495 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003496 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3497 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003498 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003499 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003500 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003501 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003502 S += '"';
3503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003505 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003506 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003507 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003508 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003509 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003510 QualType qt = Field->getType();
3511 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003512 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003513 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003514 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003515 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003516 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003517 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003518 return;
3519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003521 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003522 if (FD && FD->isBitField())
3523 EncodeBitField(this, S, FD);
3524 else
3525 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003526 return;
3527 }
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003529 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003530 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003531 return;
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
John McCall0953e762009-09-24 19:53:00 +00003534 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003535 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003536 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003537 S += '{';
3538 const IdentifierInfo *II = OI->getIdentifier();
3539 S += II->getName();
3540 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003541 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003542 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003543 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003544 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003545 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003546 RecFields[i]);
3547 else
Mike Stump1eb44332009-09-09 15:08:12 +00003548 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003549 FD);
3550 }
3551 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003552 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003553 }
Mike Stump1eb44332009-09-09 15:08:12 +00003554
John McCall183700f2009-09-21 23:43:11 +00003555 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003556 if (OPT->isObjCIdType()) {
3557 S += '@';
3558 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Steve Naroff27d20a22009-10-28 22:03:49 +00003561 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3562 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3563 // Since this is a binary compatibility issue, need to consult with runtime
3564 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003565 S += '#';
3566 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003567 }
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003569 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003570 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003571 ExpandPointedToStructures,
3572 ExpandStructures, FD);
3573 if (FD || EncodingProperty) {
3574 // Note that we do extended encoding of protocol qualifer list
3575 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003576 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003577 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3578 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003579 S += '<';
3580 S += (*I)->getNameAsString();
3581 S += '>';
3582 }
3583 S += '"';
3584 }
3585 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003586 }
Mike Stump1eb44332009-09-09 15:08:12 +00003587
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003588 QualType PointeeTy = OPT->getPointeeType();
3589 if (!EncodingProperty &&
3590 isa<TypedefType>(PointeeTy.getTypePtr())) {
3591 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003592 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003593 // {...};
3594 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003595 getObjCEncodingForTypeImpl(PointeeTy, S,
3596 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003597 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003598 return;
3599 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003600
3601 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003602 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003603 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003604 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003605 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3606 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003607 S += '<';
3608 S += (*I)->getNameAsString();
3609 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003610 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003611 S += '"';
3612 }
3613 return;
3614 }
Mike Stump1eb44332009-09-09 15:08:12 +00003615
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003616 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003617}
3618
Mike Stump1eb44332009-09-09 15:08:12 +00003619void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003620 std::string& S) const {
3621 if (QT & Decl::OBJC_TQ_In)
3622 S += 'n';
3623 if (QT & Decl::OBJC_TQ_Inout)
3624 S += 'N';
3625 if (QT & Decl::OBJC_TQ_Out)
3626 S += 'o';
3627 if (QT & Decl::OBJC_TQ_Bycopy)
3628 S += 'O';
3629 if (QT & Decl::OBJC_TQ_Byref)
3630 S += 'R';
3631 if (QT & Decl::OBJC_TQ_Oneway)
3632 S += 'V';
3633}
3634
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003635void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003636 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003637
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003638 BuiltinVaListType = T;
3639}
3640
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003641void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003642 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003643}
3644
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003645void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003646 ObjCSelType = T;
3647
John McCall183700f2009-09-21 23:43:11 +00003648 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003649 if (!TT)
3650 return;
3651 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003652
3653 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003654 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003655 if (!ptr)
3656 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003657 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003658 if (!rec)
3659 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003660 SelStructType = rec;
3661}
3662
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003663void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003664 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003665}
3666
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003667void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003668 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003669}
3670
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003671void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003672 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003673 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003675 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003676}
3677
Douglas Gregor7532dc62009-03-30 22:58:21 +00003678/// \brief Retrieve the template name that represents a qualified
3679/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003680TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003681 bool TemplateKeyword,
3682 TemplateDecl *Template) {
3683 llvm::FoldingSetNodeID ID;
3684 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3685
3686 void *InsertPos = 0;
3687 QualifiedTemplateName *QTN =
3688 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3689 if (!QTN) {
3690 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3691 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3692 }
3693
3694 return TemplateName(QTN);
3695}
3696
Douglas Gregord99cbe62009-07-29 18:26:50 +00003697/// \brief Retrieve the template name that represents a qualified
3698/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003699TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003700 bool TemplateKeyword,
3701 OverloadedFunctionDecl *Template) {
3702 llvm::FoldingSetNodeID ID;
3703 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Douglas Gregord99cbe62009-07-29 18:26:50 +00003705 void *InsertPos = 0;
3706 QualifiedTemplateName *QTN =
3707 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3708 if (!QTN) {
3709 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3710 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3711 }
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Douglas Gregord99cbe62009-07-29 18:26:50 +00003713 return TemplateName(QTN);
3714}
3715
Douglas Gregor7532dc62009-03-30 22:58:21 +00003716/// \brief Retrieve the template name that represents a dependent
3717/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003718TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003719 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003720 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003721 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003722
3723 llvm::FoldingSetNodeID ID;
3724 DependentTemplateName::Profile(ID, NNS, Name);
3725
3726 void *InsertPos = 0;
3727 DependentTemplateName *QTN =
3728 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3729
3730 if (QTN)
3731 return TemplateName(QTN);
3732
3733 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3734 if (CanonNNS == NNS) {
3735 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3736 } else {
3737 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3738 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3739 }
3740
3741 DependentTemplateNames.InsertNode(QTN, InsertPos);
3742 return TemplateName(QTN);
3743}
3744
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003745/// \brief Retrieve the template name that represents a dependent
3746/// template name such as \c MetaFun::template operator+.
3747TemplateName
3748ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3749 OverloadedOperatorKind Operator) {
3750 assert((!NNS || NNS->isDependent()) &&
3751 "Nested name specifier must be dependent");
3752
3753 llvm::FoldingSetNodeID ID;
3754 DependentTemplateName::Profile(ID, NNS, Operator);
3755
3756 void *InsertPos = 0;
3757 DependentTemplateName *QTN =
3758 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3759
3760 if (QTN)
3761 return TemplateName(QTN);
3762
3763 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3764 if (CanonNNS == NNS) {
3765 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3766 } else {
3767 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3768 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3769 }
3770
3771 DependentTemplateNames.InsertNode(QTN, InsertPos);
3772 return TemplateName(QTN);
3773}
3774
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003775/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003776/// TargetInfo, produce the corresponding type. The unsigned @p Type
3777/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003778CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003779 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003780 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003781 case TargetInfo::SignedShort: return ShortTy;
3782 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3783 case TargetInfo::SignedInt: return IntTy;
3784 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3785 case TargetInfo::SignedLong: return LongTy;
3786 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3787 case TargetInfo::SignedLongLong: return LongLongTy;
3788 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3789 }
3790
3791 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003792 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003793}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003794
3795//===----------------------------------------------------------------------===//
3796// Type Predicates.
3797//===----------------------------------------------------------------------===//
3798
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003799/// isObjCNSObjectType - Return true if this is an NSObject object using
3800/// NSObject attribute on a c-style pointer type.
3801/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003802/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003803///
3804bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3805 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3806 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003807 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003808 return true;
3809 }
Mike Stump1eb44332009-09-09 15:08:12 +00003810 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003811}
3812
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003813/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3814/// garbage collection attribute.
3815///
John McCall0953e762009-09-24 19:53:00 +00003816Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3817 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003818 if (getLangOptions().ObjC1 &&
3819 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003820 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003821 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003822 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003823 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003824 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003825 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003826 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003827 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003828 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003829 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003830 // Non-pointers have none gc'able attribute regardless of the attribute
3831 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003832 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003833 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003834 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003835 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003836}
3837
Chris Lattner6ac46a42008-04-07 06:51:04 +00003838//===----------------------------------------------------------------------===//
3839// Type Compatibility Testing
3840//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003841
Mike Stump1eb44332009-09-09 15:08:12 +00003842/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003843/// compatible.
3844static bool areCompatVectorTypes(const VectorType *LHS,
3845 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003846 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003847 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003848 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003849}
3850
Steve Naroff4084c302009-07-23 01:01:38 +00003851//===----------------------------------------------------------------------===//
3852// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3853//===----------------------------------------------------------------------===//
3854
3855/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3856/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003857bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3858 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003859 if (lProto == rProto)
3860 return true;
3861 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3862 E = rProto->protocol_end(); PI != E; ++PI)
3863 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3864 return true;
3865 return false;
3866}
3867
Steve Naroff4084c302009-07-23 01:01:38 +00003868/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3869/// return true if lhs's protocols conform to rhs's protocol; false
3870/// otherwise.
3871bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3872 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3873 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3874 return false;
3875}
3876
3877/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3878/// ObjCQualifiedIDType.
3879bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3880 bool compare) {
3881 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003882 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003883 lhs->isObjCIdType() || lhs->isObjCClassType())
3884 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003885 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003886 rhs->isObjCIdType() || rhs->isObjCClassType())
3887 return true;
3888
3889 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003890 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Steve Naroff4084c302009-07-23 01:01:38 +00003892 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Steve Naroff4084c302009-07-23 01:01:38 +00003894 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003895 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003896 // make sure we check the class hierarchy.
3897 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3898 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3899 E = lhsQID->qual_end(); I != E; ++I) {
3900 // when comparing an id<P> on lhs with a static type on rhs,
3901 // see if static class implements all of id's protocols, directly or
3902 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003903 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003904 return false;
3905 }
3906 }
3907 // If there are no qualifiers and no interface, we have an 'id'.
3908 return true;
3909 }
Mike Stump1eb44332009-09-09 15:08:12 +00003910 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003911 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3912 E = lhsQID->qual_end(); I != E; ++I) {
3913 ObjCProtocolDecl *lhsProto = *I;
3914 bool match = false;
3915
3916 // when comparing an id<P> on lhs with a static type on rhs,
3917 // see if static class implements all of id's protocols, directly or
3918 // through its super class and categories.
3919 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3920 E = rhsOPT->qual_end(); J != E; ++J) {
3921 ObjCProtocolDecl *rhsProto = *J;
3922 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3923 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3924 match = true;
3925 break;
3926 }
3927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003929 // make sure we check the class hierarchy.
3930 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3931 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3932 E = lhsQID->qual_end(); I != E; ++I) {
3933 // when comparing an id<P> on lhs with a static type on rhs,
3934 // see if static class implements all of id's protocols, directly or
3935 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003936 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003937 match = true;
3938 break;
3939 }
3940 }
3941 }
3942 if (!match)
3943 return false;
3944 }
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Steve Naroff4084c302009-07-23 01:01:38 +00003946 return true;
3947 }
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Steve Naroff4084c302009-07-23 01:01:38 +00003949 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3950 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3951
Mike Stump1eb44332009-09-09 15:08:12 +00003952 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003953 lhs->getAsObjCInterfacePointerType()) {
3954 if (lhsOPT->qual_empty()) {
3955 bool match = false;
3956 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3957 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3958 E = rhsQID->qual_end(); I != E; ++I) {
3959 // when comparing an id<P> on lhs with a static type on rhs,
3960 // see if static class implements all of id's protocols, directly or
3961 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003962 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003963 match = true;
3964 break;
3965 }
3966 }
3967 if (!match)
3968 return false;
3969 }
3970 return true;
3971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003973 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3974 E = lhsOPT->qual_end(); I != E; ++I) {
3975 ObjCProtocolDecl *lhsProto = *I;
3976 bool match = false;
3977
3978 // when comparing an id<P> on lhs with a static type on rhs,
3979 // see if static class implements all of id's protocols, directly or
3980 // through its super class and categories.
3981 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3982 E = rhsQID->qual_end(); J != E; ++J) {
3983 ObjCProtocolDecl *rhsProto = *J;
3984 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3985 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3986 match = true;
3987 break;
3988 }
3989 }
3990 if (!match)
3991 return false;
3992 }
3993 return true;
3994 }
3995 return false;
3996}
3997
Eli Friedman3d815e72008-08-22 00:56:42 +00003998/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003999/// compatible for assignment from RHS to LHS. This handles validation of any
4000/// protocol qualifiers on the LHS or RHS.
4001///
Steve Naroff14108da2009-07-10 23:34:53 +00004002bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4003 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004004 // If either type represents the built-in 'id' or 'Class' types, return true.
4005 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004006 return true;
4007
Steve Naroff4084c302009-07-23 01:01:38 +00004008 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004009 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4010 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004011 false);
4012
Steve Naroff14108da2009-07-10 23:34:53 +00004013 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4014 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004015 if (LHS && RHS) // We have 2 user-defined types.
4016 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Steve Naroff4084c302009-07-23 01:01:38 +00004018 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004019}
4020
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004021/// getIntersectionOfProtocols - This routine finds the intersection of set
4022/// of protocols inherited from two distinct objective-c pointer objects.
4023/// It is used to build composite qualifier list of the composite type of
4024/// the conditional expression involving two objective-c pointer objects.
4025static
4026void getIntersectionOfProtocols(ASTContext &Context,
4027 const ObjCObjectPointerType *LHSOPT,
4028 const ObjCObjectPointerType *RHSOPT,
4029 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4030
4031 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4032 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4033
4034 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4035 unsigned LHSNumProtocols = LHS->getNumProtocols();
4036 if (LHSNumProtocols > 0)
4037 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4038 else {
4039 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4040 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4041 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4042 LHSInheritedProtocols.end());
4043 }
4044
4045 unsigned RHSNumProtocols = RHS->getNumProtocols();
4046 if (RHSNumProtocols > 0) {
4047 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4048 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4049 if (InheritedProtocolSet.count(RHSProtocols[i]))
4050 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4051 }
4052 else {
4053 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4054 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4055 // FIXME. This may cause duplication of protocols in the list, but should
4056 // be harmless.
4057 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4058 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4059 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4060 }
4061}
4062
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004063/// areCommonBaseCompatible - Returns common base class of the two classes if
4064/// one found. Note that this is O'2 algorithm. But it will be called as the
4065/// last type comparison in a ?-exp of ObjC pointer types before a
4066/// warning is issued. So, its invokation is extremely rare.
4067QualType ASTContext::areCommonBaseCompatible(
4068 const ObjCObjectPointerType *LHSOPT,
4069 const ObjCObjectPointerType *RHSOPT) {
4070 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4071 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4072 if (!LHS || !RHS)
4073 return QualType();
4074
4075 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4076 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4077 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004078 if (canAssignObjCInterfaces(LHS, RHS)) {
4079 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4080 getIntersectionOfProtocols(*this,
4081 LHSOPT, RHSOPT, IntersectionOfProtocols);
4082 if (IntersectionOfProtocols.empty())
4083 LHSTy = getObjCObjectPointerType(LHSTy);
4084 else
4085 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4086 IntersectionOfProtocols.size());
4087 return LHSTy;
4088 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004089 }
4090
4091 return QualType();
4092}
4093
Eli Friedman3d815e72008-08-22 00:56:42 +00004094bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4095 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004096 // Verify that the base decls are compatible: the RHS must be a subclass of
4097 // the LHS.
4098 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4099 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Chris Lattner6ac46a42008-04-07 06:51:04 +00004101 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4102 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004103 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004104 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004105
Chris Lattner6ac46a42008-04-07 06:51:04 +00004106 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4107 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004108 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004109 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004111 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4112 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004113 LHSPI != LHSPE; LHSPI++) {
4114 bool RHSImplementsProtocol = false;
4115
4116 // If the RHS doesn't implement the protocol on the left, the types
4117 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004118 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004119 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004120 RHSPI != RHSPE; RHSPI++) {
4121 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004122 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004123 break;
4124 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004125 }
4126 // FIXME: For better diagnostics, consider passing back the protocol name.
4127 if (!RHSImplementsProtocol)
4128 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004129 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004130 // The RHS implements all protocols listed on the LHS.
4131 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004132}
4133
Steve Naroff389bf462009-02-12 17:52:19 +00004134bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4135 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004136 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4137 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Steve Naroff14108da2009-07-10 23:34:53 +00004139 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004140 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004141
4142 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4143 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004144}
4145
Mike Stump1eb44332009-09-09 15:08:12 +00004146/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004147/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004148/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004149/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004150bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4151 return !mergeTypes(LHS, RHS).isNull();
4152}
4153
4154QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004155 const FunctionType *lbase = lhs->getAs<FunctionType>();
4156 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004157 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4158 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004159 bool allLTypes = true;
4160 bool allRTypes = true;
4161
4162 // Check return type
4163 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4164 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004165 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4166 allLTypes = false;
4167 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4168 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004169 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004170 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4171 if (NoReturn != lbase->getNoReturnAttr())
4172 allLTypes = false;
4173 if (NoReturn != rbase->getNoReturnAttr())
4174 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004175
Eli Friedman3d815e72008-08-22 00:56:42 +00004176 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004177 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4178 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004179 unsigned lproto_nargs = lproto->getNumArgs();
4180 unsigned rproto_nargs = rproto->getNumArgs();
4181
4182 // Compatible functions must have the same number of arguments
4183 if (lproto_nargs != rproto_nargs)
4184 return QualType();
4185
4186 // Variadic and non-variadic functions aren't compatible
4187 if (lproto->isVariadic() != rproto->isVariadic())
4188 return QualType();
4189
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004190 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4191 return QualType();
4192
Eli Friedman3d815e72008-08-22 00:56:42 +00004193 // Check argument compatibility
4194 llvm::SmallVector<QualType, 10> types;
4195 for (unsigned i = 0; i < lproto_nargs; i++) {
4196 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4197 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4198 QualType argtype = mergeTypes(largtype, rargtype);
4199 if (argtype.isNull()) return QualType();
4200 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004201 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4202 allLTypes = false;
4203 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4204 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004205 }
4206 if (allLTypes) return lhs;
4207 if (allRTypes) return rhs;
4208 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004209 lproto->isVariadic(), lproto->getTypeQuals(),
4210 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004211 }
4212
4213 if (lproto) allRTypes = false;
4214 if (rproto) allLTypes = false;
4215
Douglas Gregor72564e72009-02-26 23:50:07 +00004216 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004217 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004218 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004219 if (proto->isVariadic()) return QualType();
4220 // Check that the types are compatible with the types that
4221 // would result from default argument promotions (C99 6.7.5.3p15).
4222 // The only types actually affected are promotable integer
4223 // types and floats, which would be passed as a different
4224 // type depending on whether the prototype is visible.
4225 unsigned proto_nargs = proto->getNumArgs();
4226 for (unsigned i = 0; i < proto_nargs; ++i) {
4227 QualType argTy = proto->getArgType(i);
4228 if (argTy->isPromotableIntegerType() ||
4229 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4230 return QualType();
4231 }
4232
4233 if (allLTypes) return lhs;
4234 if (allRTypes) return rhs;
4235 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004236 proto->getNumArgs(), proto->isVariadic(),
4237 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004238 }
4239
4240 if (allLTypes) return lhs;
4241 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004242 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004243}
4244
4245QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004246 // C++ [expr]: If an expression initially has the type "reference to T", the
4247 // type is adjusted to "T" prior to any further analysis, the expression
4248 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004249 // expression is an lvalue unless the reference is an rvalue reference and
4250 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004251 // FIXME: C++ shouldn't be going through here! The rules are different
4252 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004253 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4254 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004255 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004256 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004257 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004258 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004259
Eli Friedman3d815e72008-08-22 00:56:42 +00004260 QualType LHSCan = getCanonicalType(LHS),
4261 RHSCan = getCanonicalType(RHS);
4262
4263 // If two types are identical, they are compatible.
4264 if (LHSCan == RHSCan)
4265 return LHS;
4266
John McCall0953e762009-09-24 19:53:00 +00004267 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004268 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4269 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004270 if (LQuals != RQuals) {
4271 // If any of these qualifiers are different, we have a type
4272 // mismatch.
4273 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4274 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4275 return QualType();
4276
4277 // Exactly one GC qualifier difference is allowed: __strong is
4278 // okay if the other type has no GC qualifier but is an Objective
4279 // C object pointer (i.e. implicitly strong by default). We fix
4280 // this by pretending that the unqualified type was actually
4281 // qualified __strong.
4282 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4283 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4284 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4285
4286 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4287 return QualType();
4288
4289 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4290 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4291 }
4292 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4293 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4294 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004295 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004296 }
4297
4298 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004299
Eli Friedman852d63b2009-06-01 01:22:52 +00004300 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4301 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004302
Chris Lattner1adb8832008-01-14 05:45:46 +00004303 // We want to consider the two function types to be the same for these
4304 // comparisons, just force one to the other.
4305 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4306 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004307
4308 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004309 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4310 LHSClass = Type::ConstantArray;
4311 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4312 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Nate Begeman213541a2008-04-18 23:10:10 +00004314 // Canonicalize ExtVector -> Vector.
4315 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4316 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004317
Chris Lattnera36a61f2008-04-07 05:43:21 +00004318 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004319 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004320 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004321 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004322 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004323 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4324 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004325 }
John McCall183700f2009-09-21 23:43:11 +00004326 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004327 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4328 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004329 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004330
Eli Friedman3d815e72008-08-22 00:56:42 +00004331 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004332 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004333
Steve Naroff4a746782008-01-09 22:43:08 +00004334 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004335 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004336#define TYPE(Class, Base)
4337#define ABSTRACT_TYPE(Class, Base)
4338#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4339#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4340#include "clang/AST/TypeNodes.def"
4341 assert(false && "Non-canonical and dependent types shouldn't get here");
4342 return QualType();
4343
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004344 case Type::LValueReference:
4345 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004346 case Type::MemberPointer:
4347 assert(false && "C++ should never be in mergeTypes");
4348 return QualType();
4349
4350 case Type::IncompleteArray:
4351 case Type::VariableArray:
4352 case Type::FunctionProto:
4353 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004354 assert(false && "Types are eliminated above");
4355 return QualType();
4356
Chris Lattner1adb8832008-01-14 05:45:46 +00004357 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004358 {
4359 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004360 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4361 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004362 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4363 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004364 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004365 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004366 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004367 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004368 return getPointerType(ResultType);
4369 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004370 case Type::BlockPointer:
4371 {
4372 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004373 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4374 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004375 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4376 if (ResultType.isNull()) return QualType();
4377 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4378 return LHS;
4379 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4380 return RHS;
4381 return getBlockPointerType(ResultType);
4382 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004383 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004384 {
4385 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4386 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4387 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4388 return QualType();
4389
4390 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4391 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4392 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4393 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004394 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4395 return LHS;
4396 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4397 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004398 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4399 ArrayType::ArraySizeModifier(), 0);
4400 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4401 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004402 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4403 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004404 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4405 return LHS;
4406 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4407 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004408 if (LVAT) {
4409 // FIXME: This isn't correct! But tricky to implement because
4410 // the array's size has to be the size of LHS, but the type
4411 // has to be different.
4412 return LHS;
4413 }
4414 if (RVAT) {
4415 // FIXME: This isn't correct! But tricky to implement because
4416 // the array's size has to be the size of RHS, but the type
4417 // has to be different.
4418 return RHS;
4419 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004420 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4421 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004422 return getIncompleteArrayType(ResultType,
4423 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004424 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004425 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004426 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004427 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004428 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004429 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004430 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004431 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004432 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004433 case Type::Complex:
4434 // Distinct complex types are incompatible.
4435 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004436 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004437 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004438 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004439 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004440 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004441 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004442 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004443 // FIXME: This should be type compatibility, e.g. whether
4444 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004445 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4446 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004447 if (LHSIface && RHSIface &&
4448 canAssignObjCInterfaces(LHSIface, RHSIface))
4449 return LHS;
4450
Eli Friedman3d815e72008-08-22 00:56:42 +00004451 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004452 }
Steve Naroff14108da2009-07-10 23:34:53 +00004453 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004454 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4455 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004456 return LHS;
4457
Steve Naroffbc76dd02008-12-10 22:14:21 +00004458 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004459 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004460 case Type::FixedWidthInt:
4461 // Distinct fixed-width integers are not compatible.
4462 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004463 case Type::TemplateSpecialization:
4464 assert(false && "Dependent types have no size");
4465 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004466 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004467
4468 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004469}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004470
Chris Lattner5426bf62008-04-07 07:01:58 +00004471//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004472// Integer Predicates
4473//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004474
Eli Friedmanad74a752008-06-28 06:23:08 +00004475unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004476 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004477 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004478 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004479 return FWIT->getWidth();
4480 }
4481 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004482 return (unsigned)getTypeSize(T);
4483}
4484
4485QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4486 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004487
4488 // Turn <4 x signed int> -> <4 x unsigned int>
4489 if (const VectorType *VTy = T->getAs<VectorType>())
4490 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4491 VTy->getNumElements());
4492
4493 // For enums, we return the unsigned version of the base type.
4494 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004495 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004496
4497 const BuiltinType *BTy = T->getAs<BuiltinType>();
4498 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004499 switch (BTy->getKind()) {
4500 case BuiltinType::Char_S:
4501 case BuiltinType::SChar:
4502 return UnsignedCharTy;
4503 case BuiltinType::Short:
4504 return UnsignedShortTy;
4505 case BuiltinType::Int:
4506 return UnsignedIntTy;
4507 case BuiltinType::Long:
4508 return UnsignedLongTy;
4509 case BuiltinType::LongLong:
4510 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004511 case BuiltinType::Int128:
4512 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004513 default:
4514 assert(0 && "Unexpected signed integer type");
4515 return QualType();
4516 }
4517}
4518
Douglas Gregor2cf26342009-04-09 22:27:44 +00004519ExternalASTSource::~ExternalASTSource() { }
4520
4521void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004522
4523
4524//===----------------------------------------------------------------------===//
4525// Builtin Type Computation
4526//===----------------------------------------------------------------------===//
4527
4528/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4529/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004530static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004531 ASTContext::GetBuiltinTypeError &Error,
4532 bool AllowTypeModifiers = true) {
4533 // Modifiers.
4534 int HowLong = 0;
4535 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Chris Lattner86df27b2009-06-14 00:45:47 +00004537 // Read the modifiers first.
4538 bool Done = false;
4539 while (!Done) {
4540 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004541 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004542 case 'S':
4543 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4544 assert(!Signed && "Can't use 'S' modifier multiple times!");
4545 Signed = true;
4546 break;
4547 case 'U':
4548 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4549 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4550 Unsigned = true;
4551 break;
4552 case 'L':
4553 assert(HowLong <= 2 && "Can't have LLLL modifier");
4554 ++HowLong;
4555 break;
4556 }
4557 }
4558
4559 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Chris Lattner86df27b2009-06-14 00:45:47 +00004561 // Read the base type.
4562 switch (*Str++) {
4563 default: assert(0 && "Unknown builtin type letter!");
4564 case 'v':
4565 assert(HowLong == 0 && !Signed && !Unsigned &&
4566 "Bad modifiers used with 'v'!");
4567 Type = Context.VoidTy;
4568 break;
4569 case 'f':
4570 assert(HowLong == 0 && !Signed && !Unsigned &&
4571 "Bad modifiers used with 'f'!");
4572 Type = Context.FloatTy;
4573 break;
4574 case 'd':
4575 assert(HowLong < 2 && !Signed && !Unsigned &&
4576 "Bad modifiers used with 'd'!");
4577 if (HowLong)
4578 Type = Context.LongDoubleTy;
4579 else
4580 Type = Context.DoubleTy;
4581 break;
4582 case 's':
4583 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4584 if (Unsigned)
4585 Type = Context.UnsignedShortTy;
4586 else
4587 Type = Context.ShortTy;
4588 break;
4589 case 'i':
4590 if (HowLong == 3)
4591 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4592 else if (HowLong == 2)
4593 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4594 else if (HowLong == 1)
4595 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4596 else
4597 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4598 break;
4599 case 'c':
4600 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4601 if (Signed)
4602 Type = Context.SignedCharTy;
4603 else if (Unsigned)
4604 Type = Context.UnsignedCharTy;
4605 else
4606 Type = Context.CharTy;
4607 break;
4608 case 'b': // boolean
4609 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4610 Type = Context.BoolTy;
4611 break;
4612 case 'z': // size_t.
4613 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4614 Type = Context.getSizeType();
4615 break;
4616 case 'F':
4617 Type = Context.getCFConstantStringType();
4618 break;
4619 case 'a':
4620 Type = Context.getBuiltinVaListType();
4621 assert(!Type.isNull() && "builtin va list type not initialized!");
4622 break;
4623 case 'A':
4624 // This is a "reference" to a va_list; however, what exactly
4625 // this means depends on how va_list is defined. There are two
4626 // different kinds of va_list: ones passed by value, and ones
4627 // passed by reference. An example of a by-value va_list is
4628 // x86, where va_list is a char*. An example of by-ref va_list
4629 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4630 // we want this argument to be a char*&; for x86-64, we want
4631 // it to be a __va_list_tag*.
4632 Type = Context.getBuiltinVaListType();
4633 assert(!Type.isNull() && "builtin va list type not initialized!");
4634 if (Type->isArrayType()) {
4635 Type = Context.getArrayDecayedType(Type);
4636 } else {
4637 Type = Context.getLValueReferenceType(Type);
4638 }
4639 break;
4640 case 'V': {
4641 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004642 unsigned NumElements = strtoul(Str, &End, 10);
4643 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Chris Lattner86df27b2009-06-14 00:45:47 +00004645 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Chris Lattner86df27b2009-06-14 00:45:47 +00004647 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4648 Type = Context.getVectorType(ElementType, NumElements);
4649 break;
4650 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004651 case 'X': {
4652 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4653 Type = Context.getComplexType(ElementType);
4654 break;
4655 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004656 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004657 Type = Context.getFILEType();
4658 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004659 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004660 return QualType();
4661 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004662 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004663 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004664 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004665 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004666 else
4667 Type = Context.getjmp_bufType();
4668
Mike Stumpfd612db2009-07-28 23:47:15 +00004669 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004670 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004671 return QualType();
4672 }
4673 break;
Mike Stump782fa302009-07-28 02:25:19 +00004674 }
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Chris Lattner86df27b2009-06-14 00:45:47 +00004676 if (!AllowTypeModifiers)
4677 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Chris Lattner86df27b2009-06-14 00:45:47 +00004679 Done = false;
4680 while (!Done) {
4681 switch (*Str++) {
4682 default: Done = true; --Str; break;
4683 case '*':
4684 Type = Context.getPointerType(Type);
4685 break;
4686 case '&':
4687 Type = Context.getLValueReferenceType(Type);
4688 break;
4689 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4690 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004691 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004692 break;
4693 }
4694 }
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Chris Lattner86df27b2009-06-14 00:45:47 +00004696 return Type;
4697}
4698
4699/// GetBuiltinType - Return the type for the specified builtin.
4700QualType ASTContext::GetBuiltinType(unsigned id,
4701 GetBuiltinTypeError &Error) {
4702 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Chris Lattner86df27b2009-06-14 00:45:47 +00004704 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Chris Lattner86df27b2009-06-14 00:45:47 +00004706 Error = GE_None;
4707 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4708 if (Error != GE_None)
4709 return QualType();
4710 while (TypeStr[0] && TypeStr[0] != '.') {
4711 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4712 if (Error != GE_None)
4713 return QualType();
4714
4715 // Do array -> pointer decay. The builtin should use the decayed type.
4716 if (Ty->isArrayType())
4717 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Chris Lattner86df27b2009-06-14 00:45:47 +00004719 ArgTypes.push_back(Ty);
4720 }
4721
4722 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4723 "'.' should only occur at end of builtin type list!");
4724
4725 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4726 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4727 return getFunctionNoProtoType(ResType);
4728 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4729 TypeStr[0] == '.', 0);
4730}
Eli Friedmana95d7572009-08-19 07:44:53 +00004731
4732QualType
4733ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4734 // Perform the usual unary conversions. We do this early so that
4735 // integral promotions to "int" can allow us to exit early, in the
4736 // lhs == rhs check. Also, for conversion purposes, we ignore any
4737 // qualifiers. For example, "const float" and "float" are
4738 // equivalent.
4739 if (lhs->isPromotableIntegerType())
4740 lhs = getPromotedIntegerType(lhs);
4741 else
4742 lhs = lhs.getUnqualifiedType();
4743 if (rhs->isPromotableIntegerType())
4744 rhs = getPromotedIntegerType(rhs);
4745 else
4746 rhs = rhs.getUnqualifiedType();
4747
4748 // If both types are identical, no conversion is needed.
4749 if (lhs == rhs)
4750 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004751
Eli Friedmana95d7572009-08-19 07:44:53 +00004752 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4753 // The caller can deal with this (e.g. pointer + int).
4754 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4755 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004756
4757 // At this point, we have two different arithmetic types.
4758
Eli Friedmana95d7572009-08-19 07:44:53 +00004759 // Handle complex types first (C99 6.3.1.8p1).
4760 if (lhs->isComplexType() || rhs->isComplexType()) {
4761 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004762 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004763 // convert the rhs to the lhs complex type.
4764 return lhs;
4765 }
Mike Stump1eb44332009-09-09 15:08:12 +00004766 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004767 // convert the lhs to the rhs complex type.
4768 return rhs;
4769 }
4770 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004771 // When both operands are complex, the shorter operand is converted to the
4772 // type of the longer, and that is the type of the result. This corresponds
4773 // to what is done when combining two real floating-point operands.
4774 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004775 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004776 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004777 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004778 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004779 // "double _Complex" is promoted to "long double _Complex".
4780 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004781
4782 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004783 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004784 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004785 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004786 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004787 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4788 // domains match. This is a requirement for our implementation, C99
4789 // does not require this promotion.
4790 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4791 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4792 return rhs;
4793 } else { // handle "_Complex double, double".
4794 return lhs;
4795 }
4796 }
4797 return lhs; // The domain/size match exactly.
4798 }
4799 // Now handle "real" floating types (i.e. float, double, long double).
4800 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4801 // if we have an integer operand, the result is the real floating type.
4802 if (rhs->isIntegerType()) {
4803 // convert rhs to the lhs floating point type.
4804 return lhs;
4805 }
4806 if (rhs->isComplexIntegerType()) {
4807 // convert rhs to the complex floating point type.
4808 return getComplexType(lhs);
4809 }
4810 if (lhs->isIntegerType()) {
4811 // convert lhs to the rhs floating point type.
4812 return rhs;
4813 }
Mike Stump1eb44332009-09-09 15:08:12 +00004814 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004815 // convert lhs to the complex floating point type.
4816 return getComplexType(rhs);
4817 }
4818 // We have two real floating types, float/complex combos were handled above.
4819 // Convert the smaller operand to the bigger result.
4820 int result = getFloatingTypeOrder(lhs, rhs);
4821 if (result > 0) // convert the rhs
4822 return lhs;
4823 assert(result < 0 && "illegal float comparison");
4824 return rhs; // convert the lhs
4825 }
4826 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4827 // Handle GCC complex int extension.
4828 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4829 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4830
4831 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004832 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004833 rhsComplexInt->getElementType()) >= 0)
4834 return lhs; // convert the rhs
4835 return rhs;
4836 } else if (lhsComplexInt && rhs->isIntegerType()) {
4837 // convert the rhs to the lhs complex type.
4838 return lhs;
4839 } else if (rhsComplexInt && lhs->isIntegerType()) {
4840 // convert the lhs to the rhs complex type.
4841 return rhs;
4842 }
4843 }
4844 // Finally, we have two differing integer types.
4845 // The rules for this case are in C99 6.3.1.8
4846 int compare = getIntegerTypeOrder(lhs, rhs);
4847 bool lhsSigned = lhs->isSignedIntegerType(),
4848 rhsSigned = rhs->isSignedIntegerType();
4849 QualType destType;
4850 if (lhsSigned == rhsSigned) {
4851 // Same signedness; use the higher-ranked type
4852 destType = compare >= 0 ? lhs : rhs;
4853 } else if (compare != (lhsSigned ? 1 : -1)) {
4854 // The unsigned type has greater than or equal rank to the
4855 // signed type, so use the unsigned type
4856 destType = lhsSigned ? rhs : lhs;
4857 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4858 // The two types are different widths; if we are here, that
4859 // means the signed type is larger than the unsigned type, so
4860 // use the signed type.
4861 destType = lhsSigned ? lhs : rhs;
4862 } else {
4863 // The signed type is higher-ranked than the unsigned type,
4864 // but isn't actually any bigger (like unsigned int and long
4865 // on most 32-bit systems). Use the unsigned type corresponding
4866 // to the signed type.
4867 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4868 }
4869 return destType;
4870}