blob: 94f2fdcff9f920a6f9dcbdbb703d958dbc9b0886 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000025#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000026#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000027#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000028#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000029#include "RecordLayoutBuilder.h"
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
33enum FloatingRank {
34 FloatRank, DoubleRank, LongDoubleRank
35};
36
Chris Lattner61710852008-10-05 17:34:18 +000037ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000038 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000039 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000040 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000041 bool FreeMem, unsigned size_reserve) :
42 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000043 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000044 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
45 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000046 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000047 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000048 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000049 ObjCIdRedefinitionType = QualType();
50 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000051 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000052 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000053 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000054 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000055}
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057ASTContext::~ASTContext() {
58 // Deallocate all the types.
59 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000060 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000061 Types.pop_back();
62 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000063
Nuno Lopesb74668e2008-12-17 22:30:25 +000064 {
John McCall0953e762009-09-24 19:53:00 +000065 llvm::FoldingSet<ExtQuals>::iterator
66 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
67 while (I != E)
68 Deallocate(&*I++);
69 }
70
71 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000072 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
73 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
74 while (I != E) {
75 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
76 delete R;
77 }
78 }
79
80 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000081 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000083 while (I != E) {
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
86 }
87 }
88
Douglas Gregorab452ba2009-03-26 23:50:42 +000089 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000090 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
91 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000092 NNSEnd = NestedNameSpecifiers.end();
93 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 /* Increment in loop */)
95 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000263ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000265 = InstantiatedFromUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
John McCalled976492009-12-04 22:46:56 +0000273ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
274 assert((isa<UsingDecl>(Pattern) ||
275 isa<UnresolvedUsingValueDecl>(Pattern) ||
276 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277 "pattern decl is not a using decl");
278 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279 InstantiatedFromUsingDecl[Inst] = Pattern;
280}
281
282UsingShadowDecl *
283ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
284 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
285 = InstantiatedFromUsingShadowDecl.find(Inst);
286 if (Pos == InstantiatedFromUsingShadowDecl.end())
287 return 0;
288
289 return Pos->second;
290}
291
292void
293ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294 UsingShadowDecl *Pattern) {
295 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
296 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000297}
298
Anders Carlssond8b285f2009-09-01 04:26:58 +0000299FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301 = InstantiatedFromUnnamedFieldDecl.find(Field);
302 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Anders Carlssond8b285f2009-09-01 04:26:58 +0000305 return Pos->second;
306}
307
308void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309 FieldDecl *Tmpl) {
310 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
311 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316}
317
Douglas Gregor2e222532009-07-02 17:08:52 +0000318namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 : std::binary_function<SourceRange, SourceRange, bool> {
321 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Douglas Gregor2e222532009-07-02 17:08:52 +0000323 public:
324 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 bool operator()(SourceRange X, SourceRange Y) {
327 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328 }
329 };
330}
331
332/// \brief Determine whether the given comment is a Doxygen-style comment.
333///
334/// \param Start the start of the comment text.
335///
336/// \param End the end of the comment text.
337///
338/// \param Member whether we want to check whether this is a member comment
339/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
340/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000341static bool
342isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000343 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000345 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
346 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
347 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 if (End - Start < 4)
350 return false;
351
352 assert(Start[0] == '/' && "Not a comment?");
353 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
354 return false;
355 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
356 return false;
357
358 return (Start[3] == '<') == Member;
359}
360
361/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000362/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000363const char *ASTContext::getCommentForDecl(const Decl *D) {
364 if (!D)
365 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Douglas Gregor2e222532009-07-02 17:08:52 +0000367 // Check whether we have cached a comment string for this declaration
368 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000369 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000370 = DeclComments.find(D);
371 if (Pos != DeclComments.end())
372 return Pos->second.c_str();
373
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000375 // that source, do so now.
376 if (ExternalSource && !LoadedExternalComments) {
377 std::vector<SourceRange> LoadedComments;
378 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 if (!LoadedComments.empty())
381 Comments.insert(Comments.begin(), LoadedComments.begin(),
382 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 LoadedExternalComments = true;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
387 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 if (Comments.empty())
389 return 0;
390
391 // If the declaration doesn't map directly to a location in a file, we
392 // can't find the comment.
393 SourceLocation DeclStartLoc = D->getLocStart();
394 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
395 return 0;
396
397 // Find the comment that occurs just before this declaration.
398 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000399 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000400 SourceRange(DeclStartLoc),
401 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 // Decompose the location for the start of the declaration and find the
404 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000406 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000407 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 // First check whether we have a comment for a member.
411 if (LastComment != Comments.end() &&
412 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
413 isDoxygenComment(SourceMgr, *LastComment, true)) {
414 std::pair<FileID, unsigned> LastCommentEndDecomp
415 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
416 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000418 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000419 LastCommentEndDecomp.second)) {
420 // The Doxygen member comment comes after the declaration starts and
421 // is on the same line and in the same file as the declaration. This
422 // is the comment we want.
423 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000424 Result.append(FileBufferStart +
425 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000426 FileBufferStart + LastCommentEndDecomp.second + 1);
427 return Result.c_str();
428 }
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Douglas Gregor2e222532009-07-02 17:08:52 +0000431 if (LastComment == Comments.begin())
432 return 0;
433 --LastComment;
434
435 // Decompose the end of the comment.
436 std::pair<FileID, unsigned> LastCommentEndDecomp
437 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor2e222532009-07-02 17:08:52 +0000439 // If the comment and the declaration aren't in the same file, then they
440 // aren't related.
441 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
442 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor2e222532009-07-02 17:08:52 +0000444 // Check that we actually have a Doxygen comment.
445 if (!isDoxygenComment(SourceMgr, *LastComment))
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-07-02 17:08:52 +0000448 // Compute the starting line for the declaration and for the end of the
449 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000450 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000453 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-07-02 17:08:52 +0000456 // If the comment does not end on the line prior to the declaration, then
457 // the comment is not associated with the declaration at all.
458 if (CommentEndLine + 1 != DeclStartLine)
459 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Douglas Gregor2e222532009-07-02 17:08:52 +0000461 // We have a comment, but there may be more comments on the previous lines.
462 // Keep looking so long as the comments are still Doxygen comments and are
463 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000464 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000465 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
466 std::vector<SourceRange>::iterator FirstComment = LastComment;
467 while (FirstComment != Comments.begin()) {
468 // Look at the previous comment
469 --FirstComment;
470 std::pair<FileID, unsigned> Decomp
471 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor2e222532009-07-02 17:08:52 +0000473 // If this previous comment is in a different file, we're done.
474 if (Decomp.first != DeclStartDecomp.first) {
475 ++FirstComment;
476 break;
477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregor2e222532009-07-02 17:08:52 +0000479 // If this comment is not a Doxygen comment, we're done.
480 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
481 ++FirstComment;
482 break;
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor2e222532009-07-02 17:08:52 +0000485 // If the line number is not what we expected, we're done.
486 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
487 if (Line != ExpectedLine) {
488 ++FirstComment;
489 break;
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000493 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Douglas Gregor2e222532009-07-02 17:08:52 +0000497 // The iterator range [FirstComment, LastComment] contains all of the
498 // BCPL comments that, together, are associated with this declaration.
499 // Form a single comment block string for this declaration that concatenates
500 // all of these comments.
501 std::string &Result = DeclComments[D];
502 while (FirstComment != LastComment) {
503 std::pair<FileID, unsigned> DecompStart
504 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
505 std::pair<FileID, unsigned> DecompEnd
506 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
507 Result.append(FileBufferStart + DecompStart.second,
508 FileBufferStart + DecompEnd.second + 1);
509 ++FirstComment;
510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor2e222532009-07-02 17:08:52 +0000512 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 Result.append(FileBufferStart +
514 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 FileBufferStart + LastCommentEndDecomp.second + 1);
516 return Result.c_str();
517}
518
Chris Lattner464175b2007-07-18 17:52:12 +0000519//===----------------------------------------------------------------------===//
520// Type Sizing and Analysis
521//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000522
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000523/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
524/// scalar floating point type.
525const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000526 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527 assert(BT && "Not a floating point type!");
528 switch (BT->getKind()) {
529 default: assert(0 && "Not a floating point type!");
530 case BuiltinType::Float: return Target.getFloatFormat();
531 case BuiltinType::Double: return Target.getDoubleFormat();
532 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
533 }
534}
535
Mike Stump196efbf2009-09-22 02:43:44 +0000536/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537/// specified decl. Note that bitfields do not have a valid alignment, so
538/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000539/// If @p RefAsPointee, references are treated like their underlying type
540/// (for alignof), else they're treated like pointers (for CodeGen).
541unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000542 unsigned Align = Target.getCharWidth();
543
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000544 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000545 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546
Chris Lattneraf707ab2009-01-24 21:53:27 +0000547 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000549 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000550 if (RefAsPointee)
551 T = RT->getPointeeType();
552 else
553 T = getPointerType(RT->getPointeeType());
554 }
555 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000557 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558 T = cast<ArrayType>(T)->getElementType();
559
560 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000562 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000563
564 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000565}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000566
Chris Lattnera7674d82007-07-13 22:13:22 +0000567/// getTypeSize - Return the size of the specified type, in bits. This method
568/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000569///
570/// FIXME: Pointers into different addr spaces could have different sizes and
571/// alignment requirements: getPointerInfo should take an AddrSpace, this
572/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000573std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000574ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000575 uint64_t Width=0;
576 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000577 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000578#define TYPE(Class, Base)
579#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000580#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000583 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000584 break;
585
Chris Lattner692233e2007-07-13 22:27:08 +0000586 case Type::FunctionNoProto:
587 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000588 // GCC extension: alignof(function) = 32 bits
589 Width = 0;
590 Align = 32;
591 break;
592
Douglas Gregor72564e72009-02-26 23:50:07 +0000593 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000594 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000595 Width = 0;
596 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597 break;
598
Steve Narofffb22d962007-08-30 01:06:46 +0000599 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000600 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner98be4942008-03-05 18:54:05 +0000602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000603 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000604 Align = EltInfo.second;
605 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000606 }
Nate Begeman213541a2008-04-18 23:10:10 +0000607 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000608 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000609 const VectorType *VT = cast<VectorType>(T);
610 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
611 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000612 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000613 // If the alignment is not a power of 2, round up to the next power of 2.
614 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000615 if (VT->getNumElements() & (VT->getNumElements()-1)) {
616 Align = llvm::NextPowerOf2(Align);
617 Width = llvm::RoundUpToAlignment(Width, Align);
618 }
Chris Lattner030d8842007-07-19 22:06:24 +0000619 break;
620 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000621
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000623 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000624 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000625 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000626 // GCC extension: alignof(void) = 8 bits.
627 Width = 0;
628 Align = 8;
629 break;
630
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getBoolWidth();
633 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::Char_S:
636 case BuiltinType::Char_U:
637 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getCharWidth();
640 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000642 case BuiltinType::WChar:
643 Width = Target.getWCharWidth();
644 Align = Target.getWCharAlign();
645 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000646 case BuiltinType::Char16:
647 Width = Target.getChar16Width();
648 Align = Target.getChar16Align();
649 break;
650 case BuiltinType::Char32:
651 Width = Target.getChar32Width();
652 Align = Target.getChar32Align();
653 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000654 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getShortWidth();
657 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000659 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000660 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000661 Width = Target.getIntWidth();
662 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000664 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000666 Width = Target.getLongWidth();
667 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000669 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000671 Width = Target.getLongLongWidth();
672 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000674 case BuiltinType::Int128:
675 case BuiltinType::UInt128:
676 Width = 128;
677 Align = 128; // int128_t is 128-bit aligned on all targets.
678 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000680 Width = Target.getFloatWidth();
681 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 break;
683 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000684 Width = Target.getDoubleWidth();
685 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 Width = Target.getLongDoubleWidth();
689 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000691 case BuiltinType::NullPtr:
692 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
693 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000694 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000695 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000696 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000697 case Type::FixedWidthInt:
698 // FIXME: This isn't precisely correct; the width/alignment should depend
699 // on the available types for the target
700 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000701 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000702 Align = Width;
703 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000704 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000705 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000706 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000708 case Type::BlockPointer: {
709 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
710 Width = Target.getPointerWidth(AS);
711 Align = Target.getPointerAlign(AS);
712 break;
713 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000714 case Type::LValueReference:
715 case Type::RValueReference: {
716 // alignof and sizeof should never enter this code path here, so we go
717 // the pointer route.
718 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
719 Width = Target.getPointerWidth(AS);
720 Align = Target.getPointerAlign(AS);
721 break;
722 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 case Type::Pointer: {
724 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000725 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000726 Align = Target.getPointerAlign(AS);
727 break;
728 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000729 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000730 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
731 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
732 // If we ever want to support other ABIs this needs to be abstracted.
733
Sebastian Redlf30208a2009-01-24 21:16:55 +0000734 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000735 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000736 getTypeInfo(getPointerDiffType());
737 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000738 if (Pointee->isFunctionType())
739 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000740 Align = PtrDiffInfo.second;
741 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000742 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000743 case Type::Complex: {
744 // Complex types have the same alignment as their elements, but twice the
745 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000746 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000747 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000748 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000749 Align = EltInfo.second;
750 break;
751 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000752 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000753 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000754 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
755 Width = Layout.getSize();
756 Align = Layout.getAlignment();
757 break;
758 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000759 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000760 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000761 const TagType *TT = cast<TagType>(T);
762
763 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000764 Width = 1;
765 Align = 1;
766 break;
767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Daniel Dunbar1d751182008-11-08 05:48:37 +0000769 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000770 return getTypeInfo(ET->getDecl()->getIntegerType());
771
Daniel Dunbar1d751182008-11-08 05:48:37 +0000772 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000773 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
774 Width = Layout.getSize();
775 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000776 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000777 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000778
Chris Lattner9fcfe922009-10-22 05:17:15 +0000779 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000780 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
781 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000782
Chris Lattner9fcfe922009-10-22 05:17:15 +0000783 case Type::Elaborated:
784 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
785 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000786
Douglas Gregor18857642009-04-30 17:32:17 +0000787 case Type::Typedef: {
788 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000789 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000790 Align = std::max(Aligned->getMaxAlignment(),
791 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000792 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
793 } else
794 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000795 break;
Chris Lattner71763312008-04-06 22:05:18 +0000796 }
Douglas Gregor18857642009-04-30 17:32:17 +0000797
798 case Type::TypeOfExpr:
799 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
800 .getTypePtr());
801
802 case Type::TypeOf:
803 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
804
Anders Carlsson395b4752009-06-24 19:06:50 +0000805 case Type::Decltype:
806 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
807 .getTypePtr());
808
Douglas Gregor18857642009-04-30 17:32:17 +0000809 case Type::QualifiedName:
810 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Douglas Gregor18857642009-04-30 17:32:17 +0000812 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000813 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000814 "Cannot request the size of a dependent type");
815 // FIXME: this is likely to be wrong once we support template
816 // aliases, since a template alias could refer to a typedef that
817 // has an __aligned__ attribute on it.
818 return getTypeInfo(getCanonicalType(T));
819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner464175b2007-07-18 17:52:12 +0000821 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000822 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000823}
824
Chris Lattner34ebde42009-01-27 18:08:34 +0000825/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
826/// type for the current target in bits. This can be different than the ABI
827/// alignment in cases where it is beneficial for performance to overalign
828/// a data type.
829unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
830 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000831
832 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000833 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000834 T = CT->getElementType().getTypePtr();
835 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
836 T->isSpecificBuiltinType(BuiltinType::LongLong))
837 return std::max(ABIAlign, (unsigned)getTypeSize(T));
838
Chris Lattner34ebde42009-01-27 18:08:34 +0000839 return ABIAlign;
840}
841
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000842static void CollectLocalObjCIvars(ASTContext *Ctx,
843 const ObjCInterfaceDecl *OI,
844 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000845 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
846 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000847 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000848 if (!IVDecl->isInvalidDecl())
849 Fields.push_back(cast<FieldDecl>(IVDecl));
850 }
851}
852
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000853void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
854 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
855 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
856 CollectObjCIvars(SuperClass, Fields);
857 CollectLocalObjCIvars(this, OI, Fields);
858}
859
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000860/// ShallowCollectObjCIvars -
861/// Collect all ivars, including those synthesized, in the current class.
862///
863void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
864 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
865 bool CollectSynthesized) {
866 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
867 E = OI->ivar_end(); I != E; ++I) {
868 Ivars.push_back(*I);
869 }
870 if (CollectSynthesized)
871 CollectSynthesizedIvars(OI, Ivars);
872}
873
Fariborz Jahanian98200742009-05-12 18:14:29 +0000874void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000876 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
877 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000878 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
879 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Fariborz Jahanian98200742009-05-12 18:14:29 +0000881 // Also look into nested protocols.
882 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
883 E = PD->protocol_end(); P != E; ++P)
884 CollectProtocolSynthesizedIvars(*P, Ivars);
885}
886
887/// CollectSynthesizedIvars -
888/// This routine collect synthesized ivars for the designated class.
889///
890void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
891 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000892 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
893 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000894 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
895 Ivars.push_back(Ivar);
896 }
897 // Also look into interface's protocol list for properties declared
898 // in the protocol and whose ivars are synthesized.
899 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
900 PE = OI->protocol_end(); P != PE; ++P) {
901 ObjCProtocolDecl *PD = (*P);
902 CollectProtocolSynthesizedIvars(PD, Ivars);
903 }
904}
905
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000906/// CollectInheritedProtocols - Collect all protocols in current class and
907/// those inherited by it.
908void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
909 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
910 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
911 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
912 PE = OI->protocol_end(); P != PE; ++P) {
913 ObjCProtocolDecl *Proto = (*P);
914 Protocols.push_back(Proto);
915 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
916 PE = Proto->protocol_end(); P != PE; ++P)
917 CollectInheritedProtocols(*P, Protocols);
918 }
919
920 // Categories of this Interface.
921 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
922 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
923 CollectInheritedProtocols(CDeclChain, Protocols);
924 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
925 while (SD) {
926 CollectInheritedProtocols(SD, Protocols);
927 SD = SD->getSuperClass();
928 }
929 return;
930 }
931 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
932 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
933 PE = OC->protocol_end(); P != PE; ++P) {
934 ObjCProtocolDecl *Proto = (*P);
935 Protocols.push_back(Proto);
936 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
937 PE = Proto->protocol_end(); P != PE; ++P)
938 CollectInheritedProtocols(*P, Protocols);
939 }
940 return;
941 }
942 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
943 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
944 PE = OP->protocol_end(); P != PE; ++P) {
945 ObjCProtocolDecl *Proto = (*P);
946 Protocols.push_back(Proto);
947 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
948 PE = Proto->protocol_end(); P != PE; ++P)
949 CollectInheritedProtocols(*P, Protocols);
950 }
951 return;
952 }
953}
954
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000955unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
956 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000957 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
958 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000959 if ((*I)->getPropertyIvarDecl())
960 ++count;
961
962 // Also look into nested protocols.
963 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
964 E = PD->protocol_end(); P != E; ++P)
965 count += CountProtocolSynthesizedIvars(*P);
966 return count;
967}
968
Mike Stump1eb44332009-09-09 15:08:12 +0000969unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000970 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000971 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
972 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000973 if ((*I)->getPropertyIvarDecl())
974 ++count;
975 }
976 // Also look into interface's protocol list for properties declared
977 // in the protocol and whose ivars are synthesized.
978 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
979 PE = OI->protocol_end(); P != PE; ++P) {
980 ObjCProtocolDecl *PD = (*P);
981 count += CountProtocolSynthesizedIvars(PD);
982 }
983 return count;
984}
985
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000986/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
987ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
988 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
989 I = ObjCImpls.find(D);
990 if (I != ObjCImpls.end())
991 return cast<ObjCImplementationDecl>(I->second);
992 return 0;
993}
994/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
995ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
996 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
997 I = ObjCImpls.find(D);
998 if (I != ObjCImpls.end())
999 return cast<ObjCCategoryImplDecl>(I->second);
1000 return 0;
1001}
1002
1003/// \brief Set the implementation of ObjCInterfaceDecl.
1004void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1005 ObjCImplementationDecl *ImplD) {
1006 assert(IFaceD && ImplD && "Passed null params");
1007 ObjCImpls[IFaceD] = ImplD;
1008}
1009/// \brief Set the implementation of ObjCCategoryDecl.
1010void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1011 ObjCCategoryImplDecl *ImplD) {
1012 assert(CatD && ImplD && "Passed null params");
1013 ObjCImpls[CatD] = ImplD;
1014}
1015
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001016/// \brief Allocate an uninitialized DeclaratorInfo.
1017///
1018/// The caller should initialize the memory held by DeclaratorInfo using
1019/// the TypeLoc wrappers.
1020///
1021/// \param T the type that will be the basis for type source info. This type
1022/// should refer to how the declarator was written in source code, not to
1023/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +00001024DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
1025 unsigned DataSize) {
1026 if (!DataSize)
1027 DataSize = TypeLoc::getFullDataSizeForType(T);
1028 else
1029 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1030 "incorrect data size provided to CreateDeclaratorInfo!");
1031
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001032 DeclaratorInfo *DInfo =
1033 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1034 new (DInfo) DeclaratorInfo(T);
1035 return DInfo;
1036}
1037
John McCalla4eb74d2009-10-23 21:14:09 +00001038DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1039 SourceLocation L) {
1040 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1041 DI->getTypeLoc().initialize(L);
1042 return DI;
1043}
1044
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001045/// getInterfaceLayoutImpl - Get or compute information about the
1046/// layout of the given interface.
1047///
1048/// \param Impl - If given, also include the layout of the interface's
1049/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001050const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001051ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1052 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001053 assert(!D->isForwardDecl() && "Invalid interface decl!");
1054
Devang Patel44a3dde2008-06-04 21:54:36 +00001055 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001056 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001057 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1058 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1059 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001060
Daniel Dunbar453addb2009-05-03 11:16:44 +00001061 // Add in synthesized ivar count if laying out an implementation.
1062 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001063 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001064 unsigned SynthCount = CountSynthesizedIvars(D);
1065 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001066 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001067 // entry. Note we can't cache this because we simply free all
1068 // entries later; however we shouldn't look up implementations
1069 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001070 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001071 return getObjCLayout(D, 0);
1072 }
1073
Mike Stump1eb44332009-09-09 15:08:12 +00001074 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001075 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1076 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Devang Patel44a3dde2008-06-04 21:54:36 +00001078 return *NewEntry;
1079}
1080
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001081const ASTRecordLayout &
1082ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1083 return getObjCLayout(D, 0);
1084}
1085
1086const ASTRecordLayout &
1087ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1088 return getObjCLayout(D->getClassInterface(), D);
1089}
1090
Devang Patel88a981b2007-11-01 19:11:01 +00001091/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001092/// specified record (struct/union/class), which indicates its size and field
1093/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001094const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001095 D = D->getDefinition(*this);
1096 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001097
Chris Lattner464175b2007-07-18 17:52:12 +00001098 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001099 // Note that we can't save a reference to the entry because this function
1100 // is recursive.
1101 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001102 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001103
Mike Stump1eb44332009-09-09 15:08:12 +00001104 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001105 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001106 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Chris Lattner5d2a6302007-07-18 18:26:58 +00001108 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001109}
1110
Chris Lattnera7674d82007-07-13 22:13:22 +00001111//===----------------------------------------------------------------------===//
1112// Type creation/memoization methods
1113//===----------------------------------------------------------------------===//
1114
John McCall0953e762009-09-24 19:53:00 +00001115QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1116 unsigned Fast = Quals.getFastQualifiers();
1117 Quals.removeFastQualifiers();
1118
1119 // Check if we've already instantiated this type.
1120 llvm::FoldingSetNodeID ID;
1121 ExtQuals::Profile(ID, TypeNode, Quals);
1122 void *InsertPos = 0;
1123 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1124 assert(EQ->getQualifiers() == Quals);
1125 QualType T = QualType(EQ, Fast);
1126 return T;
1127 }
1128
John McCall6b304a02009-09-24 23:30:46 +00001129 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001130 ExtQualNodes.InsertNode(New, InsertPos);
1131 QualType T = QualType(New, Fast);
1132 return T;
1133}
1134
1135QualType ASTContext::getVolatileType(QualType T) {
1136 QualType CanT = getCanonicalType(T);
1137 if (CanT.isVolatileQualified()) return T;
1138
1139 QualifierCollector Quals;
1140 const Type *TypeNode = Quals.strip(T);
1141 Quals.addVolatile();
1142
1143 return getExtQualType(TypeNode, Quals);
1144}
1145
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001146QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001147 QualType CanT = getCanonicalType(T);
1148 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001149 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001150
John McCall0953e762009-09-24 19:53:00 +00001151 // If we are composing extended qualifiers together, merge together
1152 // into one ExtQuals node.
1153 QualifierCollector Quals;
1154 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001155
John McCall0953e762009-09-24 19:53:00 +00001156 // If this type already has an address space specified, it cannot get
1157 // another one.
1158 assert(!Quals.hasAddressSpace() &&
1159 "Type cannot be in multiple addr spaces!");
1160 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCall0953e762009-09-24 19:53:00 +00001162 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001163}
1164
Chris Lattnerb7d25532009-02-18 22:53:11 +00001165QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001166 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001167 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001168 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001169 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001171 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001172 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001173 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001174 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1175 return getPointerType(ResultType);
1176 }
1177 }
Mike Stump1eb44332009-09-09 15:08:12 +00001178
John McCall0953e762009-09-24 19:53:00 +00001179 // If we are composing extended qualifiers together, merge together
1180 // into one ExtQuals node.
1181 QualifierCollector Quals;
1182 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
John McCall0953e762009-09-24 19:53:00 +00001184 // If this type already has an ObjCGC specified, it cannot get
1185 // another one.
1186 assert(!Quals.hasObjCGCAttr() &&
1187 "Type cannot have multiple ObjCGCs!");
1188 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCall0953e762009-09-24 19:53:00 +00001190 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001191}
Chris Lattnera7674d82007-07-13 22:13:22 +00001192
Mike Stump24556362009-07-25 21:26:53 +00001193QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001194 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001195 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001196 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001197 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001198 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001199 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001200 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001201 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001202 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001203 } else {
1204 assert (T->isFunctionType()
1205 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001207 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1208 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001209 } else {
1210 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1211 ResultType
1212 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1213 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1214 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1215 F->getNumExceptions(), F->exception_begin(), true);
1216 }
Mike Stump24556362009-07-25 21:26:53 +00001217 }
John McCall0953e762009-09-24 19:53:00 +00001218
Douglas Gregora4923eb2009-11-16 21:35:15 +00001219 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001220}
1221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222/// getComplexType - Return the uniqued reference to the type for a complex
1223/// number with the specified element type.
1224QualType ASTContext::getComplexType(QualType T) {
1225 // Unique pointers, to guarantee there is only one pointer of a particular
1226 // structure.
1227 llvm::FoldingSetNodeID ID;
1228 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 void *InsertPos = 0;
1231 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1232 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // If the pointee type isn't canonical, this won't be a canonical type either,
1235 // so fill in the canonical type field.
1236 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001237 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001238 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // Get the new insert position for the node we care about.
1241 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001242 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 }
John McCall6b304a02009-09-24 23:30:46 +00001244 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 Types.push_back(New);
1246 ComplexTypes.InsertNode(New, InsertPos);
1247 return QualType(New, 0);
1248}
1249
Eli Friedmanf98aba32009-02-13 02:31:07 +00001250QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1251 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1252 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1253 FixedWidthIntType *&Entry = Map[Width];
1254 if (!Entry)
1255 Entry = new FixedWidthIntType(Width, Signed);
1256 return QualType(Entry, 0);
1257}
Reid Spencer5f016e22007-07-11 17:01:13 +00001258
1259/// getPointerType - Return the uniqued reference to the type for a pointer to
1260/// the specified type.
1261QualType ASTContext::getPointerType(QualType T) {
1262 // Unique pointers, to guarantee there is only one pointer of a particular
1263 // structure.
1264 llvm::FoldingSetNodeID ID;
1265 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 void *InsertPos = 0;
1268 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1269 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 // If the pointee type isn't canonical, this won't be a canonical type either,
1272 // so fill in the canonical type field.
1273 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001274 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001275 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 // Get the new insert position for the node we care about.
1278 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001279 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 }
John McCall6b304a02009-09-24 23:30:46 +00001281 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 Types.push_back(New);
1283 PointerTypes.InsertNode(New, InsertPos);
1284 return QualType(New, 0);
1285}
1286
Mike Stump1eb44332009-09-09 15:08:12 +00001287/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001288/// a pointer to the specified block.
1289QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001290 assert(T->isFunctionType() && "block of function types only");
1291 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001292 // structure.
1293 llvm::FoldingSetNodeID ID;
1294 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Steve Naroff5618bd42008-08-27 16:04:49 +00001296 void *InsertPos = 0;
1297 if (BlockPointerType *PT =
1298 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1299 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001300
1301 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001302 // type either so fill in the canonical type field.
1303 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001304 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001305 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Steve Naroff5618bd42008-08-27 16:04:49 +00001307 // Get the new insert position for the node we care about.
1308 BlockPointerType *NewIP =
1309 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001310 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001311 }
John McCall6b304a02009-09-24 23:30:46 +00001312 BlockPointerType *New
1313 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001314 Types.push_back(New);
1315 BlockPointerTypes.InsertNode(New, InsertPos);
1316 return QualType(New, 0);
1317}
1318
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001319/// getLValueReferenceType - Return the uniqued reference to the type for an
1320/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001321QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 // Unique pointers, to guarantee there is only one pointer of a particular
1323 // structure.
1324 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001325 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
1327 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001328 if (LValueReferenceType *RT =
1329 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001331
John McCall54e14c42009-10-22 22:37:11 +00001332 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1333
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 // If the referencee type isn't canonical, this won't be a canonical type
1335 // either, so fill in the canonical type field.
1336 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001337 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1338 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1339 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001340
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001342 LValueReferenceType *NewIP =
1343 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001344 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 }
1346
John McCall6b304a02009-09-24 23:30:46 +00001347 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001348 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1349 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001351 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001352
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001353 return QualType(New, 0);
1354}
1355
1356/// getRValueReferenceType - Return the uniqued reference to the type for an
1357/// rvalue reference to the specified type.
1358QualType ASTContext::getRValueReferenceType(QualType T) {
1359 // Unique pointers, to guarantee there is only one pointer of a particular
1360 // structure.
1361 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001362 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001363
1364 void *InsertPos = 0;
1365 if (RValueReferenceType *RT =
1366 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1367 return QualType(RT, 0);
1368
John McCall54e14c42009-10-22 22:37:11 +00001369 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1370
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001371 // If the referencee type isn't canonical, this won't be a canonical type
1372 // either, so fill in the canonical type field.
1373 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001374 if (InnerRef || !T.isCanonical()) {
1375 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1376 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001377
1378 // Get the new insert position for the node we care about.
1379 RValueReferenceType *NewIP =
1380 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1381 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1382 }
1383
John McCall6b304a02009-09-24 23:30:46 +00001384 RValueReferenceType *New
1385 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001386 Types.push_back(New);
1387 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 return QualType(New, 0);
1389}
1390
Sebastian Redlf30208a2009-01-24 21:16:55 +00001391/// getMemberPointerType - Return the uniqued reference to the type for a
1392/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001393QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001394 // Unique pointers, to guarantee there is only one pointer of a particular
1395 // structure.
1396 llvm::FoldingSetNodeID ID;
1397 MemberPointerType::Profile(ID, T, Cls);
1398
1399 void *InsertPos = 0;
1400 if (MemberPointerType *PT =
1401 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1402 return QualType(PT, 0);
1403
1404 // If the pointee or class type isn't canonical, this won't be a canonical
1405 // type either, so fill in the canonical type field.
1406 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001407 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001408 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1409
1410 // Get the new insert position for the node we care about.
1411 MemberPointerType *NewIP =
1412 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1413 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1414 }
John McCall6b304a02009-09-24 23:30:46 +00001415 MemberPointerType *New
1416 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001417 Types.push_back(New);
1418 MemberPointerTypes.InsertNode(New, InsertPos);
1419 return QualType(New, 0);
1420}
1421
Mike Stump1eb44332009-09-09 15:08:12 +00001422/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001423/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001424QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001425 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001426 ArrayType::ArraySizeModifier ASM,
1427 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001428 assert((EltTy->isDependentType() ||
1429 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001430 "Constant array of VLAs is illegal!");
1431
Chris Lattner38aeec72009-05-13 04:12:56 +00001432 // Convert the array size into a canonical width matching the pointer size for
1433 // the target.
1434 llvm::APInt ArySize(ArySizeIn);
1435 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001438 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001441 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001442 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // If the element type isn't canonical, this won't be a canonical type either,
1446 // so fill in the canonical type field.
1447 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001448 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001449 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001450 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001452 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001453 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001454 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
John McCall6b304a02009-09-24 23:30:46 +00001457 ConstantArrayType *New = new(*this,TypeAlignment)
1458 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001459 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 Types.push_back(New);
1461 return QualType(New, 0);
1462}
1463
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001464/// getVariableArrayType - Returns a non-unique reference to the type for a
1465/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001466QualType ASTContext::getVariableArrayType(QualType EltTy,
1467 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001468 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001469 unsigned EltTypeQuals,
1470 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001471 // Since we don't unique expressions, it isn't possible to unique VLA's
1472 // that have an expression provided for their size.
1473
John McCall6b304a02009-09-24 23:30:46 +00001474 VariableArrayType *New = new(*this, TypeAlignment)
1475 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001476
1477 VariableArrayTypes.push_back(New);
1478 Types.push_back(New);
1479 return QualType(New, 0);
1480}
1481
Douglas Gregor898574e2008-12-05 23:32:09 +00001482/// getDependentSizedArrayType - Returns a non-unique reference to
1483/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001484/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001485QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1486 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001487 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001488 unsigned EltTypeQuals,
1489 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001490 assert((!NumElts || NumElts->isTypeDependent() ||
1491 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001492 "Size must be type- or value-dependent!");
1493
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001494 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001495 DependentSizedArrayType *Canon = 0;
1496
1497 if (NumElts) {
1498 // Dependently-sized array types that do not have a specified
1499 // number of elements will have their sizes deduced from an
1500 // initializer.
1501 llvm::FoldingSetNodeID ID;
1502 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1503 EltTypeQuals, NumElts);
1504
1505 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1506 }
1507
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001508 DependentSizedArrayType *New;
1509 if (Canon) {
1510 // We already have a canonical version of this array type; use it as
1511 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001512 New = new (*this, TypeAlignment)
1513 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1514 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001515 } else {
1516 QualType CanonEltTy = getCanonicalType(EltTy);
1517 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001518 New = new (*this, TypeAlignment)
1519 DependentSizedArrayType(*this, EltTy, QualType(),
1520 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001521
1522 if (NumElts)
1523 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001524 } else {
1525 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1526 ASM, EltTypeQuals,
1527 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001528 New = new (*this, TypeAlignment)
1529 DependentSizedArrayType(*this, EltTy, Canon,
1530 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001531 }
1532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Douglas Gregor898574e2008-12-05 23:32:09 +00001534 Types.push_back(New);
1535 return QualType(New, 0);
1536}
1537
Eli Friedmanc5773c42008-02-15 18:16:39 +00001538QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1539 ArrayType::ArraySizeModifier ASM,
1540 unsigned EltTypeQuals) {
1541 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001542 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001543
1544 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001545 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001546 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1547 return QualType(ATP, 0);
1548
1549 // If the element type isn't canonical, this won't be a canonical type
1550 // either, so fill in the canonical type field.
1551 QualType Canonical;
1552
John McCall467b27b2009-10-22 20:10:53 +00001553 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001554 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001555 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001556
1557 // Get the new insert position for the node we care about.
1558 IncompleteArrayType *NewIP =
1559 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001560 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001561 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001562
John McCall6b304a02009-09-24 23:30:46 +00001563 IncompleteArrayType *New = new (*this, TypeAlignment)
1564 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001565
1566 IncompleteArrayTypes.InsertNode(New, InsertPos);
1567 Types.push_back(New);
1568 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001569}
1570
Steve Naroff73322922007-07-18 18:00:27 +00001571/// getVectorType - Return the unique reference to a vector type of
1572/// the specified element type and size. VectorType must be a built-in type.
1573QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Chris Lattnerf52ab252008-04-06 22:59:24 +00001576 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001577 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 // Check if we've already instantiated a vector of this type.
1580 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001581 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 void *InsertPos = 0;
1583 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1584 return QualType(VTP, 0);
1585
1586 // If the element type isn't canonical, this won't be a canonical type either,
1587 // so fill in the canonical type field.
1588 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001589 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001590 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 // Get the new insert position for the node we care about.
1593 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001594 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 }
John McCall6b304a02009-09-24 23:30:46 +00001596 VectorType *New = new (*this, TypeAlignment)
1597 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 VectorTypes.InsertNode(New, InsertPos);
1599 Types.push_back(New);
1600 return QualType(New, 0);
1601}
1602
Nate Begeman213541a2008-04-18 23:10:10 +00001603/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001604/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001605QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001606 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Chris Lattnerf52ab252008-04-06 22:59:24 +00001608 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001609 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Steve Naroff73322922007-07-18 18:00:27 +00001611 // Check if we've already instantiated a vector of this type.
1612 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001613 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001614 void *InsertPos = 0;
1615 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1616 return QualType(VTP, 0);
1617
1618 // If the element type isn't canonical, this won't be a canonical type either,
1619 // so fill in the canonical type field.
1620 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001621 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001622 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Steve Naroff73322922007-07-18 18:00:27 +00001624 // Get the new insert position for the node we care about.
1625 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001626 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001627 }
John McCall6b304a02009-09-24 23:30:46 +00001628 ExtVectorType *New = new (*this, TypeAlignment)
1629 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001630 VectorTypes.InsertNode(New, InsertPos);
1631 Types.push_back(New);
1632 return QualType(New, 0);
1633}
1634
Mike Stump1eb44332009-09-09 15:08:12 +00001635QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001636 Expr *SizeExpr,
1637 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001638 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001639 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001640 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001642 void *InsertPos = 0;
1643 DependentSizedExtVectorType *Canon
1644 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1645 DependentSizedExtVectorType *New;
1646 if (Canon) {
1647 // We already have a canonical version of this array type; use it as
1648 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001649 New = new (*this, TypeAlignment)
1650 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1651 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001652 } else {
1653 QualType CanonVecTy = getCanonicalType(vecType);
1654 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001655 New = new (*this, TypeAlignment)
1656 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1657 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001658 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1659 } else {
1660 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1661 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001662 New = new (*this, TypeAlignment)
1663 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001664 }
1665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001667 Types.push_back(New);
1668 return QualType(New, 0);
1669}
1670
Douglas Gregor72564e72009-02-26 23:50:07 +00001671/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001672///
Mike Stump24556362009-07-25 21:26:53 +00001673QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 // Unique functions, to guarantee there is only one function of a particular
1675 // structure.
1676 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001677 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001680 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001681 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001685 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001686 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001689 FunctionNoProtoType *NewIP =
1690 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001691 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
John McCall6b304a02009-09-24 23:30:46 +00001694 FunctionNoProtoType *New = new (*this, TypeAlignment)
1695 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001697 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 return QualType(New, 0);
1699}
1700
1701/// getFunctionType - Return a normal function type with a typed argument
1702/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001703QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001704 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001705 unsigned TypeQuals, bool hasExceptionSpec,
1706 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001707 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 // Unique functions, to guarantee there is only one function of a particular
1709 // structure.
1710 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001711 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001712 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001713 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714
1715 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001716 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001717 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001719
1720 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001721 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001723 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 isCanonical = false;
1725
1726 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001727 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 QualType Canonical;
1729 if (!isCanonical) {
1730 llvm::SmallVector<QualType, 16> CanonicalArgs;
1731 CanonicalArgs.reserve(NumArgs);
1732 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001733 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001734
Chris Lattnerf52ab252008-04-06 22:59:24 +00001735 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001736 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001737 isVariadic, TypeQuals, false,
1738 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001739
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001741 FunctionProtoType *NewIP =
1742 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001743 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001745
Douglas Gregor72564e72009-02-26 23:50:07 +00001746 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001747 // for two variable size arrays (for parameter and exception types) at the
1748 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001749 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001750 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1751 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001752 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001753 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001754 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001755 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001757 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 return QualType(FTP, 0);
1759}
1760
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001761/// getTypeDeclType - Return the unique reference to the type for the
1762/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001763QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001764 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001765 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001767 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001768 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001769 else if (isa<TemplateTypeParmDecl>(Decl)) {
1770 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001771 } else if (ObjCInterfaceDecl *ObjCInterface
1772 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001773 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001774
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001775 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001776 if (PrevDecl)
1777 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001778 else
John McCall6b304a02009-09-24 23:30:46 +00001779 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001780 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001781 if (PrevDecl)
1782 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001783 else
John McCall6b304a02009-09-24 23:30:46 +00001784 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001785 } else if (UnresolvedUsingTypenameDecl *Using =
1786 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1787 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001788 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001789 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001790
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001791 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001792 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001793}
1794
Reid Spencer5f016e22007-07-11 17:01:13 +00001795/// getTypedefType - Return the unique reference to the type for the
1796/// specified typename decl.
1797QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1798 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Chris Lattnerf52ab252008-04-06 22:59:24 +00001800 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001801 Decl->TypeForDecl = new(*this, TypeAlignment)
1802 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 Types.push_back(Decl->TypeForDecl);
1804 return QualType(Decl->TypeForDecl, 0);
1805}
1806
John McCall49a832b2009-10-18 09:09:24 +00001807/// \brief Retrieve a substitution-result type.
1808QualType
1809ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1810 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001811 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001812 && "replacement types must always be canonical");
1813
1814 llvm::FoldingSetNodeID ID;
1815 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1816 void *InsertPos = 0;
1817 SubstTemplateTypeParmType *SubstParm
1818 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1819
1820 if (!SubstParm) {
1821 SubstParm = new (*this, TypeAlignment)
1822 SubstTemplateTypeParmType(Parm, Replacement);
1823 Types.push_back(SubstParm);
1824 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1825 }
1826
1827 return QualType(SubstParm, 0);
1828}
1829
Douglas Gregorfab9d672009-02-05 23:33:38 +00001830/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001831/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001832/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001833QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001834 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001835 IdentifierInfo *Name) {
1836 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001837 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001838 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001839 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001840 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1841
1842 if (TypeParm)
1843 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001845 if (Name) {
1846 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001847 TypeParm = new (*this, TypeAlignment)
1848 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001849 } else
John McCall6b304a02009-09-24 23:30:46 +00001850 TypeParm = new (*this, TypeAlignment)
1851 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001852
1853 Types.push_back(TypeParm);
1854 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1855
1856 return QualType(TypeParm, 0);
1857}
1858
Mike Stump1eb44332009-09-09 15:08:12 +00001859QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001860ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001861 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001862 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001863 unsigned NumArgs = Args.size();
1864
John McCall833ca992009-10-29 08:12:44 +00001865 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1866 ArgVec.reserve(NumArgs);
1867 for (unsigned i = 0; i != NumArgs; ++i)
1868 ArgVec.push_back(Args[i].getArgument());
1869
1870 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1871}
1872
1873QualType
1874ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001875 const TemplateArgument *Args,
1876 unsigned NumArgs,
1877 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001878 if (!Canon.isNull())
1879 Canon = getCanonicalType(Canon);
1880 else {
1881 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001882 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1883 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1884 CanonArgs.reserve(NumArgs);
1885 for (unsigned I = 0; I != NumArgs; ++I)
1886 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1887
1888 // Determine whether this canonical template specialization type already
1889 // exists.
1890 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001891 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001892 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001893
1894 void *InsertPos = 0;
1895 TemplateSpecializationType *Spec
1896 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Douglas Gregor1275ae02009-07-28 23:00:59 +00001898 if (!Spec) {
1899 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001900 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001901 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001902 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001903 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001904 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001905 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001906 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001907 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001908 }
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Douglas Gregorb88e8882009-07-30 17:40:51 +00001910 if (Canon.isNull())
1911 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001912 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001913 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001914 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001915
Douglas Gregor1275ae02009-07-28 23:00:59 +00001916 // Allocate the (non-canonical) template specialization type, but don't
1917 // try to unique it: these types typically have location information that
1918 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001919 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001920 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001921 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001922 TemplateSpecializationType *Spec
1923 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001924 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Douglas Gregor55f6b142009-02-09 18:46:07 +00001926 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001927 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001928}
1929
Mike Stump1eb44332009-09-09 15:08:12 +00001930QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001931ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001932 QualType NamedType) {
1933 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001934 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001935
1936 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001937 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001938 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1939 if (T)
1940 return QualType(T, 0);
1941
Mike Stump1eb44332009-09-09 15:08:12 +00001942 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001943 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001944 Types.push_back(T);
1945 QualifiedNameTypes.InsertNode(T, InsertPos);
1946 return QualType(T, 0);
1947}
1948
Mike Stump1eb44332009-09-09 15:08:12 +00001949QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001950 const IdentifierInfo *Name,
1951 QualType Canon) {
1952 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1953
1954 if (Canon.isNull()) {
1955 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1956 if (CanonNNS != NNS)
1957 Canon = getTypenameType(CanonNNS, Name);
1958 }
1959
1960 llvm::FoldingSetNodeID ID;
1961 TypenameType::Profile(ID, NNS, Name);
1962
1963 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001964 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001965 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1966 if (T)
1967 return QualType(T, 0);
1968
1969 T = new (*this) TypenameType(NNS, Name, Canon);
1970 Types.push_back(T);
1971 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001972 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001973}
1974
Mike Stump1eb44332009-09-09 15:08:12 +00001975QualType
1976ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001977 const TemplateSpecializationType *TemplateId,
1978 QualType Canon) {
1979 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1980
1981 if (Canon.isNull()) {
1982 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1983 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1984 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1985 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001986 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001987 assert(CanonTemplateId &&
1988 "Canonical type must also be a template specialization type");
1989 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1990 }
1991 }
1992
1993 llvm::FoldingSetNodeID ID;
1994 TypenameType::Profile(ID, NNS, TemplateId);
1995
1996 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001997 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001998 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1999 if (T)
2000 return QualType(T, 0);
2001
2002 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2003 Types.push_back(T);
2004 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002005 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002006}
2007
John McCall7da24312009-09-05 00:15:47 +00002008QualType
2009ASTContext::getElaboratedType(QualType UnderlyingType,
2010 ElaboratedType::TagKind Tag) {
2011 llvm::FoldingSetNodeID ID;
2012 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002013
John McCall7da24312009-09-05 00:15:47 +00002014 void *InsertPos = 0;
2015 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2016 if (T)
2017 return QualType(T, 0);
2018
2019 QualType Canon = getCanonicalType(UnderlyingType);
2020
2021 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2022 Types.push_back(T);
2023 ElaboratedTypes.InsertNode(T, InsertPos);
2024 return QualType(T, 0);
2025}
2026
Chris Lattner88cb27a2008-04-07 04:56:42 +00002027/// CmpProtocolNames - Comparison predicate for sorting protocols
2028/// alphabetically.
2029static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2030 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002031 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002032}
2033
John McCall54e14c42009-10-22 22:37:11 +00002034static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2035 unsigned NumProtocols) {
2036 if (NumProtocols == 0) return true;
2037
2038 for (unsigned i = 1; i != NumProtocols; ++i)
2039 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2040 return false;
2041 return true;
2042}
2043
2044static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002045 unsigned &NumProtocols) {
2046 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattner88cb27a2008-04-07 04:56:42 +00002048 // Sort protocols, keyed by name.
2049 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2050
2051 // Remove duplicates.
2052 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2053 NumProtocols = ProtocolsEnd-Protocols;
2054}
2055
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002056/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2057/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002058QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002059 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002060 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002061 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002062 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002063
2064 void *InsertPos = 0;
2065 if (ObjCObjectPointerType *QT =
2066 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2067 return QualType(QT, 0);
2068
John McCall54e14c42009-10-22 22:37:11 +00002069 // Sort the protocol list alphabetically to canonicalize it.
2070 QualType Canonical;
2071 if (!InterfaceT.isCanonical() ||
2072 !areSortedAndUniqued(Protocols, NumProtocols)) {
2073 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2074 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2075 unsigned UniqueCount = NumProtocols;
2076
2077 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2078 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2079
2080 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2081 &Sorted[0], UniqueCount);
2082 } else {
2083 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2084 Protocols, NumProtocols);
2085 }
2086
2087 // Regenerate InsertPos.
2088 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2089 }
2090
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002091 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002092 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002093 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002095 Types.push_back(QType);
2096 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2097 return QualType(QType, 0);
2098}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002099
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002100/// getObjCInterfaceType - Return the unique reference to the type for the
2101/// specified ObjC interface decl. The list of protocols is optional.
2102QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002103 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002104 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002105 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002107 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002108 if (ObjCInterfaceType *QT =
2109 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002110 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
John McCall54e14c42009-10-22 22:37:11 +00002112 // Sort the protocol list alphabetically to canonicalize it.
2113 QualType Canonical;
2114 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2115 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2116 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2117
2118 unsigned UniqueCount = NumProtocols;
2119 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2120
2121 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2122
2123 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2124 }
2125
John McCall6b304a02009-09-24 23:30:46 +00002126 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002127 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002128 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002129
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002130 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002131 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002132 return QualType(QType, 0);
2133}
2134
Douglas Gregor72564e72009-02-26 23:50:07 +00002135/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2136/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002137/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002138/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002139/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002140QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002141 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002142 if (tofExpr->isTypeDependent()) {
2143 llvm::FoldingSetNodeID ID;
2144 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Douglas Gregorb1975722009-07-30 23:18:24 +00002146 void *InsertPos = 0;
2147 DependentTypeOfExprType *Canon
2148 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2149 if (Canon) {
2150 // We already have a "canonical" version of an identical, dependent
2151 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002152 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002153 QualType((TypeOfExprType*)Canon, 0));
2154 }
2155 else {
2156 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002157 Canon
2158 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002159 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2160 toe = Canon;
2161 }
2162 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002163 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002164 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002165 }
Steve Naroff9752f252007-08-01 18:02:17 +00002166 Types.push_back(toe);
2167 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002168}
2169
Steve Naroff9752f252007-08-01 18:02:17 +00002170/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2171/// TypeOfType AST's. The only motivation to unique these nodes would be
2172/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002173/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002174/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002175QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002176 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002177 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002178 Types.push_back(tot);
2179 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002180}
2181
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002182/// getDecltypeForExpr - Given an expr, will return the decltype for that
2183/// expression, according to the rules in C++0x [dcl.type.simple]p4
2184static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002185 if (e->isTypeDependent())
2186 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002188 // If e is an id expression or a class member access, decltype(e) is defined
2189 // as the type of the entity named by e.
2190 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2191 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2192 return VD->getType();
2193 }
2194 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2195 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2196 return FD->getType();
2197 }
2198 // If e is a function call or an invocation of an overloaded operator,
2199 // (parentheses around e are ignored), decltype(e) is defined as the
2200 // return type of that function.
2201 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2202 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002204 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002205
2206 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002207 // defined as T&, otherwise decltype(e) is defined as T.
2208 if (e->isLvalue(Context) == Expr::LV_Valid)
2209 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002211 return T;
2212}
2213
Anders Carlsson395b4752009-06-24 19:06:50 +00002214/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2215/// DecltypeType AST's. The only motivation to unique these nodes would be
2216/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002217/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002218/// on canonical type's (which are always unique).
2219QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002220 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002221 if (e->isTypeDependent()) {
2222 llvm::FoldingSetNodeID ID;
2223 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002225 void *InsertPos = 0;
2226 DependentDecltypeType *Canon
2227 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2228 if (Canon) {
2229 // We already have a "canonical" version of an equivalent, dependent
2230 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002231 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002232 QualType((DecltypeType*)Canon, 0));
2233 }
2234 else {
2235 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002236 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002237 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2238 dt = Canon;
2239 }
2240 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002241 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002242 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002243 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002244 Types.push_back(dt);
2245 return QualType(dt, 0);
2246}
2247
Reid Spencer5f016e22007-07-11 17:01:13 +00002248/// getTagDeclType - Return the unique reference to the type for the
2249/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002250QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002251 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002252 // FIXME: What is the design on getTagDeclType when it requires casting
2253 // away const? mutable?
2254 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002255}
2256
Mike Stump1eb44332009-09-09 15:08:12 +00002257/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2258/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2259/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002260QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002261 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002262}
2263
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002264/// getSignedWCharType - Return the type of "signed wchar_t".
2265/// Used when in C++, as a GCC extension.
2266QualType ASTContext::getSignedWCharType() const {
2267 // FIXME: derive from "Target" ?
2268 return WCharTy;
2269}
2270
2271/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2272/// Used when in C++, as a GCC extension.
2273QualType ASTContext::getUnsignedWCharType() const {
2274 // FIXME: derive from "Target" ?
2275 return UnsignedIntTy;
2276}
2277
Chris Lattner8b9023b2007-07-13 03:05:23 +00002278/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2279/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2280QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002281 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002282}
2283
Chris Lattnere6327742008-04-02 05:18:44 +00002284//===----------------------------------------------------------------------===//
2285// Type Operators
2286//===----------------------------------------------------------------------===//
2287
John McCall54e14c42009-10-22 22:37:11 +00002288CanQualType ASTContext::getCanonicalParamType(QualType T) {
2289 // Push qualifiers into arrays, and then discard any remaining
2290 // qualifiers.
2291 T = getCanonicalType(T);
2292 const Type *Ty = T.getTypePtr();
2293
2294 QualType Result;
2295 if (isa<ArrayType>(Ty)) {
2296 Result = getArrayDecayedType(QualType(Ty,0));
2297 } else if (isa<FunctionType>(Ty)) {
2298 Result = getPointerType(QualType(Ty, 0));
2299 } else {
2300 Result = QualType(Ty, 0);
2301 }
2302
2303 return CanQualType::CreateUnsafe(Result);
2304}
2305
Chris Lattner77c96472008-04-06 22:41:35 +00002306/// getCanonicalType - Return the canonical (structural) type corresponding to
2307/// the specified potentially non-canonical type. The non-canonical version
2308/// of a type may have many "decorated" versions of types. Decorators can
2309/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2310/// to be free of any of these, allowing two canonical types to be compared
2311/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002312CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002313 QualifierCollector Quals;
2314 const Type *Ptr = Quals.strip(T);
2315 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002316
John McCall0953e762009-09-24 19:53:00 +00002317 // The canonical internal type will be the canonical type *except*
2318 // that we push type qualifiers down through array types.
2319
2320 // If there are no new qualifiers to push down, stop here.
2321 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002322 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002323
John McCall0953e762009-09-24 19:53:00 +00002324 // If the type qualifiers are on an array type, get the canonical
2325 // type of the array with the qualifiers applied to the element
2326 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002327 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2328 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002329 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002331 // Get the canonical version of the element with the extra qualifiers on it.
2332 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002333 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002334 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002336 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002337 return CanQualType::CreateUnsafe(
2338 getConstantArrayType(NewEltTy, CAT->getSize(),
2339 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002340 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002341 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002342 return CanQualType::CreateUnsafe(
2343 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002344 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Douglas Gregor898574e2008-12-05 23:32:09 +00002346 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002347 return CanQualType::CreateUnsafe(
2348 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002349 DSAT->getSizeExpr() ?
2350 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002351 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002352 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002353 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002354
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002355 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002356 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002357 VAT->getSizeExpr() ?
2358 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002359 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002360 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002361 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002362}
2363
John McCall80ad16f2009-11-24 18:42:40 +00002364DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2365 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2366 return TD->getDeclName();
2367
2368 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2369 if (DTN->isIdentifier()) {
2370 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2371 } else {
2372 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2373 }
2374 }
2375
John McCall0bd6feb2009-12-02 08:04:21 +00002376 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2377 assert(Storage);
2378 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002379}
2380
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002381TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2382 // If this template name refers to a template, the canonical
2383 // template name merely stores the template itself.
2384 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002385 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002386
John McCall0bd6feb2009-12-02 08:04:21 +00002387 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002389 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2390 assert(DTN && "Non-dependent template names must refer to template decls.");
2391 return DTN->CanonicalTemplateName;
2392}
2393
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002394bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2395 X = getCanonicalTemplateName(X);
2396 Y = getCanonicalTemplateName(Y);
2397 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2398}
2399
Mike Stump1eb44332009-09-09 15:08:12 +00002400TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002401ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2402 switch (Arg.getKind()) {
2403 case TemplateArgument::Null:
2404 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Douglas Gregor1275ae02009-07-28 23:00:59 +00002406 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002407 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Douglas Gregor1275ae02009-07-28 23:00:59 +00002409 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002410 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002411
Douglas Gregor788cd062009-11-11 01:00:40 +00002412 case TemplateArgument::Template:
2413 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2414
Douglas Gregor1275ae02009-07-28 23:00:59 +00002415 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002416 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002417 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Douglas Gregor1275ae02009-07-28 23:00:59 +00002419 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002420 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002421
Douglas Gregor1275ae02009-07-28 23:00:59 +00002422 case TemplateArgument::Pack: {
2423 // FIXME: Allocate in ASTContext
2424 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2425 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002426 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002427 AEnd = Arg.pack_end();
2428 A != AEnd; (void)++A, ++Idx)
2429 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Douglas Gregor1275ae02009-07-28 23:00:59 +00002431 TemplateArgument Result;
2432 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2433 return Result;
2434 }
2435 }
2436
2437 // Silence GCC warning
2438 assert(false && "Unhandled template argument kind");
2439 return TemplateArgument();
2440}
2441
Douglas Gregord57959a2009-03-27 23:10:48 +00002442NestedNameSpecifier *
2443ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002444 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002445 return 0;
2446
2447 switch (NNS->getKind()) {
2448 case NestedNameSpecifier::Identifier:
2449 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002450 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002451 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2452 NNS->getAsIdentifier());
2453
2454 case NestedNameSpecifier::Namespace:
2455 // A namespace is canonical; build a nested-name-specifier with
2456 // this namespace and no prefix.
2457 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2458
2459 case NestedNameSpecifier::TypeSpec:
2460 case NestedNameSpecifier::TypeSpecWithTemplate: {
2461 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002462 return NestedNameSpecifier::Create(*this, 0,
2463 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002464 T.getTypePtr());
2465 }
2466
2467 case NestedNameSpecifier::Global:
2468 // The global specifier is canonical and unique.
2469 return NNS;
2470 }
2471
2472 // Required to silence a GCC warning
2473 return 0;
2474}
2475
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002476
2477const ArrayType *ASTContext::getAsArrayType(QualType T) {
2478 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002479 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002480 // Handle the common positive case fast.
2481 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2482 return AT;
2483 }
Mike Stump1eb44332009-09-09 15:08:12 +00002484
John McCall0953e762009-09-24 19:53:00 +00002485 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002486 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002487 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002488 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002489
John McCall0953e762009-09-24 19:53:00 +00002490 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002491 // implements C99 6.7.3p8: "If the specification of an array type includes
2492 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002494 // If we get here, we either have type qualifiers on the type, or we have
2495 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002496 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002497
John McCall0953e762009-09-24 19:53:00 +00002498 QualifierCollector Qs;
2499 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002501 // If we have a simple case, just return now.
2502 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002503 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002504 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002505
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002506 // Otherwise, we have an array and we have qualifiers on it. Push the
2507 // qualifiers into the array element type and return a new array type.
2508 // Get the canonical version of the element with the extra qualifiers on it.
2509 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002510 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002512 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2513 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2514 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002515 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002516 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2517 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2518 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002519 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002520
Mike Stump1eb44332009-09-09 15:08:12 +00002521 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002522 = dyn_cast<DependentSizedArrayType>(ATy))
2523 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002524 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002525 DSAT->getSizeExpr() ?
2526 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002527 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002528 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002529 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002531 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002532 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002533 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002534 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002535 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002536 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002537 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002538}
2539
2540
Chris Lattnere6327742008-04-02 05:18:44 +00002541/// getArrayDecayedType - Return the properly qualified result of decaying the
2542/// specified array type to a pointer. This operation is non-trivial when
2543/// handling typedefs etc. The canonical type of "T" must be an array type,
2544/// this returns a pointer to a properly qualified element of the array.
2545///
2546/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2547QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002548 // Get the element type with 'getAsArrayType' so that we don't lose any
2549 // typedefs in the element type of the array. This also handles propagation
2550 // of type qualifiers from the array type into the element type if present
2551 // (C99 6.7.3p8).
2552 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2553 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002555 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002556
2557 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002558 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002559}
2560
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002561QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002562 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002563 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002564 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002565 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2566 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002567 } else {
John McCall0953e762009-09-24 19:53:00 +00002568 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002569 }
2570 }
2571}
2572
Anders Carlssonfbbce492009-09-25 01:23:32 +00002573QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2574 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Anders Carlssonfbbce492009-09-25 01:23:32 +00002576 if (const ArrayType *AT = getAsArrayType(ElemTy))
2577 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Anders Carlsson6183a992008-12-21 03:44:36 +00002579 return ElemTy;
2580}
2581
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002582/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002583uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002584ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2585 uint64_t ElementCount = 1;
2586 do {
2587 ElementCount *= CA->getSize().getZExtValue();
2588 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2589 } while (CA);
2590 return ElementCount;
2591}
2592
Reid Spencer5f016e22007-07-11 17:01:13 +00002593/// getFloatingRank - Return a relative rank for floating point types.
2594/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002595static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002596 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002598
John McCall183700f2009-09-21 23:43:11 +00002599 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2600 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002601 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 case BuiltinType::Float: return FloatRank;
2603 case BuiltinType::Double: return DoubleRank;
2604 case BuiltinType::LongDouble: return LongDoubleRank;
2605 }
2606}
2607
Mike Stump1eb44332009-09-09 15:08:12 +00002608/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2609/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002610/// 'typeDomain' is a real floating point or complex type.
2611/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002612QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2613 QualType Domain) const {
2614 FloatingRank EltRank = getFloatingRank(Size);
2615 if (Domain->isComplexType()) {
2616 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002617 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002618 case FloatRank: return FloatComplexTy;
2619 case DoubleRank: return DoubleComplexTy;
2620 case LongDoubleRank: return LongDoubleComplexTy;
2621 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 }
Chris Lattner1361b112008-04-06 23:58:54 +00002623
2624 assert(Domain->isRealFloatingType() && "Unknown domain!");
2625 switch (EltRank) {
2626 default: assert(0 && "getFloatingRank(): illegal value for rank");
2627 case FloatRank: return FloatTy;
2628 case DoubleRank: return DoubleTy;
2629 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002630 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002631}
2632
Chris Lattner7cfeb082008-04-06 23:55:33 +00002633/// getFloatingTypeOrder - Compare the rank of the two specified floating
2634/// point types, ignoring the domain of the type (i.e. 'double' ==
2635/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002636/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002637int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2638 FloatingRank LHSR = getFloatingRank(LHS);
2639 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Chris Lattnera75cea32008-04-06 23:38:49 +00002641 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002642 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002643 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002644 return 1;
2645 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646}
2647
Chris Lattnerf52ab252008-04-06 22:59:24 +00002648/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2649/// routine will assert if passed a built-in type that isn't an integer or enum,
2650/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002651unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002652 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002653 if (EnumType* ET = dyn_cast<EnumType>(T))
2654 T = ET->getDecl()->getIntegerType().getTypePtr();
2655
Eli Friedmana3426752009-07-05 23:44:27 +00002656 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2657 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2658
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002659 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2660 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2661
2662 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2663 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2664
Eli Friedmanf98aba32009-02-13 02:31:07 +00002665 // There are two things which impact the integer rank: the width, and
2666 // the ordering of builtins. The builtin ordering is encoded in the
2667 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002668 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002669 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002670
Chris Lattnerf52ab252008-04-06 22:59:24 +00002671 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002672 default: assert(0 && "getIntegerRank(): not a built-in integer");
2673 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002674 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002675 case BuiltinType::Char_S:
2676 case BuiltinType::Char_U:
2677 case BuiltinType::SChar:
2678 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002679 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002680 case BuiltinType::Short:
2681 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002682 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002683 case BuiltinType::Int:
2684 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002685 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002686 case BuiltinType::Long:
2687 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002688 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002689 case BuiltinType::LongLong:
2690 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002691 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002692 case BuiltinType::Int128:
2693 case BuiltinType::UInt128:
2694 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002695 }
2696}
2697
Eli Friedman04e83572009-08-20 04:21:42 +00002698/// \brief Whether this is a promotable bitfield reference according
2699/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2700///
2701/// \returns the type this bit-field will promote to, or NULL if no
2702/// promotion occurs.
2703QualType ASTContext::isPromotableBitField(Expr *E) {
2704 FieldDecl *Field = E->getBitField();
2705 if (!Field)
2706 return QualType();
2707
2708 QualType FT = Field->getType();
2709
2710 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2711 uint64_t BitWidth = BitWidthAP.getZExtValue();
2712 uint64_t IntSize = getTypeSize(IntTy);
2713 // GCC extension compatibility: if the bit-field size is less than or equal
2714 // to the size of int, it gets promoted no matter what its type is.
2715 // For instance, unsigned long bf : 4 gets promoted to signed int.
2716 if (BitWidth < IntSize)
2717 return IntTy;
2718
2719 if (BitWidth == IntSize)
2720 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2721
2722 // Types bigger than int are not subject to promotions, and therefore act
2723 // like the base type.
2724 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2725 // is ridiculous.
2726 return QualType();
2727}
2728
Eli Friedmana95d7572009-08-19 07:44:53 +00002729/// getPromotedIntegerType - Returns the type that Promotable will
2730/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2731/// integer type.
2732QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2733 assert(!Promotable.isNull());
2734 assert(Promotable->isPromotableIntegerType());
2735 if (Promotable->isSignedIntegerType())
2736 return IntTy;
2737 uint64_t PromotableSize = getTypeSize(Promotable);
2738 uint64_t IntSize = getTypeSize(IntTy);
2739 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2740 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2741}
2742
Mike Stump1eb44332009-09-09 15:08:12 +00002743/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002744/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002745/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002746int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002747 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2748 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002749 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Chris Lattnerf52ab252008-04-06 22:59:24 +00002751 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2752 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Chris Lattner7cfeb082008-04-06 23:55:33 +00002754 unsigned LHSRank = getIntegerRank(LHSC);
2755 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Chris Lattner7cfeb082008-04-06 23:55:33 +00002757 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2758 if (LHSRank == RHSRank) return 0;
2759 return LHSRank > RHSRank ? 1 : -1;
2760 }
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Chris Lattner7cfeb082008-04-06 23:55:33 +00002762 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2763 if (LHSUnsigned) {
2764 // If the unsigned [LHS] type is larger, return it.
2765 if (LHSRank >= RHSRank)
2766 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Chris Lattner7cfeb082008-04-06 23:55:33 +00002768 // If the signed type can represent all values of the unsigned type, it
2769 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002770 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002771 return -1;
2772 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002773
Chris Lattner7cfeb082008-04-06 23:55:33 +00002774 // If the unsigned [RHS] type is larger, return it.
2775 if (RHSRank >= LHSRank)
2776 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Chris Lattner7cfeb082008-04-06 23:55:33 +00002778 // If the signed type can represent all values of the unsigned type, it
2779 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002780 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002781 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002782}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002783
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002784static RecordDecl *
2785CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2786 SourceLocation L, IdentifierInfo *Id) {
2787 if (Ctx.getLangOptions().CPlusPlus)
2788 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2789 else
2790 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2791}
2792
Mike Stump1eb44332009-09-09 15:08:12 +00002793// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002794QualType ASTContext::getCFConstantStringType() {
2795 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002796 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002797 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2798 &Idents.get("NSConstantString"));
2799
Anders Carlssonf06273f2007-11-19 00:25:30 +00002800 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Anders Carlsson71993dd2007-08-17 05:31:46 +00002802 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002803 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002804 // int flags;
2805 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002806 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002807 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002808 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002809 FieldTypes[3] = LongTy;
2810
Anders Carlsson71993dd2007-08-17 05:31:46 +00002811 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002812 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002813 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002814 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002815 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002816 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002817 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002818 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002819 }
2820
2821 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002822 }
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Anders Carlsson71993dd2007-08-17 05:31:46 +00002824 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002825}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002826
Douglas Gregor319ac892009-04-23 22:29:11 +00002827void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002828 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002829 assert(Rec && "Invalid CFConstantStringType");
2830 CFConstantStringTypeDecl = Rec->getDecl();
2831}
2832
Mike Stump1eb44332009-09-09 15:08:12 +00002833QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002834 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002835 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002836 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2837 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002839 QualType FieldTypes[] = {
2840 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002841 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002842 getPointerType(UnsignedLongTy),
2843 getConstantArrayType(UnsignedLongTy,
2844 llvm::APInt(32, 5), ArrayType::Normal, 0)
2845 };
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Douglas Gregor44b43212008-12-11 16:49:14 +00002847 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002848 FieldDecl *Field = FieldDecl::Create(*this,
2849 ObjCFastEnumerationStateTypeDecl,
2850 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002851 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002852 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002853 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002854 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002855 }
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Douglas Gregor44b43212008-12-11 16:49:14 +00002857 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002858 }
Mike Stump1eb44332009-09-09 15:08:12 +00002859
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002860 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2861}
2862
Mike Stumpadaaad32009-10-20 02:12:22 +00002863QualType ASTContext::getBlockDescriptorType() {
2864 if (BlockDescriptorType)
2865 return getTagDeclType(BlockDescriptorType);
2866
2867 RecordDecl *T;
2868 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002869 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2870 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002871
2872 QualType FieldTypes[] = {
2873 UnsignedLongTy,
2874 UnsignedLongTy,
2875 };
2876
2877 const char *FieldNames[] = {
2878 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002879 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002880 };
2881
2882 for (size_t i = 0; i < 2; ++i) {
2883 FieldDecl *Field = FieldDecl::Create(*this,
2884 T,
2885 SourceLocation(),
2886 &Idents.get(FieldNames[i]),
2887 FieldTypes[i], /*DInfo=*/0,
2888 /*BitWidth=*/0,
2889 /*Mutable=*/false);
2890 T->addDecl(Field);
2891 }
2892
2893 T->completeDefinition(*this);
2894
2895 BlockDescriptorType = T;
2896
2897 return getTagDeclType(BlockDescriptorType);
2898}
2899
2900void ASTContext::setBlockDescriptorType(QualType T) {
2901 const RecordType *Rec = T->getAs<RecordType>();
2902 assert(Rec && "Invalid BlockDescriptorType");
2903 BlockDescriptorType = Rec->getDecl();
2904}
2905
Mike Stump083c25e2009-10-22 00:49:09 +00002906QualType ASTContext::getBlockDescriptorExtendedType() {
2907 if (BlockDescriptorExtendedType)
2908 return getTagDeclType(BlockDescriptorExtendedType);
2909
2910 RecordDecl *T;
2911 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002912 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2913 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002914
2915 QualType FieldTypes[] = {
2916 UnsignedLongTy,
2917 UnsignedLongTy,
2918 getPointerType(VoidPtrTy),
2919 getPointerType(VoidPtrTy)
2920 };
2921
2922 const char *FieldNames[] = {
2923 "reserved",
2924 "Size",
2925 "CopyFuncPtr",
2926 "DestroyFuncPtr"
2927 };
2928
2929 for (size_t i = 0; i < 4; ++i) {
2930 FieldDecl *Field = FieldDecl::Create(*this,
2931 T,
2932 SourceLocation(),
2933 &Idents.get(FieldNames[i]),
2934 FieldTypes[i], /*DInfo=*/0,
2935 /*BitWidth=*/0,
2936 /*Mutable=*/false);
2937 T->addDecl(Field);
2938 }
2939
2940 T->completeDefinition(*this);
2941
2942 BlockDescriptorExtendedType = T;
2943
2944 return getTagDeclType(BlockDescriptorExtendedType);
2945}
2946
2947void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2948 const RecordType *Rec = T->getAs<RecordType>();
2949 assert(Rec && "Invalid BlockDescriptorType");
2950 BlockDescriptorExtendedType = Rec->getDecl();
2951}
2952
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002953bool ASTContext::BlockRequiresCopying(QualType Ty) {
2954 if (Ty->isBlockPointerType())
2955 return true;
2956 if (isObjCNSObjectType(Ty))
2957 return true;
2958 if (Ty->isObjCObjectPointerType())
2959 return true;
2960 return false;
2961}
2962
2963QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2964 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002965 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002966 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002967 // unsigned int __flags;
2968 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002969 // void *__copy_helper; // as needed
2970 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002971 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002972 // } *
2973
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002974 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2975
2976 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002977 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002978 llvm::SmallString<36> Name;
2979 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2980 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002981 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002982 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2983 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002984 T->startDefinition();
2985 QualType Int32Ty = IntTy;
2986 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2987 QualType FieldTypes[] = {
2988 getPointerType(VoidPtrTy),
2989 getPointerType(getTagDeclType(T)),
2990 Int32Ty,
2991 Int32Ty,
2992 getPointerType(VoidPtrTy),
2993 getPointerType(VoidPtrTy),
2994 Ty
2995 };
2996
2997 const char *FieldNames[] = {
2998 "__isa",
2999 "__forwarding",
3000 "__flags",
3001 "__size",
3002 "__copy_helper",
3003 "__destroy_helper",
3004 DeclName,
3005 };
3006
3007 for (size_t i = 0; i < 7; ++i) {
3008 if (!HasCopyAndDispose && i >=4 && i <= 5)
3009 continue;
3010 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3011 &Idents.get(FieldNames[i]),
3012 FieldTypes[i], /*DInfo=*/0,
3013 /*BitWidth=*/0, /*Mutable=*/false);
3014 T->addDecl(Field);
3015 }
3016
3017 T->completeDefinition(*this);
3018
3019 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003020}
3021
3022
3023QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003024 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003025 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003026 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003027 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003028 llvm::SmallString<36> Name;
3029 llvm::raw_svector_ostream(Name) << "__block_literal_"
3030 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003031 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003032 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3033 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003034 QualType FieldTypes[] = {
3035 getPointerType(VoidPtrTy),
3036 IntTy,
3037 IntTy,
3038 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003039 (BlockHasCopyDispose ?
3040 getPointerType(getBlockDescriptorExtendedType()) :
3041 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003042 };
3043
3044 const char *FieldNames[] = {
3045 "__isa",
3046 "__flags",
3047 "__reserved",
3048 "__FuncPtr",
3049 "__descriptor"
3050 };
3051
3052 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003053 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003054 &Idents.get(FieldNames[i]),
3055 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003056 /*BitWidth=*/0, /*Mutable=*/false);
3057 T->addDecl(Field);
3058 }
3059
3060 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3061 const Expr *E = BlockDeclRefDecls[i];
3062 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3063 clang::IdentifierInfo *Name = 0;
3064 if (BDRE) {
3065 const ValueDecl *D = BDRE->getDecl();
3066 Name = &Idents.get(D->getName());
3067 }
3068 QualType FieldType = E->getType();
3069
3070 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003071 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3072 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003073
3074 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3075 Name, FieldType, /*DInfo=*/0,
3076 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003077 T->addDecl(Field);
3078 }
3079
3080 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003081
3082 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003083}
3084
Douglas Gregor319ac892009-04-23 22:29:11 +00003085void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003086 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003087 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3088 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3089}
3090
Anders Carlssone8c49532007-10-29 06:33:42 +00003091// This returns true if a type has been typedefed to BOOL:
3092// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003093static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003094 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003095 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3096 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003098 return false;
3099}
3100
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003101/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003102/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003103int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003104 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003106 // Make all integer and enum types at least as large as an int
3107 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003108 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003109 // Treat arrays as pointers, since that's how they're passed in.
3110 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003111 sz = getTypeSize(VoidPtrTy);
3112 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003113}
3114
David Chisnall5e530af2009-11-17 19:33:30 +00003115/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3116/// declaration.
3117void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3118 std::string& S) {
3119 const BlockDecl *Decl = Expr->getBlockDecl();
3120 QualType BlockTy =
3121 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3122 // Encode result type.
3123 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3124 // Compute size of all parameters.
3125 // Start with computing size of a pointer in number of bytes.
3126 // FIXME: There might(should) be a better way of doing this computation!
3127 SourceLocation Loc;
3128 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3129 int ParmOffset = PtrSize;
3130 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3131 E = Decl->param_end(); PI != E; ++PI) {
3132 QualType PType = (*PI)->getType();
3133 int sz = getObjCEncodingTypeSize(PType);
3134 assert (sz > 0 && "BlockExpr - Incomplete param type");
3135 ParmOffset += sz;
3136 }
3137 // Size of the argument frame
3138 S += llvm::utostr(ParmOffset);
3139 // Block pointer and offset.
3140 S += "@?0";
3141 ParmOffset = PtrSize;
3142
3143 // Argument types.
3144 ParmOffset = PtrSize;
3145 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3146 Decl->param_end(); PI != E; ++PI) {
3147 ParmVarDecl *PVDecl = *PI;
3148 QualType PType = PVDecl->getOriginalType();
3149 if (const ArrayType *AT =
3150 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3151 // Use array's original type only if it has known number of
3152 // elements.
3153 if (!isa<ConstantArrayType>(AT))
3154 PType = PVDecl->getType();
3155 } else if (PType->isFunctionType())
3156 PType = PVDecl->getType();
3157 getObjCEncodingForType(PType, S);
3158 S += llvm::utostr(ParmOffset);
3159 ParmOffset += getObjCEncodingTypeSize(PType);
3160 }
3161}
3162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003163/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003164/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003165void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003166 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003167 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003168 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003169 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003170 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003171 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003172 // Compute size of all parameters.
3173 // Start with computing size of a pointer in number of bytes.
3174 // FIXME: There might(should) be a better way of doing this computation!
3175 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003176 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003177 // The first two arguments (self and _cmd) are pointers; account for
3178 // their size.
3179 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003180 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3181 E = Decl->param_end(); PI != E; ++PI) {
3182 QualType PType = (*PI)->getType();
3183 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003184 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003185 ParmOffset += sz;
3186 }
3187 S += llvm::utostr(ParmOffset);
3188 S += "@0:";
3189 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003191 // Argument types.
3192 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003193 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3194 E = Decl->param_end(); PI != E; ++PI) {
3195 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003196 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003197 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003198 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3199 // Use array's original type only if it has known number of
3200 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003201 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003202 PType = PVDecl->getType();
3203 } else if (PType->isFunctionType())
3204 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003205 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003206 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003207 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003208 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003209 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003211 }
3212}
3213
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003214/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003215/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003216/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3217/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003218/// Property attributes are stored as a comma-delimited C string. The simple
3219/// attributes readonly and bycopy are encoded as single characters. The
3220/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3221/// encoded as single characters, followed by an identifier. Property types
3222/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003223/// these attributes are defined by the following enumeration:
3224/// @code
3225/// enum PropertyAttributes {
3226/// kPropertyReadOnly = 'R', // property is read-only.
3227/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3228/// kPropertyByref = '&', // property is a reference to the value last assigned
3229/// kPropertyDynamic = 'D', // property is dynamic
3230/// kPropertyGetter = 'G', // followed by getter selector name
3231/// kPropertySetter = 'S', // followed by setter selector name
3232/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3233/// kPropertyType = 't' // followed by old-style type encoding.
3234/// kPropertyWeak = 'W' // 'weak' property
3235/// kPropertyStrong = 'P' // property GC'able
3236/// kPropertyNonAtomic = 'N' // property non-atomic
3237/// };
3238/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003239void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003240 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003241 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003242 // Collect information from the property implementation decl(s).
3243 bool Dynamic = false;
3244 ObjCPropertyImplDecl *SynthesizePID = 0;
3245
3246 // FIXME: Duplicated code due to poor abstraction.
3247 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003248 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003249 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3250 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003251 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003252 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003253 ObjCPropertyImplDecl *PID = *i;
3254 if (PID->getPropertyDecl() == PD) {
3255 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3256 Dynamic = true;
3257 } else {
3258 SynthesizePID = PID;
3259 }
3260 }
3261 }
3262 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003263 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003264 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003265 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003266 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003267 ObjCPropertyImplDecl *PID = *i;
3268 if (PID->getPropertyDecl() == PD) {
3269 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3270 Dynamic = true;
3271 } else {
3272 SynthesizePID = PID;
3273 }
3274 }
Mike Stump1eb44332009-09-09 15:08:12 +00003275 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003276 }
3277 }
3278
3279 // FIXME: This is not very efficient.
3280 S = "T";
3281
3282 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003283 // GCC has some special rules regarding encoding of properties which
3284 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003285 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003286 true /* outermost type */,
3287 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003288
3289 if (PD->isReadOnly()) {
3290 S += ",R";
3291 } else {
3292 switch (PD->getSetterKind()) {
3293 case ObjCPropertyDecl::Assign: break;
3294 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003295 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003296 }
3297 }
3298
3299 // It really isn't clear at all what this means, since properties
3300 // are "dynamic by default".
3301 if (Dynamic)
3302 S += ",D";
3303
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003304 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3305 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003307 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3308 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003309 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003310 }
3311
3312 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3313 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003314 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003315 }
3316
3317 if (SynthesizePID) {
3318 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3319 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003320 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003321 }
3322
3323 // FIXME: OBJCGC: weak & strong
3324}
3325
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003326/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003327/// Another legacy compatibility encoding: 32-bit longs are encoded as
3328/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003329/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3330///
3331void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003332 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003333 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003334 if (BT->getKind() == BuiltinType::ULong &&
3335 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003336 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003337 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003338 if (BT->getKind() == BuiltinType::Long &&
3339 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003340 PointeeTy = IntTy;
3341 }
3342 }
3343}
3344
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003345void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003346 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003347 // We follow the behavior of gcc, expanding structures which are
3348 // directly pointed to, and expanding embedded structures. Note that
3349 // these rules are sufficient to prevent recursive encoding of the
3350 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003351 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003352 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003353}
3354
Mike Stump1eb44332009-09-09 15:08:12 +00003355static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003356 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003357 const Expr *E = FD->getBitWidth();
3358 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3359 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003360 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003361 S += 'b';
3362 S += llvm::utostr(N);
3363}
3364
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003365// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003366void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3367 bool ExpandPointedToStructures,
3368 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003369 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003370 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003371 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003372 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003373 if (FD && FD->isBitField())
3374 return EncodeBitField(this, S, FD);
3375 char encoding;
3376 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003377 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003378 case BuiltinType::Void: encoding = 'v'; break;
3379 case BuiltinType::Bool: encoding = 'B'; break;
3380 case BuiltinType::Char_U:
3381 case BuiltinType::UChar: encoding = 'C'; break;
3382 case BuiltinType::UShort: encoding = 'S'; break;
3383 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003384 case BuiltinType::ULong:
3385 encoding =
3386 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003387 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003388 case BuiltinType::UInt128: encoding = 'T'; break;
3389 case BuiltinType::ULongLong: encoding = 'Q'; break;
3390 case BuiltinType::Char_S:
3391 case BuiltinType::SChar: encoding = 'c'; break;
3392 case BuiltinType::Short: encoding = 's'; break;
3393 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003394 case BuiltinType::Long:
3395 encoding =
3396 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003397 break;
3398 case BuiltinType::LongLong: encoding = 'q'; break;
3399 case BuiltinType::Int128: encoding = 't'; break;
3400 case BuiltinType::Float: encoding = 'f'; break;
3401 case BuiltinType::Double: encoding = 'd'; break;
3402 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003403 }
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003405 S += encoding;
3406 return;
3407 }
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall183700f2009-09-21 23:43:11 +00003409 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003410 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003411 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003412 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003413 return;
3414 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003415
Ted Kremenek6217b802009-07-29 21:53:49 +00003416 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003417 if (PT->isObjCSelType()) {
3418 S += ':';
3419 return;
3420 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003421 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003422
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003423 bool isReadOnly = false;
3424 // For historical/compatibility reasons, the read-only qualifier of the
3425 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3426 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003427 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003428 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003429 if (OutermostType && T.isConstQualified()) {
3430 isReadOnly = true;
3431 S += 'r';
3432 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003433 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003434 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003435 while (P->getAs<PointerType>())
3436 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003437 if (P.isConstQualified()) {
3438 isReadOnly = true;
3439 S += 'r';
3440 }
3441 }
3442 if (isReadOnly) {
3443 // Another legacy compatibility encoding. Some ObjC qualifier and type
3444 // combinations need to be rearranged.
3445 // Rewrite "in const" from "nr" to "rn"
3446 const char * s = S.c_str();
3447 int len = S.length();
3448 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3449 std::string replace = "rn";
3450 S.replace(S.end()-2, S.end(), replace);
3451 }
3452 }
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003454 if (PointeeTy->isCharType()) {
3455 // char pointer types should be encoded as '*' unless it is a
3456 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003457 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003458 S += '*';
3459 return;
3460 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003461 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003462 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3463 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3464 S += '#';
3465 return;
3466 }
3467 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3468 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3469 S += '@';
3470 return;
3471 }
3472 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003473 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003474 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003475 getLegacyIntegralTypeEncoding(PointeeTy);
3476
Mike Stump1eb44332009-09-09 15:08:12 +00003477 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003478 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003479 return;
3480 }
Mike Stump1eb44332009-09-09 15:08:12 +00003481
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003482 if (const ArrayType *AT =
3483 // Ignore type qualifiers etc.
3484 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003485 if (isa<IncompleteArrayType>(AT)) {
3486 // Incomplete arrays are encoded as a pointer to the array element.
3487 S += '^';
3488
Mike Stump1eb44332009-09-09 15:08:12 +00003489 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003490 false, ExpandStructures, FD);
3491 } else {
3492 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Anders Carlsson559a8332009-02-22 01:38:57 +00003494 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3495 S += llvm::utostr(CAT->getSize().getZExtValue());
3496 else {
3497 //Variable length arrays are encoded as a regular array with 0 elements.
3498 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3499 S += '0';
3500 }
Mike Stump1eb44332009-09-09 15:08:12 +00003501
3502 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003503 false, ExpandStructures, FD);
3504 S += ']';
3505 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003506 return;
3507 }
Mike Stump1eb44332009-09-09 15:08:12 +00003508
John McCall183700f2009-09-21 23:43:11 +00003509 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003510 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003511 return;
3512 }
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Ted Kremenek6217b802009-07-29 21:53:49 +00003514 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003515 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003516 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003517 // Anonymous structures print as '?'
3518 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3519 S += II->getName();
3520 } else {
3521 S += '?';
3522 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003523 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003524 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003525 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3526 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003527 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003528 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003529 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003530 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003531 S += '"';
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003534 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003535 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003536 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003537 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003538 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003539 QualType qt = Field->getType();
3540 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003541 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003542 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003543 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003544 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003545 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003546 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003547 return;
3548 }
Mike Stump1eb44332009-09-09 15:08:12 +00003549
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003550 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003551 if (FD && FD->isBitField())
3552 EncodeBitField(this, S, FD);
3553 else
3554 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003555 return;
3556 }
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003558 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003559 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003560 return;
3561 }
Mike Stump1eb44332009-09-09 15:08:12 +00003562
John McCall0953e762009-09-24 19:53:00 +00003563 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003564 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003565 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003566 S += '{';
3567 const IdentifierInfo *II = OI->getIdentifier();
3568 S += II->getName();
3569 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003570 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003571 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003572 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003573 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003574 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003575 RecFields[i]);
3576 else
Mike Stump1eb44332009-09-09 15:08:12 +00003577 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003578 FD);
3579 }
3580 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003581 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003582 }
Mike Stump1eb44332009-09-09 15:08:12 +00003583
John McCall183700f2009-09-21 23:43:11 +00003584 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003585 if (OPT->isObjCIdType()) {
3586 S += '@';
3587 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003588 }
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Steve Naroff27d20a22009-10-28 22:03:49 +00003590 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3591 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3592 // Since this is a binary compatibility issue, need to consult with runtime
3593 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003594 S += '#';
3595 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003596 }
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003599 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003600 ExpandPointedToStructures,
3601 ExpandStructures, FD);
3602 if (FD || EncodingProperty) {
3603 // Note that we do extended encoding of protocol qualifer list
3604 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003605 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003606 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3607 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003608 S += '<';
3609 S += (*I)->getNameAsString();
3610 S += '>';
3611 }
3612 S += '"';
3613 }
3614 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003615 }
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003617 QualType PointeeTy = OPT->getPointeeType();
3618 if (!EncodingProperty &&
3619 isa<TypedefType>(PointeeTy.getTypePtr())) {
3620 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003621 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003622 // {...};
3623 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003624 getObjCEncodingForTypeImpl(PointeeTy, S,
3625 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003626 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003627 return;
3628 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003629
3630 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003631 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003632 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003633 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003634 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3635 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003636 S += '<';
3637 S += (*I)->getNameAsString();
3638 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003639 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003640 S += '"';
3641 }
3642 return;
3643 }
Mike Stump1eb44332009-09-09 15:08:12 +00003644
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003645 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003646}
3647
Mike Stump1eb44332009-09-09 15:08:12 +00003648void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003649 std::string& S) const {
3650 if (QT & Decl::OBJC_TQ_In)
3651 S += 'n';
3652 if (QT & Decl::OBJC_TQ_Inout)
3653 S += 'N';
3654 if (QT & Decl::OBJC_TQ_Out)
3655 S += 'o';
3656 if (QT & Decl::OBJC_TQ_Bycopy)
3657 S += 'O';
3658 if (QT & Decl::OBJC_TQ_Byref)
3659 S += 'R';
3660 if (QT & Decl::OBJC_TQ_Oneway)
3661 S += 'V';
3662}
3663
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003664void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003665 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003667 BuiltinVaListType = T;
3668}
3669
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003670void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003671 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003672}
3673
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003674void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003675 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003676}
3677
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003678void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003679 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003680}
3681
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003682void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003683 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003684}
3685
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003686void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003687 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003688 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003690 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003691}
3692
John McCall0bd6feb2009-12-02 08:04:21 +00003693/// \brief Retrieve the template name that corresponds to a non-empty
3694/// lookup.
3695TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3696 NamedDecl * const *End) {
3697 unsigned size = End - Begin;
3698 assert(size > 1 && "set is not overloaded!");
3699
3700 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3701 size * sizeof(FunctionTemplateDecl*));
3702 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3703
3704 NamedDecl **Storage = OT->getStorage();
3705 for (NamedDecl * const *I = Begin; I != End; ++I) {
3706 NamedDecl *D = *I;
3707 assert(isa<FunctionTemplateDecl>(D) ||
3708 (isa<UsingShadowDecl>(D) &&
3709 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3710 *Storage++ = D;
3711 }
3712
3713 return TemplateName(OT);
3714}
3715
Douglas Gregor7532dc62009-03-30 22:58:21 +00003716/// \brief Retrieve the template name that represents a qualified
3717/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003718TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003719 bool TemplateKeyword,
3720 TemplateDecl *Template) {
3721 llvm::FoldingSetNodeID ID;
3722 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3723
3724 void *InsertPos = 0;
3725 QualifiedTemplateName *QTN =
3726 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3727 if (!QTN) {
3728 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3729 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3730 }
3731
3732 return TemplateName(QTN);
3733}
3734
3735/// \brief Retrieve the template name that represents a dependent
3736/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003737TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003738 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003739 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003740 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003741
3742 llvm::FoldingSetNodeID ID;
3743 DependentTemplateName::Profile(ID, NNS, Name);
3744
3745 void *InsertPos = 0;
3746 DependentTemplateName *QTN =
3747 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3748
3749 if (QTN)
3750 return TemplateName(QTN);
3751
3752 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3753 if (CanonNNS == NNS) {
3754 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3755 } else {
3756 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3757 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3758 }
3759
3760 DependentTemplateNames.InsertNode(QTN, InsertPos);
3761 return TemplateName(QTN);
3762}
3763
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003764/// \brief Retrieve the template name that represents a dependent
3765/// template name such as \c MetaFun::template operator+.
3766TemplateName
3767ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3768 OverloadedOperatorKind Operator) {
3769 assert((!NNS || NNS->isDependent()) &&
3770 "Nested name specifier must be dependent");
3771
3772 llvm::FoldingSetNodeID ID;
3773 DependentTemplateName::Profile(ID, NNS, Operator);
3774
3775 void *InsertPos = 0;
3776 DependentTemplateName *QTN =
3777 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3778
3779 if (QTN)
3780 return TemplateName(QTN);
3781
3782 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3783 if (CanonNNS == NNS) {
3784 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3785 } else {
3786 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3787 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3788 }
3789
3790 DependentTemplateNames.InsertNode(QTN, InsertPos);
3791 return TemplateName(QTN);
3792}
3793
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003794/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003795/// TargetInfo, produce the corresponding type. The unsigned @p Type
3796/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003797CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003798 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003799 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003800 case TargetInfo::SignedShort: return ShortTy;
3801 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3802 case TargetInfo::SignedInt: return IntTy;
3803 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3804 case TargetInfo::SignedLong: return LongTy;
3805 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3806 case TargetInfo::SignedLongLong: return LongLongTy;
3807 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3808 }
3809
3810 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003811 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003812}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003813
3814//===----------------------------------------------------------------------===//
3815// Type Predicates.
3816//===----------------------------------------------------------------------===//
3817
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003818/// isObjCNSObjectType - Return true if this is an NSObject object using
3819/// NSObject attribute on a c-style pointer type.
3820/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003821/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003822///
3823bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3824 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3825 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003826 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003827 return true;
3828 }
Mike Stump1eb44332009-09-09 15:08:12 +00003829 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003830}
3831
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003832/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3833/// garbage collection attribute.
3834///
John McCall0953e762009-09-24 19:53:00 +00003835Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3836 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003837 if (getLangOptions().ObjC1 &&
3838 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003839 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003840 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003841 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003842 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003843 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003844 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003845 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003846 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003847 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003848 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003849 // Non-pointers have none gc'able attribute regardless of the attribute
3850 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003851 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003852 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003853 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003854 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003855}
3856
Chris Lattner6ac46a42008-04-07 06:51:04 +00003857//===----------------------------------------------------------------------===//
3858// Type Compatibility Testing
3859//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003860
Mike Stump1eb44332009-09-09 15:08:12 +00003861/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003862/// compatible.
3863static bool areCompatVectorTypes(const VectorType *LHS,
3864 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003865 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003866 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003867 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003868}
3869
Steve Naroff4084c302009-07-23 01:01:38 +00003870//===----------------------------------------------------------------------===//
3871// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3872//===----------------------------------------------------------------------===//
3873
3874/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3875/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003876bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3877 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003878 if (lProto == rProto)
3879 return true;
3880 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3881 E = rProto->protocol_end(); PI != E; ++PI)
3882 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3883 return true;
3884 return false;
3885}
3886
Steve Naroff4084c302009-07-23 01:01:38 +00003887/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3888/// return true if lhs's protocols conform to rhs's protocol; false
3889/// otherwise.
3890bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3891 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3892 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3893 return false;
3894}
3895
3896/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3897/// ObjCQualifiedIDType.
3898bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3899 bool compare) {
3900 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003901 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003902 lhs->isObjCIdType() || lhs->isObjCClassType())
3903 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003904 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003905 rhs->isObjCIdType() || rhs->isObjCClassType())
3906 return true;
3907
3908 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003909 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003910
Steve Naroff4084c302009-07-23 01:01:38 +00003911 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003912
Steve Naroff4084c302009-07-23 01:01:38 +00003913 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003914 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003915 // make sure we check the class hierarchy.
3916 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3917 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3918 E = lhsQID->qual_end(); I != E; ++I) {
3919 // when comparing an id<P> on lhs with a static type on rhs,
3920 // see if static class implements all of id's protocols, directly or
3921 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003922 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003923 return false;
3924 }
3925 }
3926 // If there are no qualifiers and no interface, we have an 'id'.
3927 return true;
3928 }
Mike Stump1eb44332009-09-09 15:08:12 +00003929 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003930 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3931 E = lhsQID->qual_end(); I != E; ++I) {
3932 ObjCProtocolDecl *lhsProto = *I;
3933 bool match = false;
3934
3935 // when comparing an id<P> on lhs with a static type on rhs,
3936 // see if static class implements all of id's protocols, directly or
3937 // through its super class and categories.
3938 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3939 E = rhsOPT->qual_end(); J != E; ++J) {
3940 ObjCProtocolDecl *rhsProto = *J;
3941 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3942 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3943 match = true;
3944 break;
3945 }
3946 }
Mike Stump1eb44332009-09-09 15:08:12 +00003947 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003948 // make sure we check the class hierarchy.
3949 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3950 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3951 E = lhsQID->qual_end(); I != E; ++I) {
3952 // when comparing an id<P> on lhs with a static type on rhs,
3953 // see if static class implements all of id's protocols, directly or
3954 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003955 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003956 match = true;
3957 break;
3958 }
3959 }
3960 }
3961 if (!match)
3962 return false;
3963 }
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Steve Naroff4084c302009-07-23 01:01:38 +00003965 return true;
3966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Steve Naroff4084c302009-07-23 01:01:38 +00003968 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3969 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3970
Mike Stump1eb44332009-09-09 15:08:12 +00003971 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003972 lhs->getAsObjCInterfacePointerType()) {
3973 if (lhsOPT->qual_empty()) {
3974 bool match = false;
3975 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3976 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3977 E = rhsQID->qual_end(); I != E; ++I) {
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.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003981 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003982 match = true;
3983 break;
3984 }
3985 }
3986 if (!match)
3987 return false;
3988 }
3989 return true;
3990 }
Mike Stump1eb44332009-09-09 15:08:12 +00003991 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003992 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3993 E = lhsOPT->qual_end(); I != E; ++I) {
3994 ObjCProtocolDecl *lhsProto = *I;
3995 bool match = false;
3996
3997 // when comparing an id<P> on lhs with a static type on rhs,
3998 // see if static class implements all of id's protocols, directly or
3999 // through its super class and categories.
4000 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4001 E = rhsQID->qual_end(); J != E; ++J) {
4002 ObjCProtocolDecl *rhsProto = *J;
4003 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4004 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4005 match = true;
4006 break;
4007 }
4008 }
4009 if (!match)
4010 return false;
4011 }
4012 return true;
4013 }
4014 return false;
4015}
4016
Eli Friedman3d815e72008-08-22 00:56:42 +00004017/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004018/// compatible for assignment from RHS to LHS. This handles validation of any
4019/// protocol qualifiers on the LHS or RHS.
4020///
Steve Naroff14108da2009-07-10 23:34:53 +00004021bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4022 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004023 // If either type represents the built-in 'id' or 'Class' types, return true.
4024 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004025 return true;
4026
Steve Naroff4084c302009-07-23 01:01:38 +00004027 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004028 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4029 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004030 false);
4031
Steve Naroff14108da2009-07-10 23:34:53 +00004032 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4033 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004034 if (LHS && RHS) // We have 2 user-defined types.
4035 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Steve Naroff4084c302009-07-23 01:01:38 +00004037 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004038}
4039
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004040/// getIntersectionOfProtocols - This routine finds the intersection of set
4041/// of protocols inherited from two distinct objective-c pointer objects.
4042/// It is used to build composite qualifier list of the composite type of
4043/// the conditional expression involving two objective-c pointer objects.
4044static
4045void getIntersectionOfProtocols(ASTContext &Context,
4046 const ObjCObjectPointerType *LHSOPT,
4047 const ObjCObjectPointerType *RHSOPT,
4048 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4049
4050 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4051 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4052
4053 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4054 unsigned LHSNumProtocols = LHS->getNumProtocols();
4055 if (LHSNumProtocols > 0)
4056 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4057 else {
4058 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4059 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4060 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4061 LHSInheritedProtocols.end());
4062 }
4063
4064 unsigned RHSNumProtocols = RHS->getNumProtocols();
4065 if (RHSNumProtocols > 0) {
4066 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4067 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4068 if (InheritedProtocolSet.count(RHSProtocols[i]))
4069 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4070 }
4071 else {
4072 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4073 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4074 // FIXME. This may cause duplication of protocols in the list, but should
4075 // be harmless.
4076 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4077 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4078 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4079 }
4080}
4081
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004082/// areCommonBaseCompatible - Returns common base class of the two classes if
4083/// one found. Note that this is O'2 algorithm. But it will be called as the
4084/// last type comparison in a ?-exp of ObjC pointer types before a
4085/// warning is issued. So, its invokation is extremely rare.
4086QualType ASTContext::areCommonBaseCompatible(
4087 const ObjCObjectPointerType *LHSOPT,
4088 const ObjCObjectPointerType *RHSOPT) {
4089 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4090 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4091 if (!LHS || !RHS)
4092 return QualType();
4093
4094 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4095 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4096 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004097 if (canAssignObjCInterfaces(LHS, RHS)) {
4098 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4099 getIntersectionOfProtocols(*this,
4100 LHSOPT, RHSOPT, IntersectionOfProtocols);
4101 if (IntersectionOfProtocols.empty())
4102 LHSTy = getObjCObjectPointerType(LHSTy);
4103 else
4104 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4105 IntersectionOfProtocols.size());
4106 return LHSTy;
4107 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004108 }
4109
4110 return QualType();
4111}
4112
Eli Friedman3d815e72008-08-22 00:56:42 +00004113bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4114 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004115 // Verify that the base decls are compatible: the RHS must be a subclass of
4116 // the LHS.
4117 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4118 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Chris Lattner6ac46a42008-04-07 06:51:04 +00004120 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4121 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004122 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004123 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Chris Lattner6ac46a42008-04-07 06:51:04 +00004125 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4126 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004127 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004128 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004130 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4131 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004132 LHSPI != LHSPE; LHSPI++) {
4133 bool RHSImplementsProtocol = false;
4134
4135 // If the RHS doesn't implement the protocol on the left, the types
4136 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004137 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004138 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004139 RHSPI != RHSPE; RHSPI++) {
4140 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004141 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004142 break;
4143 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004144 }
4145 // FIXME: For better diagnostics, consider passing back the protocol name.
4146 if (!RHSImplementsProtocol)
4147 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004148 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004149 // The RHS implements all protocols listed on the LHS.
4150 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004151}
4152
Steve Naroff389bf462009-02-12 17:52:19 +00004153bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4154 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004155 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4156 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Steve Naroff14108da2009-07-10 23:34:53 +00004158 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004159 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004160
4161 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4162 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004163}
4164
Mike Stump1eb44332009-09-09 15:08:12 +00004165/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004166/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004167/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004168/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004169bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4170 return !mergeTypes(LHS, RHS).isNull();
4171}
4172
4173QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004174 const FunctionType *lbase = lhs->getAs<FunctionType>();
4175 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004176 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4177 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004178 bool allLTypes = true;
4179 bool allRTypes = true;
4180
4181 // Check return type
4182 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4183 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004184 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4185 allLTypes = false;
4186 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4187 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004188 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004189 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4190 if (NoReturn != lbase->getNoReturnAttr())
4191 allLTypes = false;
4192 if (NoReturn != rbase->getNoReturnAttr())
4193 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Eli Friedman3d815e72008-08-22 00:56:42 +00004195 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004196 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4197 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004198 unsigned lproto_nargs = lproto->getNumArgs();
4199 unsigned rproto_nargs = rproto->getNumArgs();
4200
4201 // Compatible functions must have the same number of arguments
4202 if (lproto_nargs != rproto_nargs)
4203 return QualType();
4204
4205 // Variadic and non-variadic functions aren't compatible
4206 if (lproto->isVariadic() != rproto->isVariadic())
4207 return QualType();
4208
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004209 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4210 return QualType();
4211
Eli Friedman3d815e72008-08-22 00:56:42 +00004212 // Check argument compatibility
4213 llvm::SmallVector<QualType, 10> types;
4214 for (unsigned i = 0; i < lproto_nargs; i++) {
4215 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4216 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4217 QualType argtype = mergeTypes(largtype, rargtype);
4218 if (argtype.isNull()) return QualType();
4219 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004220 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4221 allLTypes = false;
4222 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4223 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004224 }
4225 if (allLTypes) return lhs;
4226 if (allRTypes) return rhs;
4227 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004228 lproto->isVariadic(), lproto->getTypeQuals(),
4229 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004230 }
4231
4232 if (lproto) allRTypes = false;
4233 if (rproto) allLTypes = false;
4234
Douglas Gregor72564e72009-02-26 23:50:07 +00004235 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004236 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004237 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004238 if (proto->isVariadic()) return QualType();
4239 // Check that the types are compatible with the types that
4240 // would result from default argument promotions (C99 6.7.5.3p15).
4241 // The only types actually affected are promotable integer
4242 // types and floats, which would be passed as a different
4243 // type depending on whether the prototype is visible.
4244 unsigned proto_nargs = proto->getNumArgs();
4245 for (unsigned i = 0; i < proto_nargs; ++i) {
4246 QualType argTy = proto->getArgType(i);
4247 if (argTy->isPromotableIntegerType() ||
4248 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4249 return QualType();
4250 }
4251
4252 if (allLTypes) return lhs;
4253 if (allRTypes) return rhs;
4254 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004255 proto->getNumArgs(), proto->isVariadic(),
4256 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004257 }
4258
4259 if (allLTypes) return lhs;
4260 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004261 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004262}
4263
4264QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004265 // C++ [expr]: If an expression initially has the type "reference to T", the
4266 // type is adjusted to "T" prior to any further analysis, the expression
4267 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004268 // expression is an lvalue unless the reference is an rvalue reference and
4269 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004270 // FIXME: C++ shouldn't be going through here! The rules are different
4271 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004272 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4273 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004274 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004275 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004276 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004277 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004278
Eli Friedman3d815e72008-08-22 00:56:42 +00004279 QualType LHSCan = getCanonicalType(LHS),
4280 RHSCan = getCanonicalType(RHS);
4281
4282 // If two types are identical, they are compatible.
4283 if (LHSCan == RHSCan)
4284 return LHS;
4285
John McCall0953e762009-09-24 19:53:00 +00004286 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004287 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4288 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004289 if (LQuals != RQuals) {
4290 // If any of these qualifiers are different, we have a type
4291 // mismatch.
4292 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4293 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4294 return QualType();
4295
4296 // Exactly one GC qualifier difference is allowed: __strong is
4297 // okay if the other type has no GC qualifier but is an Objective
4298 // C object pointer (i.e. implicitly strong by default). We fix
4299 // this by pretending that the unqualified type was actually
4300 // qualified __strong.
4301 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4302 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4303 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4304
4305 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4306 return QualType();
4307
4308 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4309 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4310 }
4311 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4312 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4313 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004314 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004315 }
4316
4317 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004318
Eli Friedman852d63b2009-06-01 01:22:52 +00004319 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4320 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004321
Chris Lattner1adb8832008-01-14 05:45:46 +00004322 // We want to consider the two function types to be the same for these
4323 // comparisons, just force one to the other.
4324 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4325 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004326
4327 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004328 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4329 LHSClass = Type::ConstantArray;
4330 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4331 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004332
Nate Begeman213541a2008-04-18 23:10:10 +00004333 // Canonicalize ExtVector -> Vector.
4334 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4335 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004336
Chris Lattnera36a61f2008-04-07 05:43:21 +00004337 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004338 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004339 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004340 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004341 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004342 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4343 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004344 }
John McCall183700f2009-09-21 23:43:11 +00004345 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004346 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4347 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004348 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004349
Eli Friedman3d815e72008-08-22 00:56:42 +00004350 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004351 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004352
Steve Naroff4a746782008-01-09 22:43:08 +00004353 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004354 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004355#define TYPE(Class, Base)
4356#define ABSTRACT_TYPE(Class, Base)
4357#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4358#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4359#include "clang/AST/TypeNodes.def"
4360 assert(false && "Non-canonical and dependent types shouldn't get here");
4361 return QualType();
4362
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004363 case Type::LValueReference:
4364 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004365 case Type::MemberPointer:
4366 assert(false && "C++ should never be in mergeTypes");
4367 return QualType();
4368
4369 case Type::IncompleteArray:
4370 case Type::VariableArray:
4371 case Type::FunctionProto:
4372 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004373 assert(false && "Types are eliminated above");
4374 return QualType();
4375
Chris Lattner1adb8832008-01-14 05:45:46 +00004376 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004377 {
4378 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004379 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4380 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004381 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4382 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004383 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004384 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004385 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004386 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004387 return getPointerType(ResultType);
4388 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004389 case Type::BlockPointer:
4390 {
4391 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004392 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4393 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004394 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4395 if (ResultType.isNull()) return QualType();
4396 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4397 return LHS;
4398 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4399 return RHS;
4400 return getBlockPointerType(ResultType);
4401 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004402 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004403 {
4404 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4405 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4406 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4407 return QualType();
4408
4409 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4410 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4411 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4412 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004413 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4414 return LHS;
4415 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4416 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004417 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4418 ArrayType::ArraySizeModifier(), 0);
4419 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4420 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004421 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4422 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004423 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4424 return LHS;
4425 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4426 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004427 if (LVAT) {
4428 // FIXME: This isn't correct! But tricky to implement because
4429 // the array's size has to be the size of LHS, but the type
4430 // has to be different.
4431 return LHS;
4432 }
4433 if (RVAT) {
4434 // FIXME: This isn't correct! But tricky to implement because
4435 // the array's size has to be the size of RHS, but the type
4436 // has to be different.
4437 return RHS;
4438 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004439 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4440 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004441 return getIncompleteArrayType(ResultType,
4442 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004443 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004444 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004445 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004446 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004447 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004448 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004449 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004450 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004451 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004452 case Type::Complex:
4453 // Distinct complex types are incompatible.
4454 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004455 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004456 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004457 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004458 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004459 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004460 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004461 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004462 // FIXME: This should be type compatibility, e.g. whether
4463 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004464 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4465 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004466 if (LHSIface && RHSIface &&
4467 canAssignObjCInterfaces(LHSIface, RHSIface))
4468 return LHS;
4469
Eli Friedman3d815e72008-08-22 00:56:42 +00004470 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004471 }
Steve Naroff14108da2009-07-10 23:34:53 +00004472 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004473 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4474 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004475 return LHS;
4476
Steve Naroffbc76dd02008-12-10 22:14:21 +00004477 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004478 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004479 case Type::FixedWidthInt:
4480 // Distinct fixed-width integers are not compatible.
4481 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004482 case Type::TemplateSpecialization:
4483 assert(false && "Dependent types have no size");
4484 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004485 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004486
4487 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004488}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004489
Chris Lattner5426bf62008-04-07 07:01:58 +00004490//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004491// Integer Predicates
4492//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004493
Eli Friedmanad74a752008-06-28 06:23:08 +00004494unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004495 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004496 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004497 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004498 return FWIT->getWidth();
4499 }
4500 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004501 return (unsigned)getTypeSize(T);
4502}
4503
4504QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4505 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004506
4507 // Turn <4 x signed int> -> <4 x unsigned int>
4508 if (const VectorType *VTy = T->getAs<VectorType>())
4509 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4510 VTy->getNumElements());
4511
4512 // For enums, we return the unsigned version of the base type.
4513 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004514 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004515
4516 const BuiltinType *BTy = T->getAs<BuiltinType>();
4517 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004518 switch (BTy->getKind()) {
4519 case BuiltinType::Char_S:
4520 case BuiltinType::SChar:
4521 return UnsignedCharTy;
4522 case BuiltinType::Short:
4523 return UnsignedShortTy;
4524 case BuiltinType::Int:
4525 return UnsignedIntTy;
4526 case BuiltinType::Long:
4527 return UnsignedLongTy;
4528 case BuiltinType::LongLong:
4529 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004530 case BuiltinType::Int128:
4531 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004532 default:
4533 assert(0 && "Unexpected signed integer type");
4534 return QualType();
4535 }
4536}
4537
Douglas Gregor2cf26342009-04-09 22:27:44 +00004538ExternalASTSource::~ExternalASTSource() { }
4539
4540void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004541
4542
4543//===----------------------------------------------------------------------===//
4544// Builtin Type Computation
4545//===----------------------------------------------------------------------===//
4546
4547/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4548/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004549static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004550 ASTContext::GetBuiltinTypeError &Error,
4551 bool AllowTypeModifiers = true) {
4552 // Modifiers.
4553 int HowLong = 0;
4554 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004555
Chris Lattner86df27b2009-06-14 00:45:47 +00004556 // Read the modifiers first.
4557 bool Done = false;
4558 while (!Done) {
4559 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004560 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004561 case 'S':
4562 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4563 assert(!Signed && "Can't use 'S' modifier multiple times!");
4564 Signed = true;
4565 break;
4566 case 'U':
4567 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4568 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4569 Unsigned = true;
4570 break;
4571 case 'L':
4572 assert(HowLong <= 2 && "Can't have LLLL modifier");
4573 ++HowLong;
4574 break;
4575 }
4576 }
4577
4578 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Chris Lattner86df27b2009-06-14 00:45:47 +00004580 // Read the base type.
4581 switch (*Str++) {
4582 default: assert(0 && "Unknown builtin type letter!");
4583 case 'v':
4584 assert(HowLong == 0 && !Signed && !Unsigned &&
4585 "Bad modifiers used with 'v'!");
4586 Type = Context.VoidTy;
4587 break;
4588 case 'f':
4589 assert(HowLong == 0 && !Signed && !Unsigned &&
4590 "Bad modifiers used with 'f'!");
4591 Type = Context.FloatTy;
4592 break;
4593 case 'd':
4594 assert(HowLong < 2 && !Signed && !Unsigned &&
4595 "Bad modifiers used with 'd'!");
4596 if (HowLong)
4597 Type = Context.LongDoubleTy;
4598 else
4599 Type = Context.DoubleTy;
4600 break;
4601 case 's':
4602 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4603 if (Unsigned)
4604 Type = Context.UnsignedShortTy;
4605 else
4606 Type = Context.ShortTy;
4607 break;
4608 case 'i':
4609 if (HowLong == 3)
4610 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4611 else if (HowLong == 2)
4612 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4613 else if (HowLong == 1)
4614 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4615 else
4616 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4617 break;
4618 case 'c':
4619 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4620 if (Signed)
4621 Type = Context.SignedCharTy;
4622 else if (Unsigned)
4623 Type = Context.UnsignedCharTy;
4624 else
4625 Type = Context.CharTy;
4626 break;
4627 case 'b': // boolean
4628 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4629 Type = Context.BoolTy;
4630 break;
4631 case 'z': // size_t.
4632 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4633 Type = Context.getSizeType();
4634 break;
4635 case 'F':
4636 Type = Context.getCFConstantStringType();
4637 break;
4638 case 'a':
4639 Type = Context.getBuiltinVaListType();
4640 assert(!Type.isNull() && "builtin va list type not initialized!");
4641 break;
4642 case 'A':
4643 // This is a "reference" to a va_list; however, what exactly
4644 // this means depends on how va_list is defined. There are two
4645 // different kinds of va_list: ones passed by value, and ones
4646 // passed by reference. An example of a by-value va_list is
4647 // x86, where va_list is a char*. An example of by-ref va_list
4648 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4649 // we want this argument to be a char*&; for x86-64, we want
4650 // it to be a __va_list_tag*.
4651 Type = Context.getBuiltinVaListType();
4652 assert(!Type.isNull() && "builtin va list type not initialized!");
4653 if (Type->isArrayType()) {
4654 Type = Context.getArrayDecayedType(Type);
4655 } else {
4656 Type = Context.getLValueReferenceType(Type);
4657 }
4658 break;
4659 case 'V': {
4660 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004661 unsigned NumElements = strtoul(Str, &End, 10);
4662 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004663
Chris Lattner86df27b2009-06-14 00:45:47 +00004664 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Chris Lattner86df27b2009-06-14 00:45:47 +00004666 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4667 Type = Context.getVectorType(ElementType, NumElements);
4668 break;
4669 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004670 case 'X': {
4671 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4672 Type = Context.getComplexType(ElementType);
4673 break;
4674 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004675 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004676 Type = Context.getFILEType();
4677 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004678 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004679 return QualType();
4680 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004681 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004682 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004683 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004684 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004685 else
4686 Type = Context.getjmp_bufType();
4687
Mike Stumpfd612db2009-07-28 23:47:15 +00004688 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004689 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004690 return QualType();
4691 }
4692 break;
Mike Stump782fa302009-07-28 02:25:19 +00004693 }
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Chris Lattner86df27b2009-06-14 00:45:47 +00004695 if (!AllowTypeModifiers)
4696 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Chris Lattner86df27b2009-06-14 00:45:47 +00004698 Done = false;
4699 while (!Done) {
4700 switch (*Str++) {
4701 default: Done = true; --Str; break;
4702 case '*':
4703 Type = Context.getPointerType(Type);
4704 break;
4705 case '&':
4706 Type = Context.getLValueReferenceType(Type);
4707 break;
4708 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4709 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004710 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004711 break;
4712 }
4713 }
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Chris Lattner86df27b2009-06-14 00:45:47 +00004715 return Type;
4716}
4717
4718/// GetBuiltinType - Return the type for the specified builtin.
4719QualType ASTContext::GetBuiltinType(unsigned id,
4720 GetBuiltinTypeError &Error) {
4721 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Chris Lattner86df27b2009-06-14 00:45:47 +00004723 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Chris Lattner86df27b2009-06-14 00:45:47 +00004725 Error = GE_None;
4726 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4727 if (Error != GE_None)
4728 return QualType();
4729 while (TypeStr[0] && TypeStr[0] != '.') {
4730 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4731 if (Error != GE_None)
4732 return QualType();
4733
4734 // Do array -> pointer decay. The builtin should use the decayed type.
4735 if (Ty->isArrayType())
4736 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Chris Lattner86df27b2009-06-14 00:45:47 +00004738 ArgTypes.push_back(Ty);
4739 }
4740
4741 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4742 "'.' should only occur at end of builtin type list!");
4743
4744 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4745 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4746 return getFunctionNoProtoType(ResType);
4747 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4748 TypeStr[0] == '.', 0);
4749}
Eli Friedmana95d7572009-08-19 07:44:53 +00004750
4751QualType
4752ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4753 // Perform the usual unary conversions. We do this early so that
4754 // integral promotions to "int" can allow us to exit early, in the
4755 // lhs == rhs check. Also, for conversion purposes, we ignore any
4756 // qualifiers. For example, "const float" and "float" are
4757 // equivalent.
4758 if (lhs->isPromotableIntegerType())
4759 lhs = getPromotedIntegerType(lhs);
4760 else
4761 lhs = lhs.getUnqualifiedType();
4762 if (rhs->isPromotableIntegerType())
4763 rhs = getPromotedIntegerType(rhs);
4764 else
4765 rhs = rhs.getUnqualifiedType();
4766
4767 // If both types are identical, no conversion is needed.
4768 if (lhs == rhs)
4769 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004770
Eli Friedmana95d7572009-08-19 07:44:53 +00004771 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4772 // The caller can deal with this (e.g. pointer + int).
4773 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4774 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004775
4776 // At this point, we have two different arithmetic types.
4777
Eli Friedmana95d7572009-08-19 07:44:53 +00004778 // Handle complex types first (C99 6.3.1.8p1).
4779 if (lhs->isComplexType() || rhs->isComplexType()) {
4780 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004781 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004782 // convert the rhs to the lhs complex type.
4783 return lhs;
4784 }
Mike Stump1eb44332009-09-09 15:08:12 +00004785 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004786 // convert the lhs to the rhs complex type.
4787 return rhs;
4788 }
4789 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004790 // When both operands are complex, the shorter operand is converted to the
4791 // type of the longer, and that is the type of the result. This corresponds
4792 // to what is done when combining two real floating-point operands.
4793 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004794 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004795 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004796 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004797 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004798 // "double _Complex" is promoted to "long double _Complex".
4799 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004800
4801 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004802 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004803 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004804 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004805 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004806 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4807 // domains match. This is a requirement for our implementation, C99
4808 // does not require this promotion.
4809 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4810 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4811 return rhs;
4812 } else { // handle "_Complex double, double".
4813 return lhs;
4814 }
4815 }
4816 return lhs; // The domain/size match exactly.
4817 }
4818 // Now handle "real" floating types (i.e. float, double, long double).
4819 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4820 // if we have an integer operand, the result is the real floating type.
4821 if (rhs->isIntegerType()) {
4822 // convert rhs to the lhs floating point type.
4823 return lhs;
4824 }
4825 if (rhs->isComplexIntegerType()) {
4826 // convert rhs to the complex floating point type.
4827 return getComplexType(lhs);
4828 }
4829 if (lhs->isIntegerType()) {
4830 // convert lhs to the rhs floating point type.
4831 return rhs;
4832 }
Mike Stump1eb44332009-09-09 15:08:12 +00004833 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004834 // convert lhs to the complex floating point type.
4835 return getComplexType(rhs);
4836 }
4837 // We have two real floating types, float/complex combos were handled above.
4838 // Convert the smaller operand to the bigger result.
4839 int result = getFloatingTypeOrder(lhs, rhs);
4840 if (result > 0) // convert the rhs
4841 return lhs;
4842 assert(result < 0 && "illegal float comparison");
4843 return rhs; // convert the lhs
4844 }
4845 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4846 // Handle GCC complex int extension.
4847 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4848 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4849
4850 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004851 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004852 rhsComplexInt->getElementType()) >= 0)
4853 return lhs; // convert the rhs
4854 return rhs;
4855 } else if (lhsComplexInt && rhs->isIntegerType()) {
4856 // convert the rhs to the lhs complex type.
4857 return lhs;
4858 } else if (rhsComplexInt && lhs->isIntegerType()) {
4859 // convert the lhs to the rhs complex type.
4860 return rhs;
4861 }
4862 }
4863 // Finally, we have two differing integer types.
4864 // The rules for this case are in C99 6.3.1.8
4865 int compare = getIntegerTypeOrder(lhs, rhs);
4866 bool lhsSigned = lhs->isSignedIntegerType(),
4867 rhsSigned = rhs->isSignedIntegerType();
4868 QualType destType;
4869 if (lhsSigned == rhsSigned) {
4870 // Same signedness; use the higher-ranked type
4871 destType = compare >= 0 ? lhs : rhs;
4872 } else if (compare != (lhsSigned ? 1 : -1)) {
4873 // The unsigned type has greater than or equal rank to the
4874 // signed type, so use the unsigned type
4875 destType = lhsSigned ? rhs : lhs;
4876 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4877 // The two types are different widths; if we are here, that
4878 // means the signed type is larger than the unsigned type, so
4879 // use the signed type.
4880 destType = lhsSigned ? lhs : rhs;
4881 } else {
4882 // The signed type is higher-ranked than the unsigned type,
4883 // but isn't actually any bigger (like unsigned int and long
4884 // on most 32-bit systems). Use the unsigned type corresponding
4885 // to the signed type.
4886 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4887 }
4888 return destType;
4889}