blob: 442714a5a6491331486a674d07285195eb1f9e36 [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"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000025#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000027#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000028#include "RecordLayoutBuilder.h"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
32enum FloatingRank {
33 FloatRank, DoubleRank, LongDoubleRank
34};
35
Chris Lattner61710852008-10-05 17:34:18 +000036ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
37 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000038 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000039 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000040 bool FreeMem, unsigned size_reserve) :
41 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000042 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000043 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
44 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000045 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000046 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000047 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000048 ObjCIdRedefinitionType = QualType();
49 ObjCClassRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000050 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000051 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000052 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000053}
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055ASTContext::~ASTContext() {
56 // Deallocate all the types.
57 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000058 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000059 Types.pop_back();
60 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000061
Nuno Lopesb74668e2008-12-17 22:30:25 +000062 {
John McCall0953e762009-09-24 19:53:00 +000063 llvm::FoldingSet<ExtQuals>::iterator
64 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
65 while (I != E)
66 Deallocate(&*I++);
67 }
68
69 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
71 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
72 while (I != E) {
73 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
74 delete R;
75 }
76 }
77
78 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000079 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
80 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000081 while (I != E) {
82 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
83 delete R;
84 }
85 }
86
Douglas Gregorab452ba2009-03-26 23:50:42 +000087 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000088 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
89 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000090 NNSEnd = NestedNameSpecifiers.end();
91 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000092 /* Increment in loop */)
93 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000094
95 if (GlobalNestedNameSpecifier)
96 GlobalNestedNameSpecifier->Destroy(*this);
97
Eli Friedmanb26153c2008-05-27 03:08:09 +000098 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000099}
100
Mike Stump1eb44332009-09-09 15:08:12 +0000101void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000102ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
103 ExternalSource.reset(Source.take());
104}
105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106void ASTContext::PrintStats() const {
107 fprintf(stderr, "*** AST Context Stats:\n");
108 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000109
Douglas Gregordbe833d2009-05-26 14:40:08 +0000110 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000111#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112#define ABSTRACT_TYPE(Name, Parent)
113#include "clang/AST/TypeNodes.def"
114 0 // Extra
115 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000116
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
118 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000119 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 }
121
Douglas Gregordbe833d2009-05-26 14:40:08 +0000122 unsigned Idx = 0;
123 unsigned TotalBytes = 0;
124#define TYPE(Name, Parent) \
125 if (counts[Idx]) \
126 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
127 TotalBytes += counts[Idx] * sizeof(Name##Type); \
128 ++Idx;
129#define ABSTRACT_TYPE(Name, Parent)
130#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Douglas Gregordbe833d2009-05-26 14:40:08 +0000132 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000133
134 if (ExternalSource.get()) {
135 fprintf(stderr, "\n");
136 ExternalSource->PrintStats();
137 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000138}
139
140
141void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000142 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
143 R = QualType(Ty, 0);
144 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000145}
146
Reid Spencer5f016e22007-07-11 17:01:13 +0000147void ASTContext::InitBuiltinTypes() {
148 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 // C99 6.2.5p19.
151 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // C99 6.2.5p2.
154 InitBuiltinType(BoolTy, BuiltinType::Bool);
155 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000156 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 InitBuiltinType(CharTy, BuiltinType::Char_S);
158 else
159 InitBuiltinType(CharTy, BuiltinType::Char_U);
160 // C99 6.2.5p4.
161 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
162 InitBuiltinType(ShortTy, BuiltinType::Short);
163 InitBuiltinType(IntTy, BuiltinType::Int);
164 InitBuiltinType(LongTy, BuiltinType::Long);
165 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 // C99 6.2.5p6.
168 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
169 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
170 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
171 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
172 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000173
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 // C99 6.2.5p10.
175 InitBuiltinType(FloatTy, BuiltinType::Float);
176 InitBuiltinType(DoubleTy, BuiltinType::Double);
177 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000178
Chris Lattner2df9ced2009-04-30 02:43:43 +0000179 // GNU extension, 128-bit integers.
180 InitBuiltinType(Int128Ty, BuiltinType::Int128);
181 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
182
Chris Lattner3a250322009-02-26 23:43:47 +0000183 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
184 InitBuiltinType(WCharTy, BuiltinType::WChar);
185 else // C99
186 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000187
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000188 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
189 InitBuiltinType(Char16Ty, BuiltinType::Char16);
190 else // C99
191 Char16Ty = getFromTargetType(Target.getChar16Type());
192
193 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
194 InitBuiltinType(Char32Ty, BuiltinType::Char32);
195 else // C99
196 Char32Ty = getFromTargetType(Target.getChar32Type());
197
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000198 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000199 InitBuiltinType(OverloadTy, BuiltinType::Overload);
200
201 // Placeholder type for type-dependent expressions whose type is
202 // completely unknown. No code should ever check a type against
203 // DependentTy and users should never see it; however, it is here to
204 // help diagnose failures to properly check for type-dependent
205 // expressions.
206 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000207
Mike Stump1eb44332009-09-09 15:08:12 +0000208 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000209 // not yet been deduced.
210 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // C99 6.2.5p11.
213 FloatComplexTy = getComplexType(FloatTy);
214 DoubleComplexTy = getComplexType(DoubleTy);
215 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000216
Steve Naroff7e219e42007-10-15 14:41:52 +0000217 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Steve Naroffde2e22d2009-07-15 18:40:39 +0000219 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
220 ObjCIdTypedefType = QualType();
221 ObjCClassTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Steve Naroffde2e22d2009-07-15 18:40:39 +0000223 // Builtin types for 'id' and 'Class'.
224 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
225 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000229 // void * type
230 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000231
232 // nullptr type (C++0x 2.14.7)
233 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000234}
235
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000236MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000237ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000238 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000239 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000240 = InstantiatedFromStaticDataMember.find(Var);
241 if (Pos == InstantiatedFromStaticDataMember.end())
242 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 return Pos->second;
245}
246
Mike Stump1eb44332009-09-09 15:08:12 +0000247void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000248ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
249 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000250 assert(Inst->isStaticDataMember() && "Not a static data member");
251 assert(Tmpl->isStaticDataMember() && "Not a static data member");
252 assert(!InstantiatedFromStaticDataMember[Inst] &&
253 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000254 InstantiatedFromStaticDataMember[Inst]
255 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000256}
257
Anders Carlsson0d8df782009-08-29 19:37:28 +0000258UnresolvedUsingDecl *
259ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
Mike Stump1eb44332009-09-09 15:08:12 +0000260 llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::iterator Pos
Anders Carlsson0d8df782009-08-29 19:37:28 +0000261 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
262 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
263 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Anders Carlsson0d8df782009-08-29 19:37:28 +0000265 return Pos->second;
266}
267
268void
269ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
270 UnresolvedUsingDecl *UUD) {
271 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
272 "Already noted what using decl what instantiated from");
273 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
274}
275
Anders Carlssond8b285f2009-09-01 04:26:58 +0000276FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
277 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
278 = InstantiatedFromUnnamedFieldDecl.find(Field);
279 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
280 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Anders Carlssond8b285f2009-09-01 04:26:58 +0000282 return Pos->second;
283}
284
285void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
286 FieldDecl *Tmpl) {
287 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
288 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
289 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
290 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Anders Carlssond8b285f2009-09-01 04:26:58 +0000292 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
293}
294
Douglas Gregor2e222532009-07-02 17:08:52 +0000295namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000296 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000297 : std::binary_function<SourceRange, SourceRange, bool> {
298 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Douglas Gregor2e222532009-07-02 17:08:52 +0000300 public:
301 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Douglas Gregor2e222532009-07-02 17:08:52 +0000303 bool operator()(SourceRange X, SourceRange Y) {
304 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
305 }
306 };
307}
308
309/// \brief Determine whether the given comment is a Doxygen-style comment.
310///
311/// \param Start the start of the comment text.
312///
313/// \param End the end of the comment text.
314///
315/// \param Member whether we want to check whether this is a member comment
316/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
317/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000318static bool
319isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000321 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000322 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
323 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
324 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 if (End - Start < 4)
327 return false;
328
329 assert(Start[0] == '/' && "Not a comment?");
330 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
331 return false;
332 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
333 return false;
334
335 return (Start[3] == '<') == Member;
336}
337
338/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000340const char *ASTContext::getCommentForDecl(const Decl *D) {
341 if (!D)
342 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Douglas Gregor2e222532009-07-02 17:08:52 +0000344 // Check whether we have cached a comment string for this declaration
345 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000346 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000347 = DeclComments.find(D);
348 if (Pos != DeclComments.end())
349 return Pos->second.c_str();
350
Mike Stump1eb44332009-09-09 15:08:12 +0000351 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000352 // that source, do so now.
353 if (ExternalSource && !LoadedExternalComments) {
354 std::vector<SourceRange> LoadedComments;
355 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregor2e222532009-07-02 17:08:52 +0000357 if (!LoadedComments.empty())
358 Comments.insert(Comments.begin(), LoadedComments.begin(),
359 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor2e222532009-07-02 17:08:52 +0000361 LoadedExternalComments = true;
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
364 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000365 if (Comments.empty())
366 return 0;
367
368 // If the declaration doesn't map directly to a location in a file, we
369 // can't find the comment.
370 SourceLocation DeclStartLoc = D->getLocStart();
371 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
372 return 0;
373
374 // Find the comment that occurs just before this declaration.
375 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000376 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000377 SourceRange(DeclStartLoc),
378 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 // Decompose the location for the start of the declaration and find the
381 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000382 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000383 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000384 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000385 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor2e222532009-07-02 17:08:52 +0000387 // First check whether we have a comment for a member.
388 if (LastComment != Comments.end() &&
389 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
390 isDoxygenComment(SourceMgr, *LastComment, true)) {
391 std::pair<FileID, unsigned> LastCommentEndDecomp
392 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
393 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
394 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000395 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000396 LastCommentEndDecomp.second)) {
397 // The Doxygen member comment comes after the declaration starts and
398 // is on the same line and in the same file as the declaration. This
399 // is the comment we want.
400 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000401 Result.append(FileBufferStart +
402 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 FileBufferStart + LastCommentEndDecomp.second + 1);
404 return Result.c_str();
405 }
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 if (LastComment == Comments.begin())
409 return 0;
410 --LastComment;
411
412 // Decompose the end of the comment.
413 std::pair<FileID, unsigned> LastCommentEndDecomp
414 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Douglas Gregor2e222532009-07-02 17:08:52 +0000416 // If the comment and the declaration aren't in the same file, then they
417 // aren't related.
418 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
419 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Douglas Gregor2e222532009-07-02 17:08:52 +0000421 // Check that we actually have a Doxygen comment.
422 if (!isDoxygenComment(SourceMgr, *LastComment))
423 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregor2e222532009-07-02 17:08:52 +0000425 // Compute the starting line for the declaration and for the end of the
426 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000427 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000428 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
429 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000430 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000431 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Douglas Gregor2e222532009-07-02 17:08:52 +0000433 // If the comment does not end on the line prior to the declaration, then
434 // the comment is not associated with the declaration at all.
435 if (CommentEndLine + 1 != DeclStartLine)
436 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Douglas Gregor2e222532009-07-02 17:08:52 +0000438 // We have a comment, but there may be more comments on the previous lines.
439 // Keep looking so long as the comments are still Doxygen comments and are
440 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000441 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000442 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
443 std::vector<SourceRange>::iterator FirstComment = LastComment;
444 while (FirstComment != Comments.begin()) {
445 // Look at the previous comment
446 --FirstComment;
447 std::pair<FileID, unsigned> Decomp
448 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor2e222532009-07-02 17:08:52 +0000450 // If this previous comment is in a different file, we're done.
451 if (Decomp.first != DeclStartDecomp.first) {
452 ++FirstComment;
453 break;
454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-07-02 17:08:52 +0000456 // If this comment is not a Doxygen comment, we're done.
457 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
458 ++FirstComment;
459 break;
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregor2e222532009-07-02 17:08:52 +0000462 // If the line number is not what we expected, we're done.
463 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
464 if (Line != ExpectedLine) {
465 ++FirstComment;
466 break;
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregor2e222532009-07-02 17:08:52 +0000469 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000470 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000471 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Douglas Gregor2e222532009-07-02 17:08:52 +0000474 // The iterator range [FirstComment, LastComment] contains all of the
475 // BCPL comments that, together, are associated with this declaration.
476 // Form a single comment block string for this declaration that concatenates
477 // all of these comments.
478 std::string &Result = DeclComments[D];
479 while (FirstComment != LastComment) {
480 std::pair<FileID, unsigned> DecompStart
481 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
482 std::pair<FileID, unsigned> DecompEnd
483 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
484 Result.append(FileBufferStart + DecompStart.second,
485 FileBufferStart + DecompEnd.second + 1);
486 ++FirstComment;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregor2e222532009-07-02 17:08:52 +0000489 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000490 Result.append(FileBufferStart +
491 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 FileBufferStart + LastCommentEndDecomp.second + 1);
493 return Result.c_str();
494}
495
Chris Lattner464175b2007-07-18 17:52:12 +0000496//===----------------------------------------------------------------------===//
497// Type Sizing and Analysis
498//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000499
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000500/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
501/// scalar floating point type.
502const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000503 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000504 assert(BT && "Not a floating point type!");
505 switch (BT->getKind()) {
506 default: assert(0 && "Not a floating point type!");
507 case BuiltinType::Float: return Target.getFloatFormat();
508 case BuiltinType::Double: return Target.getDoubleFormat();
509 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
510 }
511}
512
Mike Stump196efbf2009-09-22 02:43:44 +0000513/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000514/// specified decl. Note that bitfields do not have a valid alignment, so
515/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000516unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000517 unsigned Align = Target.getCharWidth();
518
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000519 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000520 Align = std::max(Align, AA->getAlignment());
521
Chris Lattneraf707ab2009-01-24 21:53:27 +0000522 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
523 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000524 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000525 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000526 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000527 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
528 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000529 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
530 T = cast<ArrayType>(T)->getElementType();
531
532 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
533 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000534 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000535
536 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000538
Chris Lattnera7674d82007-07-13 22:13:22 +0000539/// getTypeSize - Return the size of the specified type, in bits. This method
540/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000541///
542/// FIXME: Pointers into different addr spaces could have different sizes and
543/// alignment requirements: getPointerInfo should take an AddrSpace, this
544/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000545std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000546ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000547 uint64_t Width=0;
548 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000549 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000550#define TYPE(Class, Base)
551#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000552#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000553#define DEPENDENT_TYPE(Class, Base) case Type::Class:
554#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000555 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000556 break;
557
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +0000558 case Type::ObjCProtocolList:
559 assert(false && "Should not see protocol list types");
560 break;
561
Chris Lattner692233e2007-07-13 22:27:08 +0000562 case Type::FunctionNoProto:
563 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000564 // GCC extension: alignof(function) = 32 bits
565 Width = 0;
566 Align = 32;
567 break;
568
Douglas Gregor72564e72009-02-26 23:50:07 +0000569 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000570 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000571 Width = 0;
572 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
573 break;
574
Steve Narofffb22d962007-08-30 01:06:46 +0000575 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000576 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner98be4942008-03-05 18:54:05 +0000578 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000579 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000580 Align = EltInfo.second;
581 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000582 }
Nate Begeman213541a2008-04-18 23:10:10 +0000583 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000584 case Type::Vector: {
Mike Stump1eb44332009-09-09 15:08:12 +0000585 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000586 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000587 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000588 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000589 // If the alignment is not a power of 2, round up to the next power of 2.
590 // This happens for non-power-of-2 length vectors.
591 // FIXME: this should probably be a target property.
592 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000593 break;
594 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000595
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000596 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000597 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000598 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000599 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000600 // GCC extension: alignof(void) = 8 bits.
601 Width = 0;
602 Align = 8;
603 break;
604
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000605 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000606 Width = Target.getBoolWidth();
607 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000608 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000609 case BuiltinType::Char_S:
610 case BuiltinType::Char_U:
611 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000612 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000613 Width = Target.getCharWidth();
614 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000615 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000616 case BuiltinType::WChar:
617 Width = Target.getWCharWidth();
618 Align = Target.getWCharAlign();
619 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000620 case BuiltinType::Char16:
621 Width = Target.getChar16Width();
622 Align = Target.getChar16Align();
623 break;
624 case BuiltinType::Char32:
625 Width = Target.getChar32Width();
626 Align = Target.getChar32Align();
627 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000628 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000629 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000630 Width = Target.getShortWidth();
631 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000632 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000633 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000635 Width = Target.getIntWidth();
636 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000637 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000638 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = Target.getLongWidth();
641 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000643 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000645 Width = Target.getLongLongWidth();
646 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000647 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000648 case BuiltinType::Int128:
649 case BuiltinType::UInt128:
650 Width = 128;
651 Align = 128; // int128_t is 128-bit aligned on all targets.
652 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000653 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000654 Width = Target.getFloatWidth();
655 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000656 break;
657 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000658 Width = Target.getDoubleWidth();
659 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000660 break;
661 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000662 Width = Target.getLongDoubleWidth();
663 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000664 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000665 case BuiltinType::NullPtr:
666 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
667 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000668 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000669 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000670 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000671 case Type::FixedWidthInt:
672 // FIXME: This isn't precisely correct; the width/alignment should depend
673 // on the available types for the target
674 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000675 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000676 Align = Width;
677 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000678 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000679 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000680 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000681 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000682 case Type::BlockPointer: {
683 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
684 Width = Target.getPointerWidth(AS);
685 Align = Target.getPointerAlign(AS);
686 break;
687 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000688 case Type::Pointer: {
689 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000690 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000691 Align = Target.getPointerAlign(AS);
692 break;
693 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000694 case Type::LValueReference:
695 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000696 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000697 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000698 // FIXME: This is wrong for struct layout: a reference in a struct has
699 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000700 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000701 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000702 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
703 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
704 // If we ever want to support other ABIs this needs to be abstracted.
705
Sebastian Redlf30208a2009-01-24 21:16:55 +0000706 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000707 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000708 getTypeInfo(getPointerDiffType());
709 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000710 if (Pointee->isFunctionType())
711 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000712 Align = PtrDiffInfo.second;
713 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000714 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000715 case Type::Complex: {
716 // Complex types have the same alignment as their elements, but twice the
717 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000718 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000719 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000720 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000721 Align = EltInfo.second;
722 break;
723 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000724 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000725 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000726 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
727 Width = Layout.getSize();
728 Align = Layout.getAlignment();
729 break;
730 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000731 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000732 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000733 const TagType *TT = cast<TagType>(T);
734
735 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000736 Width = 1;
737 Align = 1;
738 break;
739 }
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Daniel Dunbar1d751182008-11-08 05:48:37 +0000741 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000742 return getTypeInfo(ET->getDecl()->getIntegerType());
743
Daniel Dunbar1d751182008-11-08 05:48:37 +0000744 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000745 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
746 Width = Layout.getSize();
747 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000748 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000749 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000750
John McCall49a832b2009-10-18 09:09:24 +0000751 case Type::SubstTemplateTypeParm: {
752 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
753 getReplacementType().getTypePtr());
754 }
755
John McCall7da24312009-09-05 00:15:47 +0000756 case Type::Elaborated: {
757 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType().getTypePtr());
758 }
759
Douglas Gregor18857642009-04-30 17:32:17 +0000760 case Type::Typedef: {
761 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000762 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000763 Align = Aligned->getAlignment();
764 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
765 } else
766 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000767 break;
Chris Lattner71763312008-04-06 22:05:18 +0000768 }
Douglas Gregor18857642009-04-30 17:32:17 +0000769
770 case Type::TypeOfExpr:
771 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
772 .getTypePtr());
773
774 case Type::TypeOf:
775 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
776
Anders Carlsson395b4752009-06-24 19:06:50 +0000777 case Type::Decltype:
778 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
779 .getTypePtr());
780
Douglas Gregor18857642009-04-30 17:32:17 +0000781 case Type::QualifiedName:
782 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregor18857642009-04-30 17:32:17 +0000784 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000785 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000786 "Cannot request the size of a dependent type");
787 // FIXME: this is likely to be wrong once we support template
788 // aliases, since a template alias could refer to a typedef that
789 // has an __aligned__ attribute on it.
790 return getTypeInfo(getCanonicalType(T));
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner464175b2007-07-18 17:52:12 +0000793 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000794 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000795}
796
Chris Lattner34ebde42009-01-27 18:08:34 +0000797/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
798/// type for the current target in bits. This can be different than the ABI
799/// alignment in cases where it is beneficial for performance to overalign
800/// a data type.
801unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
802 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000803
804 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000805 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000806 T = CT->getElementType().getTypePtr();
807 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
808 T->isSpecificBuiltinType(BuiltinType::LongLong))
809 return std::max(ABIAlign, (unsigned)getTypeSize(T));
810
Chris Lattner34ebde42009-01-27 18:08:34 +0000811 return ABIAlign;
812}
813
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000814static void CollectLocalObjCIvars(ASTContext *Ctx,
815 const ObjCInterfaceDecl *OI,
816 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000817 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
818 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000819 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000820 if (!IVDecl->isInvalidDecl())
821 Fields.push_back(cast<FieldDecl>(IVDecl));
822 }
823}
824
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000825void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
826 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
827 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
828 CollectObjCIvars(SuperClass, Fields);
829 CollectLocalObjCIvars(this, OI, Fields);
830}
831
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000832/// ShallowCollectObjCIvars -
833/// Collect all ivars, including those synthesized, in the current class.
834///
835void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
836 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
837 bool CollectSynthesized) {
838 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
839 E = OI->ivar_end(); I != E; ++I) {
840 Ivars.push_back(*I);
841 }
842 if (CollectSynthesized)
843 CollectSynthesizedIvars(OI, Ivars);
844}
845
Fariborz Jahanian98200742009-05-12 18:14:29 +0000846void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
847 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000848 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
849 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000850 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
851 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Fariborz Jahanian98200742009-05-12 18:14:29 +0000853 // Also look into nested protocols.
854 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
855 E = PD->protocol_end(); P != E; ++P)
856 CollectProtocolSynthesizedIvars(*P, Ivars);
857}
858
859/// CollectSynthesizedIvars -
860/// This routine collect synthesized ivars for the designated class.
861///
862void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
863 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000864 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
865 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000866 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
867 Ivars.push_back(Ivar);
868 }
869 // Also look into interface's protocol list for properties declared
870 // in the protocol and whose ivars are synthesized.
871 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
872 PE = OI->protocol_end(); P != PE; ++P) {
873 ObjCProtocolDecl *PD = (*P);
874 CollectProtocolSynthesizedIvars(PD, Ivars);
875 }
876}
877
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000878unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
879 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000880 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
881 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000882 if ((*I)->getPropertyIvarDecl())
883 ++count;
884
885 // Also look into nested protocols.
886 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
887 E = PD->protocol_end(); P != E; ++P)
888 count += CountProtocolSynthesizedIvars(*P);
889 return count;
890}
891
Mike Stump1eb44332009-09-09 15:08:12 +0000892unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000893 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000894 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
895 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000896 if ((*I)->getPropertyIvarDecl())
897 ++count;
898 }
899 // Also look into interface's protocol list for properties declared
900 // in the protocol and whose ivars are synthesized.
901 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
902 PE = OI->protocol_end(); P != PE; ++P) {
903 ObjCProtocolDecl *PD = (*P);
904 count += CountProtocolSynthesizedIvars(PD);
905 }
906 return count;
907}
908
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000909/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
910ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
911 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
912 I = ObjCImpls.find(D);
913 if (I != ObjCImpls.end())
914 return cast<ObjCImplementationDecl>(I->second);
915 return 0;
916}
917/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
918ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
919 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
920 I = ObjCImpls.find(D);
921 if (I != ObjCImpls.end())
922 return cast<ObjCCategoryImplDecl>(I->second);
923 return 0;
924}
925
926/// \brief Set the implementation of ObjCInterfaceDecl.
927void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
928 ObjCImplementationDecl *ImplD) {
929 assert(IFaceD && ImplD && "Passed null params");
930 ObjCImpls[IFaceD] = ImplD;
931}
932/// \brief Set the implementation of ObjCCategoryDecl.
933void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
934 ObjCCategoryImplDecl *ImplD) {
935 assert(CatD && ImplD && "Passed null params");
936 ObjCImpls[CatD] = ImplD;
937}
938
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000939/// \brief Allocate an uninitialized DeclaratorInfo.
940///
941/// The caller should initialize the memory held by DeclaratorInfo using
942/// the TypeLoc wrappers.
943///
944/// \param T the type that will be the basis for type source info. This type
945/// should refer to how the declarator was written in source code, not to
946/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +0000947DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
948 unsigned DataSize) {
949 if (!DataSize)
950 DataSize = TypeLoc::getFullDataSizeForType(T);
951 else
952 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
953 "incorrect data size provided to CreateDeclaratorInfo!");
954
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000955 DeclaratorInfo *DInfo =
956 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
957 new (DInfo) DeclaratorInfo(T);
958 return DInfo;
959}
960
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000961/// getInterfaceLayoutImpl - Get or compute information about the
962/// layout of the given interface.
963///
964/// \param Impl - If given, also include the layout of the interface's
965/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000966const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000967ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
968 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000969 assert(!D->isForwardDecl() && "Invalid interface decl!");
970
Devang Patel44a3dde2008-06-04 21:54:36 +0000971 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +0000972 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000973 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
974 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
975 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000976
Daniel Dunbar453addb2009-05-03 11:16:44 +0000977 // Add in synthesized ivar count if laying out an implementation.
978 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000979 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000980 unsigned SynthCount = CountSynthesizedIvars(D);
981 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000982 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000983 // entry. Note we can't cache this because we simply free all
984 // entries later; however we shouldn't look up implementations
985 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000986 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000987 return getObjCLayout(D, 0);
988 }
989
Mike Stump1eb44332009-09-09 15:08:12 +0000990 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +0000991 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
992 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Devang Patel44a3dde2008-06-04 21:54:36 +0000994 return *NewEntry;
995}
996
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000997const ASTRecordLayout &
998ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
999 return getObjCLayout(D, 0);
1000}
1001
1002const ASTRecordLayout &
1003ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1004 return getObjCLayout(D->getClassInterface(), D);
1005}
1006
Devang Patel88a981b2007-11-01 19:11:01 +00001007/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001008/// specified record (struct/union/class), which indicates its size and field
1009/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001010const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001011 D = D->getDefinition(*this);
1012 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001013
Chris Lattner464175b2007-07-18 17:52:12 +00001014 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001015 // Note that we can't save a reference to the entry because this function
1016 // is recursive.
1017 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001018 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001019
Mike Stump1eb44332009-09-09 15:08:12 +00001020 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001021 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001022 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner5d2a6302007-07-18 18:26:58 +00001024 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001025}
1026
Chris Lattnera7674d82007-07-13 22:13:22 +00001027//===----------------------------------------------------------------------===//
1028// Type creation/memoization methods
1029//===----------------------------------------------------------------------===//
1030
John McCall0953e762009-09-24 19:53:00 +00001031QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1032 unsigned Fast = Quals.getFastQualifiers();
1033 Quals.removeFastQualifiers();
1034
1035 // Check if we've already instantiated this type.
1036 llvm::FoldingSetNodeID ID;
1037 ExtQuals::Profile(ID, TypeNode, Quals);
1038 void *InsertPos = 0;
1039 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1040 assert(EQ->getQualifiers() == Quals);
1041 QualType T = QualType(EQ, Fast);
1042 return T;
1043 }
1044
John McCall6b304a02009-09-24 23:30:46 +00001045 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001046 ExtQualNodes.InsertNode(New, InsertPos);
1047 QualType T = QualType(New, Fast);
1048 return T;
1049}
1050
1051QualType ASTContext::getVolatileType(QualType T) {
1052 QualType CanT = getCanonicalType(T);
1053 if (CanT.isVolatileQualified()) return T;
1054
1055 QualifierCollector Quals;
1056 const Type *TypeNode = Quals.strip(T);
1057 Quals.addVolatile();
1058
1059 return getExtQualType(TypeNode, Quals);
1060}
1061
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001062QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001063 QualType CanT = getCanonicalType(T);
1064 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001065 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001066
John McCall0953e762009-09-24 19:53:00 +00001067 // If we are composing extended qualifiers together, merge together
1068 // into one ExtQuals node.
1069 QualifierCollector Quals;
1070 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
John McCall0953e762009-09-24 19:53:00 +00001072 // If this type already has an address space specified, it cannot get
1073 // another one.
1074 assert(!Quals.hasAddressSpace() &&
1075 "Type cannot be in multiple addr spaces!");
1076 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001077
John McCall0953e762009-09-24 19:53:00 +00001078 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001079}
1080
Chris Lattnerb7d25532009-02-18 22:53:11 +00001081QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001082 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001083 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001084 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001085 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001087 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001088 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001089 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001090 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1091 return getPointerType(ResultType);
1092 }
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
John McCall0953e762009-09-24 19:53:00 +00001095 // If we are composing extended qualifiers together, merge together
1096 // into one ExtQuals node.
1097 QualifierCollector Quals;
1098 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001099
John McCall0953e762009-09-24 19:53:00 +00001100 // If this type already has an ObjCGC specified, it cannot get
1101 // another one.
1102 assert(!Quals.hasObjCGCAttr() &&
1103 "Type cannot have multiple ObjCGCs!");
1104 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
John McCall0953e762009-09-24 19:53:00 +00001106 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001107}
Chris Lattnera7674d82007-07-13 22:13:22 +00001108
Mike Stump24556362009-07-25 21:26:53 +00001109QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001110 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001111 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001112 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001113 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001114 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001115 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001116 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001117 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001118 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001119 } else {
1120 assert (T->isFunctionType()
1121 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001123 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1124 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001125 } else {
1126 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1127 ResultType
1128 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1129 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1130 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1131 F->getNumExceptions(), F->exception_begin(), true);
1132 }
Mike Stump24556362009-07-25 21:26:53 +00001133 }
John McCall0953e762009-09-24 19:53:00 +00001134
1135 return getQualifiedType(ResultType, T.getQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001136}
1137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138/// getComplexType - Return the uniqued reference to the type for a complex
1139/// number with the specified element type.
1140QualType ASTContext::getComplexType(QualType T) {
1141 // Unique pointers, to guarantee there is only one pointer of a particular
1142 // structure.
1143 llvm::FoldingSetNodeID ID;
1144 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 void *InsertPos = 0;
1147 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1148 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 // If the pointee type isn't canonical, this won't be a canonical type either,
1151 // so fill in the canonical type field.
1152 QualType Canonical;
1153 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001154 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 // Get the new insert position for the node we care about.
1157 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001158 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 }
John McCall6b304a02009-09-24 23:30:46 +00001160 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 Types.push_back(New);
1162 ComplexTypes.InsertNode(New, InsertPos);
1163 return QualType(New, 0);
1164}
1165
Eli Friedmanf98aba32009-02-13 02:31:07 +00001166QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1167 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1168 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1169 FixedWidthIntType *&Entry = Map[Width];
1170 if (!Entry)
1171 Entry = new FixedWidthIntType(Width, Signed);
1172 return QualType(Entry, 0);
1173}
Reid Spencer5f016e22007-07-11 17:01:13 +00001174
1175/// getPointerType - Return the uniqued reference to the type for a pointer to
1176/// the specified type.
1177QualType ASTContext::getPointerType(QualType T) {
1178 // Unique pointers, to guarantee there is only one pointer of a particular
1179 // structure.
1180 llvm::FoldingSetNodeID ID;
1181 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 void *InsertPos = 0;
1184 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1185 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 // If the pointee type isn't canonical, this won't be a canonical type either,
1188 // so fill in the canonical type field.
1189 QualType Canonical;
1190 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001191 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 // Get the new insert position for the node we care about.
1194 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001195 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 }
John McCall6b304a02009-09-24 23:30:46 +00001197 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 Types.push_back(New);
1199 PointerTypes.InsertNode(New, InsertPos);
1200 return QualType(New, 0);
1201}
1202
Mike Stump1eb44332009-09-09 15:08:12 +00001203/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001204/// a pointer to the specified block.
1205QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001206 assert(T->isFunctionType() && "block of function types only");
1207 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001208 // structure.
1209 llvm::FoldingSetNodeID ID;
1210 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Steve Naroff5618bd42008-08-27 16:04:49 +00001212 void *InsertPos = 0;
1213 if (BlockPointerType *PT =
1214 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1215 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001216
1217 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001218 // type either so fill in the canonical type field.
1219 QualType Canonical;
1220 if (!T->isCanonical()) {
1221 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Steve Naroff5618bd42008-08-27 16:04:49 +00001223 // Get the new insert position for the node we care about.
1224 BlockPointerType *NewIP =
1225 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001226 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001227 }
John McCall6b304a02009-09-24 23:30:46 +00001228 BlockPointerType *New
1229 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001230 Types.push_back(New);
1231 BlockPointerTypes.InsertNode(New, InsertPos);
1232 return QualType(New, 0);
1233}
1234
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001235/// getLValueReferenceType - Return the uniqued reference to the type for an
1236/// lvalue reference to the specified type.
1237QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 // Unique pointers, to guarantee there is only one pointer of a particular
1239 // structure.
1240 llvm::FoldingSetNodeID ID;
1241 ReferenceType::Profile(ID, T);
1242
1243 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001244 if (LValueReferenceType *RT =
1245 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001247
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 // If the referencee type isn't canonical, this won't be a canonical type
1249 // either, so fill in the canonical type field.
1250 QualType Canonical;
1251 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001252 Canonical = getLValueReferenceType(getCanonicalType(T));
1253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001255 LValueReferenceType *NewIP =
1256 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001257 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 }
1259
John McCall6b304a02009-09-24 23:30:46 +00001260 LValueReferenceType *New
1261 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001263 LValueReferenceTypes.InsertNode(New, InsertPos);
1264 return QualType(New, 0);
1265}
1266
1267/// getRValueReferenceType - Return the uniqued reference to the type for an
1268/// rvalue reference to the specified type.
1269QualType ASTContext::getRValueReferenceType(QualType T) {
1270 // Unique pointers, to guarantee there is only one pointer of a particular
1271 // structure.
1272 llvm::FoldingSetNodeID ID;
1273 ReferenceType::Profile(ID, T);
1274
1275 void *InsertPos = 0;
1276 if (RValueReferenceType *RT =
1277 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1278 return QualType(RT, 0);
1279
1280 // If the referencee type isn't canonical, this won't be a canonical type
1281 // either, so fill in the canonical type field.
1282 QualType Canonical;
1283 if (!T->isCanonical()) {
1284 Canonical = getRValueReferenceType(getCanonicalType(T));
1285
1286 // Get the new insert position for the node we care about.
1287 RValueReferenceType *NewIP =
1288 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1289 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1290 }
1291
John McCall6b304a02009-09-24 23:30:46 +00001292 RValueReferenceType *New
1293 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294 Types.push_back(New);
1295 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 return QualType(New, 0);
1297}
1298
Sebastian Redlf30208a2009-01-24 21:16:55 +00001299/// getMemberPointerType - Return the uniqued reference to the type for a
1300/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001301QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001302 // Unique pointers, to guarantee there is only one pointer of a particular
1303 // structure.
1304 llvm::FoldingSetNodeID ID;
1305 MemberPointerType::Profile(ID, T, Cls);
1306
1307 void *InsertPos = 0;
1308 if (MemberPointerType *PT =
1309 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1310 return QualType(PT, 0);
1311
1312 // If the pointee or class type isn't canonical, this won't be a canonical
1313 // type either, so fill in the canonical type field.
1314 QualType Canonical;
1315 if (!T->isCanonical()) {
1316 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1317
1318 // Get the new insert position for the node we care about.
1319 MemberPointerType *NewIP =
1320 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1321 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1322 }
John McCall6b304a02009-09-24 23:30:46 +00001323 MemberPointerType *New
1324 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001325 Types.push_back(New);
1326 MemberPointerTypes.InsertNode(New, InsertPos);
1327 return QualType(New, 0);
1328}
1329
Mike Stump1eb44332009-09-09 15:08:12 +00001330/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001331/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001332QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001333 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001334 ArrayType::ArraySizeModifier ASM,
1335 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001336 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1337 "Constant array of VLAs is illegal!");
1338
Chris Lattner38aeec72009-05-13 04:12:56 +00001339 // Convert the array size into a canonical width matching the pointer size for
1340 // the target.
1341 llvm::APInt ArySize(ArySizeIn);
1342 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001345 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001348 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001349 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // If the element type isn't canonical, this won't be a canonical type either,
1353 // so fill in the canonical type field.
1354 QualType Canonical;
1355 if (!EltTy->isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001356 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001357 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001359 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001360 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001361 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 }
Mike Stump1eb44332009-09-09 15:08:12 +00001363
John McCall6b304a02009-09-24 23:30:46 +00001364 ConstantArrayType *New = new(*this,TypeAlignment)
1365 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001366 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 Types.push_back(New);
1368 return QualType(New, 0);
1369}
1370
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001371/// getVariableArrayType - Returns a non-unique reference to the type for a
1372/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001373QualType ASTContext::getVariableArrayType(QualType EltTy,
1374 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001375 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001376 unsigned EltTypeQuals,
1377 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001378 // Since we don't unique expressions, it isn't possible to unique VLA's
1379 // that have an expression provided for their size.
1380
John McCall6b304a02009-09-24 23:30:46 +00001381 VariableArrayType *New = new(*this, TypeAlignment)
1382 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001383
1384 VariableArrayTypes.push_back(New);
1385 Types.push_back(New);
1386 return QualType(New, 0);
1387}
1388
Douglas Gregor898574e2008-12-05 23:32:09 +00001389/// getDependentSizedArrayType - Returns a non-unique reference to
1390/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001391/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001392QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1393 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001394 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001395 unsigned EltTypeQuals,
1396 SourceRange Brackets) {
Mike Stump1eb44332009-09-09 15:08:12 +00001397 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001398 "Size must be type- or value-dependent!");
1399
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001400 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001401 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001402 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001403
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001404 void *InsertPos = 0;
1405 DependentSizedArrayType *Canon
1406 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1407 DependentSizedArrayType *New;
1408 if (Canon) {
1409 // We already have a canonical version of this array type; use it as
1410 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001411 New = new (*this, TypeAlignment)
1412 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1413 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001414 } else {
1415 QualType CanonEltTy = getCanonicalType(EltTy);
1416 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001417 New = new (*this, TypeAlignment)
1418 DependentSizedArrayType(*this, EltTy, QualType(),
1419 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001420 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1421 } else {
1422 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1423 ASM, EltTypeQuals,
1424 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001425 New = new (*this, TypeAlignment)
1426 DependentSizedArrayType(*this, EltTy, Canon,
1427 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001428 }
1429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Douglas Gregor898574e2008-12-05 23:32:09 +00001431 Types.push_back(New);
1432 return QualType(New, 0);
1433}
1434
Eli Friedmanc5773c42008-02-15 18:16:39 +00001435QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1436 ArrayType::ArraySizeModifier ASM,
1437 unsigned EltTypeQuals) {
1438 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001439 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001440
1441 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001442 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001443 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1444 return QualType(ATP, 0);
1445
1446 // If the element type isn't canonical, this won't be a canonical type
1447 // either, so fill in the canonical type field.
1448 QualType Canonical;
1449
1450 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001451 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001452 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001453
1454 // Get the new insert position for the node we care about.
1455 IncompleteArrayType *NewIP =
1456 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001457 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001458 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001459
John McCall6b304a02009-09-24 23:30:46 +00001460 IncompleteArrayType *New = new (*this, TypeAlignment)
1461 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001462
1463 IncompleteArrayTypes.InsertNode(New, InsertPos);
1464 Types.push_back(New);
1465 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001466}
1467
Steve Naroff73322922007-07-18 18:00:27 +00001468/// getVectorType - Return the unique reference to a vector type of
1469/// the specified element type and size. VectorType must be a built-in type.
1470QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattnerf52ab252008-04-06 22:59:24 +00001473 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001474 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // Check if we've already instantiated a vector of this type.
1477 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001478 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 void *InsertPos = 0;
1480 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1481 return QualType(VTP, 0);
1482
1483 // If the element type isn't canonical, this won't be a canonical type either,
1484 // so fill in the canonical type field.
1485 QualType Canonical;
1486 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001487 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 // Get the new insert position for the node we care about.
1490 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001491 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 }
John McCall6b304a02009-09-24 23:30:46 +00001493 VectorType *New = new (*this, TypeAlignment)
1494 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 VectorTypes.InsertNode(New, InsertPos);
1496 Types.push_back(New);
1497 return QualType(New, 0);
1498}
1499
Nate Begeman213541a2008-04-18 23:10:10 +00001500/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001501/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001502QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001503 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Chris Lattnerf52ab252008-04-06 22:59:24 +00001505 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001506 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Steve Naroff73322922007-07-18 18:00:27 +00001508 // Check if we've already instantiated a vector of this type.
1509 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001510 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001511 void *InsertPos = 0;
1512 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1513 return QualType(VTP, 0);
1514
1515 // If the element type isn't canonical, this won't be a canonical type either,
1516 // so fill in the canonical type field.
1517 QualType Canonical;
1518 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001519 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Steve Naroff73322922007-07-18 18:00:27 +00001521 // Get the new insert position for the node we care about.
1522 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001523 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001524 }
John McCall6b304a02009-09-24 23:30:46 +00001525 ExtVectorType *New = new (*this, TypeAlignment)
1526 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001527 VectorTypes.InsertNode(New, InsertPos);
1528 Types.push_back(New);
1529 return QualType(New, 0);
1530}
1531
Mike Stump1eb44332009-09-09 15:08:12 +00001532QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001533 Expr *SizeExpr,
1534 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001535 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001536 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001537 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001539 void *InsertPos = 0;
1540 DependentSizedExtVectorType *Canon
1541 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1542 DependentSizedExtVectorType *New;
1543 if (Canon) {
1544 // We already have a canonical version of this array type; use it as
1545 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001546 New = new (*this, TypeAlignment)
1547 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1548 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001549 } else {
1550 QualType CanonVecTy = getCanonicalType(vecType);
1551 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001552 New = new (*this, TypeAlignment)
1553 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1554 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001555 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1556 } else {
1557 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1558 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001559 New = new (*this, TypeAlignment)
1560 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001561 }
1562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001564 Types.push_back(New);
1565 return QualType(New, 0);
1566}
1567
Douglas Gregor72564e72009-02-26 23:50:07 +00001568/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001569///
Mike Stump24556362009-07-25 21:26:53 +00001570QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Unique functions, to guarantee there is only one function of a particular
1572 // structure.
1573 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001574 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001577 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001578 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 QualType Canonical;
1582 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001583 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001586 FunctionNoProtoType *NewIP =
1587 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001588 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
John McCall6b304a02009-09-24 23:30:46 +00001591 FunctionNoProtoType *New = new (*this, TypeAlignment)
1592 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001594 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 return QualType(New, 0);
1596}
1597
1598/// getFunctionType - Return a normal function type with a typed argument
1599/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001600QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001601 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001602 unsigned TypeQuals, bool hasExceptionSpec,
1603 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001604 const QualType *ExArray, bool NoReturn) {
Anders Carlsson83913e32009-09-16 23:47:08 +00001605 if (LangOpts.CPlusPlus) {
1606 for (unsigned i = 0; i != NumArgs; ++i)
John McCall0953e762009-09-24 19:53:00 +00001607 assert(!ArgArray[i].hasQualifiers() &&
1608 "C++ arguments can't have toplevel qualifiers!");
Anders Carlsson83913e32009-09-16 23:47:08 +00001609 }
1610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 // Unique functions, to guarantee there is only one function of a particular
1612 // structure.
1613 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001614 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001615 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001616 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001617
1618 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001619 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001620 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001622
1623 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001625 if (hasExceptionSpec)
1626 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1628 if (!ArgArray[i]->isCanonical())
1629 isCanonical = false;
1630
1631 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001632 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 QualType Canonical;
1634 if (!isCanonical) {
1635 llvm::SmallVector<QualType, 16> CanonicalArgs;
1636 CanonicalArgs.reserve(NumArgs);
1637 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001638 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001639
Chris Lattnerf52ab252008-04-06 22:59:24 +00001640 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001641 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001642 isVariadic, TypeQuals, false,
1643 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001646 FunctionProtoType *NewIP =
1647 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001648 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001650
Douglas Gregor72564e72009-02-26 23:50:07 +00001651 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001652 // for two variable size arrays (for parameter and exception types) at the
1653 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001654 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001655 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1656 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001657 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001658 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001659 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001660 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001662 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 return QualType(FTP, 0);
1664}
1665
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001666/// getTypeDeclType - Return the unique reference to the type for the
1667/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001668QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001669 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001670 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001672 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001673 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001674 else if (isa<TemplateTypeParmDecl>(Decl)) {
1675 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001676 } else if (ObjCInterfaceDecl *ObjCInterface
1677 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001678 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001679
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001680 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001681 if (PrevDecl)
1682 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001683 else
John McCall6b304a02009-09-24 23:30:46 +00001684 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001685 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001686 if (PrevDecl)
1687 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001688 else
John McCall6b304a02009-09-24 23:30:46 +00001689 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001690 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001691 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001692
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001693 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001694 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001695}
1696
Reid Spencer5f016e22007-07-11 17:01:13 +00001697/// getTypedefType - Return the unique reference to the type for the
1698/// specified typename decl.
1699QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1700 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Chris Lattnerf52ab252008-04-06 22:59:24 +00001702 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001703 Decl->TypeForDecl = new(*this, TypeAlignment)
1704 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 Types.push_back(Decl->TypeForDecl);
1706 return QualType(Decl->TypeForDecl, 0);
1707}
1708
John McCall49a832b2009-10-18 09:09:24 +00001709/// \brief Retrieve a substitution-result type.
1710QualType
1711ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1712 QualType Replacement) {
1713 assert(Replacement->isCanonical()
1714 && "replacement types must always be canonical");
1715
1716 llvm::FoldingSetNodeID ID;
1717 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1718 void *InsertPos = 0;
1719 SubstTemplateTypeParmType *SubstParm
1720 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1721
1722 if (!SubstParm) {
1723 SubstParm = new (*this, TypeAlignment)
1724 SubstTemplateTypeParmType(Parm, Replacement);
1725 Types.push_back(SubstParm);
1726 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1727 }
1728
1729 return QualType(SubstParm, 0);
1730}
1731
Douglas Gregorfab9d672009-02-05 23:33:38 +00001732/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001733/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001734/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001735QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001736 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001737 IdentifierInfo *Name) {
1738 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001739 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001740 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001741 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001742 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1743
1744 if (TypeParm)
1745 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001747 if (Name) {
1748 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001749 TypeParm = new (*this, TypeAlignment)
1750 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001751 } else
John McCall6b304a02009-09-24 23:30:46 +00001752 TypeParm = new (*this, TypeAlignment)
1753 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001754
1755 Types.push_back(TypeParm);
1756 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1757
1758 return QualType(TypeParm, 0);
1759}
1760
Mike Stump1eb44332009-09-09 15:08:12 +00001761QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001762ASTContext::getTemplateSpecializationType(TemplateName Template,
1763 const TemplateArgument *Args,
1764 unsigned NumArgs,
1765 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001766 if (!Canon.isNull())
1767 Canon = getCanonicalType(Canon);
1768 else {
1769 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001770 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1771 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1772 CanonArgs.reserve(NumArgs);
1773 for (unsigned I = 0; I != NumArgs; ++I)
1774 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1775
1776 // Determine whether this canonical template specialization type already
1777 // exists.
1778 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001779 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001780 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001781
1782 void *InsertPos = 0;
1783 TemplateSpecializationType *Spec
1784 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregor1275ae02009-07-28 23:00:59 +00001786 if (!Spec) {
1787 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001788 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001789 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001790 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001791 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001792 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001793 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001794 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001795 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001796 }
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Douglas Gregorb88e8882009-07-30 17:40:51 +00001798 if (Canon.isNull())
1799 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001800 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001801 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001802 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001803
Douglas Gregor1275ae02009-07-28 23:00:59 +00001804 // Allocate the (non-canonical) template specialization type, but don't
1805 // try to unique it: these types typically have location information that
1806 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001807 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001808 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001809 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001810 TemplateSpecializationType *Spec
1811 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001812 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor55f6b142009-02-09 18:46:07 +00001814 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001815 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001816}
1817
Mike Stump1eb44332009-09-09 15:08:12 +00001818QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001819ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001820 QualType NamedType) {
1821 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001822 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001823
1824 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001825 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001826 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1827 if (T)
1828 return QualType(T, 0);
1829
Mike Stump1eb44332009-09-09 15:08:12 +00001830 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001831 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001832 Types.push_back(T);
1833 QualifiedNameTypes.InsertNode(T, InsertPos);
1834 return QualType(T, 0);
1835}
1836
Mike Stump1eb44332009-09-09 15:08:12 +00001837QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001838 const IdentifierInfo *Name,
1839 QualType Canon) {
1840 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1841
1842 if (Canon.isNull()) {
1843 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1844 if (CanonNNS != NNS)
1845 Canon = getTypenameType(CanonNNS, Name);
1846 }
1847
1848 llvm::FoldingSetNodeID ID;
1849 TypenameType::Profile(ID, NNS, Name);
1850
1851 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001852 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001853 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1854 if (T)
1855 return QualType(T, 0);
1856
1857 T = new (*this) TypenameType(NNS, Name, Canon);
1858 Types.push_back(T);
1859 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001860 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001861}
1862
Mike Stump1eb44332009-09-09 15:08:12 +00001863QualType
1864ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001865 const TemplateSpecializationType *TemplateId,
1866 QualType Canon) {
1867 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1868
1869 if (Canon.isNull()) {
1870 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1871 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1872 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1873 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001874 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001875 assert(CanonTemplateId &&
1876 "Canonical type must also be a template specialization type");
1877 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1878 }
1879 }
1880
1881 llvm::FoldingSetNodeID ID;
1882 TypenameType::Profile(ID, NNS, TemplateId);
1883
1884 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001885 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001886 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1887 if (T)
1888 return QualType(T, 0);
1889
1890 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1891 Types.push_back(T);
1892 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001893 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001894}
1895
John McCall7da24312009-09-05 00:15:47 +00001896QualType
1897ASTContext::getElaboratedType(QualType UnderlyingType,
1898 ElaboratedType::TagKind Tag) {
1899 llvm::FoldingSetNodeID ID;
1900 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
John McCall7da24312009-09-05 00:15:47 +00001902 void *InsertPos = 0;
1903 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1904 if (T)
1905 return QualType(T, 0);
1906
1907 QualType Canon = getCanonicalType(UnderlyingType);
1908
1909 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1910 Types.push_back(T);
1911 ElaboratedTypes.InsertNode(T, InsertPos);
1912 return QualType(T, 0);
1913}
1914
Chris Lattner88cb27a2008-04-07 04:56:42 +00001915/// CmpProtocolNames - Comparison predicate for sorting protocols
1916/// alphabetically.
1917static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1918 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001919 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001920}
1921
1922static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1923 unsigned &NumProtocols) {
1924 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Chris Lattner88cb27a2008-04-07 04:56:42 +00001926 // Sort protocols, keyed by name.
1927 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1928
1929 // Remove duplicates.
1930 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1931 NumProtocols = ProtocolsEnd-Protocols;
1932}
1933
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001934/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1935/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001936QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00001937 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001938 unsigned NumProtocols) {
1939 // Sort the protocol list alphabetically to canonicalize it.
1940 if (NumProtocols)
1941 SortAndUniqueProtocols(Protocols, NumProtocols);
1942
1943 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001944 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001945
1946 void *InsertPos = 0;
1947 if (ObjCObjectPointerType *QT =
1948 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1949 return QualType(QT, 0);
1950
1951 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00001952 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
1953 ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001955 Types.push_back(QType);
1956 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1957 return QualType(QType, 0);
1958}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001959
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001960/// getObjCInterfaceType - Return the unique reference to the type for the
1961/// specified ObjC interface decl. The list of protocols is optional.
1962QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001963 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Mike Stump1eb44332009-09-09 15:08:12 +00001964 if (NumProtocols)
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001965 // Sort the protocol list alphabetically to canonicalize it.
1966 SortAndUniqueProtocols(Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001968 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001969 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001971 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001972 if (ObjCInterfaceType *QT =
1973 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001974 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001976 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00001977 ObjCInterfaceType *QType = new (*this, TypeAlignment)
1978 ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1979 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001980 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001981 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001982 return QualType(QType, 0);
1983}
1984
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001985QualType ASTContext::getObjCProtocolListType(QualType T,
1986 ObjCProtocolDecl **Protocols,
1987 unsigned NumProtocols) {
1988 llvm::FoldingSetNodeID ID;
1989 ObjCProtocolListType::Profile(ID, T, Protocols, NumProtocols);
1990
1991 void *InsertPos = 0;
1992 if (ObjCProtocolListType *QT =
1993 ObjCProtocolListTypes.FindNodeOrInsertPos(ID, InsertPos))
1994 return QualType(QT, 0);
1995
1996 // No Match;
1997 ObjCProtocolListType *QType = new (*this, TypeAlignment)
1998 ObjCProtocolListType(T, Protocols, NumProtocols);
1999 Types.push_back(QType);
2000 ObjCProtocolListTypes.InsertNode(QType, InsertPos);
2001 return QualType(QType, 0);
2002}
2003
Douglas Gregor72564e72009-02-26 23:50:07 +00002004/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2005/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002006/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002007/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002008/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002009QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002010 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002011 if (tofExpr->isTypeDependent()) {
2012 llvm::FoldingSetNodeID ID;
2013 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Douglas Gregorb1975722009-07-30 23:18:24 +00002015 void *InsertPos = 0;
2016 DependentTypeOfExprType *Canon
2017 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2018 if (Canon) {
2019 // We already have a "canonical" version of an identical, dependent
2020 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002021 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002022 QualType((TypeOfExprType*)Canon, 0));
2023 }
2024 else {
2025 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002026 Canon
2027 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002028 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2029 toe = Canon;
2030 }
2031 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002032 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002033 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002034 }
Steve Naroff9752f252007-08-01 18:02:17 +00002035 Types.push_back(toe);
2036 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002037}
2038
Steve Naroff9752f252007-08-01 18:02:17 +00002039/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2040/// TypeOfType AST's. The only motivation to unique these nodes would be
2041/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002042/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002043/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002044QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002045 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002046 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002047 Types.push_back(tot);
2048 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002049}
2050
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002051/// getDecltypeForExpr - Given an expr, will return the decltype for that
2052/// expression, according to the rules in C++0x [dcl.type.simple]p4
2053static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002054 if (e->isTypeDependent())
2055 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002057 // If e is an id expression or a class member access, decltype(e) is defined
2058 // as the type of the entity named by e.
2059 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2060 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2061 return VD->getType();
2062 }
2063 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2064 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2065 return FD->getType();
2066 }
2067 // If e is a function call or an invocation of an overloaded operator,
2068 // (parentheses around e are ignored), decltype(e) is defined as the
2069 // return type of that function.
2070 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2071 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002073 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002074
2075 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002076 // defined as T&, otherwise decltype(e) is defined as T.
2077 if (e->isLvalue(Context) == Expr::LV_Valid)
2078 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002080 return T;
2081}
2082
Anders Carlsson395b4752009-06-24 19:06:50 +00002083/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2084/// DecltypeType AST's. The only motivation to unique these nodes would be
2085/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002086/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002087/// on canonical type's (which are always unique).
2088QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002089 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002090 if (e->isTypeDependent()) {
2091 llvm::FoldingSetNodeID ID;
2092 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002094 void *InsertPos = 0;
2095 DependentDecltypeType *Canon
2096 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2097 if (Canon) {
2098 // We already have a "canonical" version of an equivalent, dependent
2099 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002100 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002101 QualType((DecltypeType*)Canon, 0));
2102 }
2103 else {
2104 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002105 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002106 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2107 dt = Canon;
2108 }
2109 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002110 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002111 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002112 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002113 Types.push_back(dt);
2114 return QualType(dt, 0);
2115}
2116
Reid Spencer5f016e22007-07-11 17:01:13 +00002117/// getTagDeclType - Return the unique reference to the type for the
2118/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002119QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002120 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002121 // FIXME: What is the design on getTagDeclType when it requires casting
2122 // away const? mutable?
2123 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002124}
2125
Mike Stump1eb44332009-09-09 15:08:12 +00002126/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2127/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2128/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002129QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002130 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002131}
2132
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002133/// getSignedWCharType - Return the type of "signed wchar_t".
2134/// Used when in C++, as a GCC extension.
2135QualType ASTContext::getSignedWCharType() const {
2136 // FIXME: derive from "Target" ?
2137 return WCharTy;
2138}
2139
2140/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2141/// Used when in C++, as a GCC extension.
2142QualType ASTContext::getUnsignedWCharType() const {
2143 // FIXME: derive from "Target" ?
2144 return UnsignedIntTy;
2145}
2146
Chris Lattner8b9023b2007-07-13 03:05:23 +00002147/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2148/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2149QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002150 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002151}
2152
Chris Lattnere6327742008-04-02 05:18:44 +00002153//===----------------------------------------------------------------------===//
2154// Type Operators
2155//===----------------------------------------------------------------------===//
2156
Chris Lattner77c96472008-04-06 22:41:35 +00002157/// getCanonicalType - Return the canonical (structural) type corresponding to
2158/// the specified potentially non-canonical type. The non-canonical version
2159/// of a type may have many "decorated" versions of types. Decorators can
2160/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2161/// to be free of any of these, allowing two canonical types to be compared
2162/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002163CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002164 QualifierCollector Quals;
2165 const Type *Ptr = Quals.strip(T);
2166 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002167
John McCall0953e762009-09-24 19:53:00 +00002168 // The canonical internal type will be the canonical type *except*
2169 // that we push type qualifiers down through array types.
2170
2171 // If there are no new qualifiers to push down, stop here.
2172 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002173 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002174
John McCall0953e762009-09-24 19:53:00 +00002175 // If the type qualifiers are on an array type, get the canonical
2176 // type of the array with the qualifiers applied to the element
2177 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002178 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2179 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002180 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002182 // Get the canonical version of the element with the extra qualifiers on it.
2183 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002184 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002185 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002187 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002188 return CanQualType::CreateUnsafe(
2189 getConstantArrayType(NewEltTy, CAT->getSize(),
2190 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002191 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002192 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002193 return CanQualType::CreateUnsafe(
2194 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002195 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Douglas Gregor898574e2008-12-05 23:32:09 +00002197 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002198 return CanQualType::CreateUnsafe(
2199 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002200 DSAT->getSizeExpr() ?
2201 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002202 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002203 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002204 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002205
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002206 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002207 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002208 VAT->getSizeExpr() ?
2209 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002210 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002211 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002212 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002213}
2214
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002215TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2216 // If this template name refers to a template, the canonical
2217 // template name merely stores the template itself.
2218 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002219 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002220
Mike Stump1eb44332009-09-09 15:08:12 +00002221 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002222 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002223 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2224 OverloadedFunctionDecl *CanonOvl = 0;
2225 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2226 FEnd = Ovl->function_end();
2227 F != FEnd; ++F) {
2228 Decl *Canon = F->get()->getCanonicalDecl();
2229 if (CanonOvl || Canon != F->get()) {
2230 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002231 CanonOvl = OverloadedFunctionDecl::Create(*this,
2232 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002233 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002235 CanonOvl->addOverload(
2236 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2237 }
2238 }
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002240 return TemplateName(CanonOvl? CanonOvl : Ovl);
2241 }
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002243 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2244 assert(DTN && "Non-dependent template names must refer to template decls.");
2245 return DTN->CanonicalTemplateName;
2246}
2247
Mike Stump1eb44332009-09-09 15:08:12 +00002248TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002249ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2250 switch (Arg.getKind()) {
2251 case TemplateArgument::Null:
2252 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Douglas Gregor1275ae02009-07-28 23:00:59 +00002254 case TemplateArgument::Expression:
2255 // FIXME: Build canonical expression?
2256 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Douglas Gregor1275ae02009-07-28 23:00:59 +00002258 case TemplateArgument::Declaration:
2259 return TemplateArgument(SourceLocation(),
2260 Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Douglas Gregor1275ae02009-07-28 23:00:59 +00002262 case TemplateArgument::Integral:
2263 return TemplateArgument(SourceLocation(),
2264 *Arg.getAsIntegral(),
2265 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Douglas Gregor1275ae02009-07-28 23:00:59 +00002267 case TemplateArgument::Type:
2268 return TemplateArgument(SourceLocation(),
2269 getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Douglas Gregor1275ae02009-07-28 23:00:59 +00002271 case TemplateArgument::Pack: {
2272 // FIXME: Allocate in ASTContext
2273 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2274 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002275 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002276 AEnd = Arg.pack_end();
2277 A != AEnd; (void)++A, ++Idx)
2278 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Douglas Gregor1275ae02009-07-28 23:00:59 +00002280 TemplateArgument Result;
2281 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2282 return Result;
2283 }
2284 }
2285
2286 // Silence GCC warning
2287 assert(false && "Unhandled template argument kind");
2288 return TemplateArgument();
2289}
2290
Douglas Gregord57959a2009-03-27 23:10:48 +00002291NestedNameSpecifier *
2292ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002293 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002294 return 0;
2295
2296 switch (NNS->getKind()) {
2297 case NestedNameSpecifier::Identifier:
2298 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002299 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002300 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2301 NNS->getAsIdentifier());
2302
2303 case NestedNameSpecifier::Namespace:
2304 // A namespace is canonical; build a nested-name-specifier with
2305 // this namespace and no prefix.
2306 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2307
2308 case NestedNameSpecifier::TypeSpec:
2309 case NestedNameSpecifier::TypeSpecWithTemplate: {
2310 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002311 return NestedNameSpecifier::Create(*this, 0,
2312 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002313 T.getTypePtr());
2314 }
2315
2316 case NestedNameSpecifier::Global:
2317 // The global specifier is canonical and unique.
2318 return NNS;
2319 }
2320
2321 // Required to silence a GCC warning
2322 return 0;
2323}
2324
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002325
2326const ArrayType *ASTContext::getAsArrayType(QualType T) {
2327 // Handle the non-qualified case efficiently.
John McCall0953e762009-09-24 19:53:00 +00002328 if (!T.hasQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002329 // Handle the common positive case fast.
2330 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2331 return AT;
2332 }
Mike Stump1eb44332009-09-09 15:08:12 +00002333
John McCall0953e762009-09-24 19:53:00 +00002334 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002335 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002336 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002337 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
John McCall0953e762009-09-24 19:53:00 +00002339 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002340 // implements C99 6.7.3p8: "If the specification of an array type includes
2341 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002343 // If we get here, we either have type qualifiers on the type, or we have
2344 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002345 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002346
John McCall0953e762009-09-24 19:53:00 +00002347 QualifierCollector Qs;
2348 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002350 // If we have a simple case, just return now.
2351 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002352 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002353 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002355 // Otherwise, we have an array and we have qualifiers on it. Push the
2356 // qualifiers into the array element type and return a new array type.
2357 // Get the canonical version of the element with the extra qualifiers on it.
2358 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002359 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002361 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2362 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2363 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002364 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002365 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2366 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2367 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002368 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002369
Mike Stump1eb44332009-09-09 15:08:12 +00002370 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002371 = dyn_cast<DependentSizedArrayType>(ATy))
2372 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002373 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002374 DSAT->getSizeExpr() ?
2375 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002376 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002377 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002378 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002380 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002381 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002382 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002383 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002384 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002385 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002386 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002387}
2388
2389
Chris Lattnere6327742008-04-02 05:18:44 +00002390/// getArrayDecayedType - Return the properly qualified result of decaying the
2391/// specified array type to a pointer. This operation is non-trivial when
2392/// handling typedefs etc. The canonical type of "T" must be an array type,
2393/// this returns a pointer to a properly qualified element of the array.
2394///
2395/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2396QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002397 // Get the element type with 'getAsArrayType' so that we don't lose any
2398 // typedefs in the element type of the array. This also handles propagation
2399 // of type qualifiers from the array type into the element type if present
2400 // (C99 6.7.3p8).
2401 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2402 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002404 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002405
2406 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002407 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002408}
2409
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002410QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002411 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002412 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002413 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002414 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2415 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002416 } else {
John McCall0953e762009-09-24 19:53:00 +00002417 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002418 }
2419 }
2420}
2421
Anders Carlssonfbbce492009-09-25 01:23:32 +00002422QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2423 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Anders Carlssonfbbce492009-09-25 01:23:32 +00002425 if (const ArrayType *AT = getAsArrayType(ElemTy))
2426 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Anders Carlsson6183a992008-12-21 03:44:36 +00002428 return ElemTy;
2429}
2430
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002431/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002432uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002433ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2434 uint64_t ElementCount = 1;
2435 do {
2436 ElementCount *= CA->getSize().getZExtValue();
2437 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2438 } while (CA);
2439 return ElementCount;
2440}
2441
Reid Spencer5f016e22007-07-11 17:01:13 +00002442/// getFloatingRank - Return a relative rank for floating point types.
2443/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002444static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002445 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002447
John McCall183700f2009-09-21 23:43:11 +00002448 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2449 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002450 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002451 case BuiltinType::Float: return FloatRank;
2452 case BuiltinType::Double: return DoubleRank;
2453 case BuiltinType::LongDouble: return LongDoubleRank;
2454 }
2455}
2456
Mike Stump1eb44332009-09-09 15:08:12 +00002457/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2458/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002459/// 'typeDomain' is a real floating point or complex type.
2460/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002461QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2462 QualType Domain) const {
2463 FloatingRank EltRank = getFloatingRank(Size);
2464 if (Domain->isComplexType()) {
2465 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002466 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002467 case FloatRank: return FloatComplexTy;
2468 case DoubleRank: return DoubleComplexTy;
2469 case LongDoubleRank: return LongDoubleComplexTy;
2470 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 }
Chris Lattner1361b112008-04-06 23:58:54 +00002472
2473 assert(Domain->isRealFloatingType() && "Unknown domain!");
2474 switch (EltRank) {
2475 default: assert(0 && "getFloatingRank(): illegal value for rank");
2476 case FloatRank: return FloatTy;
2477 case DoubleRank: return DoubleTy;
2478 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002479 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002480}
2481
Chris Lattner7cfeb082008-04-06 23:55:33 +00002482/// getFloatingTypeOrder - Compare the rank of the two specified floating
2483/// point types, ignoring the domain of the type (i.e. 'double' ==
2484/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002485/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002486int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2487 FloatingRank LHSR = getFloatingRank(LHS);
2488 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattnera75cea32008-04-06 23:38:49 +00002490 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002491 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002492 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002493 return 1;
2494 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002495}
2496
Chris Lattnerf52ab252008-04-06 22:59:24 +00002497/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2498/// routine will assert if passed a built-in type that isn't an integer or enum,
2499/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002500unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002501 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002502 if (EnumType* ET = dyn_cast<EnumType>(T))
2503 T = ET->getDecl()->getIntegerType().getTypePtr();
2504
Eli Friedmana3426752009-07-05 23:44:27 +00002505 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2506 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2507
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002508 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2509 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2510
2511 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2512 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2513
Eli Friedmanf98aba32009-02-13 02:31:07 +00002514 // There are two things which impact the integer rank: the width, and
2515 // the ordering of builtins. The builtin ordering is encoded in the
2516 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002517 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002518 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002519
Chris Lattnerf52ab252008-04-06 22:59:24 +00002520 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002521 default: assert(0 && "getIntegerRank(): not a built-in integer");
2522 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002523 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002524 case BuiltinType::Char_S:
2525 case BuiltinType::Char_U:
2526 case BuiltinType::SChar:
2527 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002528 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002529 case BuiltinType::Short:
2530 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002531 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002532 case BuiltinType::Int:
2533 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002534 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002535 case BuiltinType::Long:
2536 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002537 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002538 case BuiltinType::LongLong:
2539 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002540 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002541 case BuiltinType::Int128:
2542 case BuiltinType::UInt128:
2543 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002544 }
2545}
2546
Eli Friedman04e83572009-08-20 04:21:42 +00002547/// \brief Whether this is a promotable bitfield reference according
2548/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2549///
2550/// \returns the type this bit-field will promote to, or NULL if no
2551/// promotion occurs.
2552QualType ASTContext::isPromotableBitField(Expr *E) {
2553 FieldDecl *Field = E->getBitField();
2554 if (!Field)
2555 return QualType();
2556
2557 QualType FT = Field->getType();
2558
2559 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2560 uint64_t BitWidth = BitWidthAP.getZExtValue();
2561 uint64_t IntSize = getTypeSize(IntTy);
2562 // GCC extension compatibility: if the bit-field size is less than or equal
2563 // to the size of int, it gets promoted no matter what its type is.
2564 // For instance, unsigned long bf : 4 gets promoted to signed int.
2565 if (BitWidth < IntSize)
2566 return IntTy;
2567
2568 if (BitWidth == IntSize)
2569 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2570
2571 // Types bigger than int are not subject to promotions, and therefore act
2572 // like the base type.
2573 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2574 // is ridiculous.
2575 return QualType();
2576}
2577
Eli Friedmana95d7572009-08-19 07:44:53 +00002578/// getPromotedIntegerType - Returns the type that Promotable will
2579/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2580/// integer type.
2581QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2582 assert(!Promotable.isNull());
2583 assert(Promotable->isPromotableIntegerType());
2584 if (Promotable->isSignedIntegerType())
2585 return IntTy;
2586 uint64_t PromotableSize = getTypeSize(Promotable);
2587 uint64_t IntSize = getTypeSize(IntTy);
2588 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2589 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2590}
2591
Mike Stump1eb44332009-09-09 15:08:12 +00002592/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002593/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002594/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002595int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002596 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2597 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002598 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Chris Lattnerf52ab252008-04-06 22:59:24 +00002600 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2601 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Chris Lattner7cfeb082008-04-06 23:55:33 +00002603 unsigned LHSRank = getIntegerRank(LHSC);
2604 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Chris Lattner7cfeb082008-04-06 23:55:33 +00002606 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2607 if (LHSRank == RHSRank) return 0;
2608 return LHSRank > RHSRank ? 1 : -1;
2609 }
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Chris Lattner7cfeb082008-04-06 23:55:33 +00002611 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2612 if (LHSUnsigned) {
2613 // If the unsigned [LHS] type is larger, return it.
2614 if (LHSRank >= RHSRank)
2615 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Chris Lattner7cfeb082008-04-06 23:55:33 +00002617 // If the signed type can represent all values of the unsigned type, it
2618 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002619 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002620 return -1;
2621 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002622
Chris Lattner7cfeb082008-04-06 23:55:33 +00002623 // If the unsigned [RHS] type is larger, return it.
2624 if (RHSRank >= LHSRank)
2625 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Chris Lattner7cfeb082008-04-06 23:55:33 +00002627 // If the signed type can represent all values of the unsigned type, it
2628 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002629 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002630 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002631}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002632
Mike Stump1eb44332009-09-09 15:08:12 +00002633// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002634QualType ASTContext::getCFConstantStringType() {
2635 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002636 CFConstantStringTypeDecl =
2637 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002638 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002639 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Anders Carlsson71993dd2007-08-17 05:31:46 +00002641 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002642 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002643 // int flags;
2644 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002645 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002646 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002647 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002648 FieldTypes[3] = LongTy;
2649
Anders Carlsson71993dd2007-08-17 05:31:46 +00002650 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002651 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002652 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002653 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002654 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002655 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002656 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002657 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002658 }
2659
2660 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002661 }
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Anders Carlsson71993dd2007-08-17 05:31:46 +00002663 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002664}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002665
Douglas Gregor319ac892009-04-23 22:29:11 +00002666void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002667 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002668 assert(Rec && "Invalid CFConstantStringType");
2669 CFConstantStringTypeDecl = Rec->getDecl();
2670}
2671
Mike Stump1eb44332009-09-09 15:08:12 +00002672QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002673 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002674 ObjCFastEnumerationStateTypeDecl =
2675 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2676 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002677
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002678 QualType FieldTypes[] = {
2679 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002680 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002681 getPointerType(UnsignedLongTy),
2682 getConstantArrayType(UnsignedLongTy,
2683 llvm::APInt(32, 5), ArrayType::Normal, 0)
2684 };
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Douglas Gregor44b43212008-12-11 16:49:14 +00002686 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002687 FieldDecl *Field = FieldDecl::Create(*this,
2688 ObjCFastEnumerationStateTypeDecl,
2689 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002690 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002691 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002692 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002693 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor44b43212008-12-11 16:49:14 +00002696 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002697 }
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002699 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2700}
2701
Mike Stumpadaaad32009-10-20 02:12:22 +00002702QualType ASTContext::getBlockDescriptorType() {
2703 if (BlockDescriptorType)
2704 return getTagDeclType(BlockDescriptorType);
2705
2706 RecordDecl *T;
2707 // FIXME: Needs the FlagAppleBlock bit.
2708 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2709 &Idents.get("__block_descriptor"));
2710
2711 QualType FieldTypes[] = {
2712 UnsignedLongTy,
2713 UnsignedLongTy,
2714 };
2715
2716 const char *FieldNames[] = {
2717 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002718 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002719 };
2720
2721 for (size_t i = 0; i < 2; ++i) {
2722 FieldDecl *Field = FieldDecl::Create(*this,
2723 T,
2724 SourceLocation(),
2725 &Idents.get(FieldNames[i]),
2726 FieldTypes[i], /*DInfo=*/0,
2727 /*BitWidth=*/0,
2728 /*Mutable=*/false);
2729 T->addDecl(Field);
2730 }
2731
2732 T->completeDefinition(*this);
2733
2734 BlockDescriptorType = T;
2735
2736 return getTagDeclType(BlockDescriptorType);
2737}
2738
2739void ASTContext::setBlockDescriptorType(QualType T) {
2740 const RecordType *Rec = T->getAs<RecordType>();
2741 assert(Rec && "Invalid BlockDescriptorType");
2742 BlockDescriptorType = Rec->getDecl();
2743}
2744
Mike Stump083c25e2009-10-22 00:49:09 +00002745QualType ASTContext::getBlockDescriptorExtendedType() {
2746 if (BlockDescriptorExtendedType)
2747 return getTagDeclType(BlockDescriptorExtendedType);
2748
2749 RecordDecl *T;
2750 // FIXME: Needs the FlagAppleBlock bit.
2751 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2752 &Idents.get("__block_descriptor_withcopydispose"));
2753
2754 QualType FieldTypes[] = {
2755 UnsignedLongTy,
2756 UnsignedLongTy,
2757 getPointerType(VoidPtrTy),
2758 getPointerType(VoidPtrTy)
2759 };
2760
2761 const char *FieldNames[] = {
2762 "reserved",
2763 "Size",
2764 "CopyFuncPtr",
2765 "DestroyFuncPtr"
2766 };
2767
2768 for (size_t i = 0; i < 4; ++i) {
2769 FieldDecl *Field = FieldDecl::Create(*this,
2770 T,
2771 SourceLocation(),
2772 &Idents.get(FieldNames[i]),
2773 FieldTypes[i], /*DInfo=*/0,
2774 /*BitWidth=*/0,
2775 /*Mutable=*/false);
2776 T->addDecl(Field);
2777 }
2778
2779 T->completeDefinition(*this);
2780
2781 BlockDescriptorExtendedType = T;
2782
2783 return getTagDeclType(BlockDescriptorExtendedType);
2784}
2785
2786void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2787 const RecordType *Rec = T->getAs<RecordType>();
2788 assert(Rec && "Invalid BlockDescriptorType");
2789 BlockDescriptorExtendedType = Rec->getDecl();
2790}
2791
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002792bool ASTContext::BlockRequiresCopying(QualType Ty) {
2793 if (Ty->isBlockPointerType())
2794 return true;
2795 if (isObjCNSObjectType(Ty))
2796 return true;
2797 if (Ty->isObjCObjectPointerType())
2798 return true;
2799 return false;
2800}
2801
2802QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2803 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002804 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002805 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002806 // unsigned int __flags;
2807 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002808 // void *__copy_helper; // as needed
2809 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002810 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002811 // } *
2812
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002813 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2814
2815 // FIXME: Move up
2816 static int UniqueBlockByRefTypeID = 0;
2817 char Name[36];
2818 sprintf(Name, "__Block_byref_%d_%s", ++UniqueBlockByRefTypeID, DeclName);
2819 RecordDecl *T;
2820 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2821 &Idents.get(Name));
2822 T->startDefinition();
2823 QualType Int32Ty = IntTy;
2824 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2825 QualType FieldTypes[] = {
2826 getPointerType(VoidPtrTy),
2827 getPointerType(getTagDeclType(T)),
2828 Int32Ty,
2829 Int32Ty,
2830 getPointerType(VoidPtrTy),
2831 getPointerType(VoidPtrTy),
2832 Ty
2833 };
2834
2835 const char *FieldNames[] = {
2836 "__isa",
2837 "__forwarding",
2838 "__flags",
2839 "__size",
2840 "__copy_helper",
2841 "__destroy_helper",
2842 DeclName,
2843 };
2844
2845 for (size_t i = 0; i < 7; ++i) {
2846 if (!HasCopyAndDispose && i >=4 && i <= 5)
2847 continue;
2848 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2849 &Idents.get(FieldNames[i]),
2850 FieldTypes[i], /*DInfo=*/0,
2851 /*BitWidth=*/0, /*Mutable=*/false);
2852 T->addDecl(Field);
2853 }
2854
2855 T->completeDefinition(*this);
2856
2857 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002858}
2859
2860
2861QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002862 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002863 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002864 // FIXME: Move up
2865 static int UniqueBlockParmTypeID = 0;
2866 char Name[36];
2867 sprintf(Name, "__block_literal_%u", ++UniqueBlockParmTypeID);
2868 RecordDecl *T;
2869 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2870 &Idents.get(Name));
Mike Stumpadaaad32009-10-20 02:12:22 +00002871 QualType FieldTypes[] = {
2872 getPointerType(VoidPtrTy),
2873 IntTy,
2874 IntTy,
2875 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00002876 (BlockHasCopyDispose ?
2877 getPointerType(getBlockDescriptorExtendedType()) :
2878 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00002879 };
2880
2881 const char *FieldNames[] = {
2882 "__isa",
2883 "__flags",
2884 "__reserved",
2885 "__FuncPtr",
2886 "__descriptor"
2887 };
2888
2889 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00002890 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00002891 &Idents.get(FieldNames[i]),
2892 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00002893 /*BitWidth=*/0, /*Mutable=*/false);
2894 T->addDecl(Field);
2895 }
2896
2897 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
2898 const Expr *E = BlockDeclRefDecls[i];
2899 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2900 clang::IdentifierInfo *Name = 0;
2901 if (BDRE) {
2902 const ValueDecl *D = BDRE->getDecl();
2903 Name = &Idents.get(D->getName());
2904 }
2905 QualType FieldType = E->getType();
2906
2907 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002908 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
2909 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00002910
2911 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2912 Name, FieldType, /*DInfo=*/0,
2913 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00002914 T->addDecl(Field);
2915 }
2916
2917 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00002918
2919 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00002920}
2921
Douglas Gregor319ac892009-04-23 22:29:11 +00002922void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002923 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002924 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2925 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2926}
2927
Anders Carlssone8c49532007-10-29 06:33:42 +00002928// This returns true if a type has been typedefed to BOOL:
2929// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002930static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002931 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002932 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2933 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002935 return false;
2936}
2937
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002938/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002939/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002940int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002941 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002943 // Make all integer and enum types at least as large as an int
2944 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002945 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002946 // Treat arrays as pointers, since that's how they're passed in.
2947 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002948 sz = getTypeSize(VoidPtrTy);
2949 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002950}
2951
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002952/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002953/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002954void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002955 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002956 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002957 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002958 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002959 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002960 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002961 // Compute size of all parameters.
2962 // Start with computing size of a pointer in number of bytes.
2963 // FIXME: There might(should) be a better way of doing this computation!
2964 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002965 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002966 // The first two arguments (self and _cmd) are pointers; account for
2967 // their size.
2968 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002969 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2970 E = Decl->param_end(); PI != E; ++PI) {
2971 QualType PType = (*PI)->getType();
2972 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002973 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002974 ParmOffset += sz;
2975 }
2976 S += llvm::utostr(ParmOffset);
2977 S += "@0:";
2978 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002980 // Argument types.
2981 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002982 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2983 E = Decl->param_end(); PI != E; ++PI) {
2984 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00002985 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002986 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002987 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2988 // Use array's original type only if it has known number of
2989 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002990 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002991 PType = PVDecl->getType();
2992 } else if (PType->isFunctionType())
2993 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002994 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002995 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002996 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002997 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002998 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003000 }
3001}
3002
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003003/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003004/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003005/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3006/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003007/// Property attributes are stored as a comma-delimited C string. The simple
3008/// attributes readonly and bycopy are encoded as single characters. The
3009/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3010/// encoded as single characters, followed by an identifier. Property types
3011/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003012/// these attributes are defined by the following enumeration:
3013/// @code
3014/// enum PropertyAttributes {
3015/// kPropertyReadOnly = 'R', // property is read-only.
3016/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3017/// kPropertyByref = '&', // property is a reference to the value last assigned
3018/// kPropertyDynamic = 'D', // property is dynamic
3019/// kPropertyGetter = 'G', // followed by getter selector name
3020/// kPropertySetter = 'S', // followed by setter selector name
3021/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3022/// kPropertyType = 't' // followed by old-style type encoding.
3023/// kPropertyWeak = 'W' // 'weak' property
3024/// kPropertyStrong = 'P' // property GC'able
3025/// kPropertyNonAtomic = 'N' // property non-atomic
3026/// };
3027/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003028void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003029 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003030 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003031 // Collect information from the property implementation decl(s).
3032 bool Dynamic = false;
3033 ObjCPropertyImplDecl *SynthesizePID = 0;
3034
3035 // FIXME: Duplicated code due to poor abstraction.
3036 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003037 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003038 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3039 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003040 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003041 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003042 ObjCPropertyImplDecl *PID = *i;
3043 if (PID->getPropertyDecl() == PD) {
3044 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3045 Dynamic = true;
3046 } else {
3047 SynthesizePID = PID;
3048 }
3049 }
3050 }
3051 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003052 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003053 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003054 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003055 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003056 ObjCPropertyImplDecl *PID = *i;
3057 if (PID->getPropertyDecl() == PD) {
3058 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3059 Dynamic = true;
3060 } else {
3061 SynthesizePID = PID;
3062 }
3063 }
Mike Stump1eb44332009-09-09 15:08:12 +00003064 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003065 }
3066 }
3067
3068 // FIXME: This is not very efficient.
3069 S = "T";
3070
3071 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003072 // GCC has some special rules regarding encoding of properties which
3073 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003074 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003075 true /* outermost type */,
3076 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003077
3078 if (PD->isReadOnly()) {
3079 S += ",R";
3080 } else {
3081 switch (PD->getSetterKind()) {
3082 case ObjCPropertyDecl::Assign: break;
3083 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003084 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003085 }
3086 }
3087
3088 // It really isn't clear at all what this means, since properties
3089 // are "dynamic by default".
3090 if (Dynamic)
3091 S += ",D";
3092
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003093 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3094 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003096 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3097 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003098 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003099 }
3100
3101 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3102 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003103 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003104 }
3105
3106 if (SynthesizePID) {
3107 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3108 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003109 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003110 }
3111
3112 // FIXME: OBJCGC: weak & strong
3113}
3114
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003115/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003116/// Another legacy compatibility encoding: 32-bit longs are encoded as
3117/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003118/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3119///
3120void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003121 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003122 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003123 if (BT->getKind() == BuiltinType::ULong &&
3124 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003125 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003126 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003127 if (BT->getKind() == BuiltinType::Long &&
3128 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003129 PointeeTy = IntTy;
3130 }
3131 }
3132}
3133
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003134void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003135 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003136 // We follow the behavior of gcc, expanding structures which are
3137 // directly pointed to, and expanding embedded structures. Note that
3138 // these rules are sufficient to prevent recursive encoding of the
3139 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003140 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003141 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003142}
3143
Mike Stump1eb44332009-09-09 15:08:12 +00003144static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003145 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003146 const Expr *E = FD->getBitWidth();
3147 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3148 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003149 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003150 S += 'b';
3151 S += llvm::utostr(N);
3152}
3153
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003154// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003155void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3156 bool ExpandPointedToStructures,
3157 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003158 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003159 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003160 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003161 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003162 if (FD && FD->isBitField())
3163 return EncodeBitField(this, S, FD);
3164 char encoding;
3165 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003166 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003167 case BuiltinType::Void: encoding = 'v'; break;
3168 case BuiltinType::Bool: encoding = 'B'; break;
3169 case BuiltinType::Char_U:
3170 case BuiltinType::UChar: encoding = 'C'; break;
3171 case BuiltinType::UShort: encoding = 'S'; break;
3172 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003173 case BuiltinType::ULong:
3174 encoding =
3175 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003176 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003177 case BuiltinType::UInt128: encoding = 'T'; break;
3178 case BuiltinType::ULongLong: encoding = 'Q'; break;
3179 case BuiltinType::Char_S:
3180 case BuiltinType::SChar: encoding = 'c'; break;
3181 case BuiltinType::Short: encoding = 's'; break;
3182 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003183 case BuiltinType::Long:
3184 encoding =
3185 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003186 break;
3187 case BuiltinType::LongLong: encoding = 'q'; break;
3188 case BuiltinType::Int128: encoding = 't'; break;
3189 case BuiltinType::Float: encoding = 'f'; break;
3190 case BuiltinType::Double: encoding = 'd'; break;
3191 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003192 }
Mike Stump1eb44332009-09-09 15:08:12 +00003193
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003194 S += encoding;
3195 return;
3196 }
Mike Stump1eb44332009-09-09 15:08:12 +00003197
John McCall183700f2009-09-21 23:43:11 +00003198 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003199 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003200 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003201 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003202 return;
3203 }
Mike Stump1eb44332009-09-09 15:08:12 +00003204
Ted Kremenek6217b802009-07-29 21:53:49 +00003205 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003206 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003207 bool isReadOnly = false;
3208 // For historical/compatibility reasons, the read-only qualifier of the
3209 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3210 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003211 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003212 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003213 if (OutermostType && T.isConstQualified()) {
3214 isReadOnly = true;
3215 S += 'r';
3216 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003217 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003218 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003219 while (P->getAs<PointerType>())
3220 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003221 if (P.isConstQualified()) {
3222 isReadOnly = true;
3223 S += 'r';
3224 }
3225 }
3226 if (isReadOnly) {
3227 // Another legacy compatibility encoding. Some ObjC qualifier and type
3228 // combinations need to be rearranged.
3229 // Rewrite "in const" from "nr" to "rn"
3230 const char * s = S.c_str();
3231 int len = S.length();
3232 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3233 std::string replace = "rn";
3234 S.replace(S.end()-2, S.end(), replace);
3235 }
3236 }
Steve Naroff14108da2009-07-10 23:34:53 +00003237 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003238 S += ':';
3239 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003240 }
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003242 if (PointeeTy->isCharType()) {
3243 // char pointer types should be encoded as '*' unless it is a
3244 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003245 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003246 S += '*';
3247 return;
3248 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003249 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003250 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3251 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3252 S += '#';
3253 return;
3254 }
3255 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3256 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3257 S += '@';
3258 return;
3259 }
3260 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003261 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003262 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003263 getLegacyIntegralTypeEncoding(PointeeTy);
3264
Mike Stump1eb44332009-09-09 15:08:12 +00003265 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003266 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003267 return;
3268 }
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003270 if (const ArrayType *AT =
3271 // Ignore type qualifiers etc.
3272 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003273 if (isa<IncompleteArrayType>(AT)) {
3274 // Incomplete arrays are encoded as a pointer to the array element.
3275 S += '^';
3276
Mike Stump1eb44332009-09-09 15:08:12 +00003277 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003278 false, ExpandStructures, FD);
3279 } else {
3280 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003281
Anders Carlsson559a8332009-02-22 01:38:57 +00003282 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3283 S += llvm::utostr(CAT->getSize().getZExtValue());
3284 else {
3285 //Variable length arrays are encoded as a regular array with 0 elements.
3286 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3287 S += '0';
3288 }
Mike Stump1eb44332009-09-09 15:08:12 +00003289
3290 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003291 false, ExpandStructures, FD);
3292 S += ']';
3293 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003294 return;
3295 }
Mike Stump1eb44332009-09-09 15:08:12 +00003296
John McCall183700f2009-09-21 23:43:11 +00003297 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003298 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003299 return;
3300 }
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Ted Kremenek6217b802009-07-29 21:53:49 +00003302 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003303 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003304 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003305 // Anonymous structures print as '?'
3306 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3307 S += II->getName();
3308 } else {
3309 S += '?';
3310 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003311 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003312 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003313 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3314 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003315 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003316 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003317 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003318 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003319 S += '"';
3320 }
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003322 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003323 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003324 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003325 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003326 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003327 QualType qt = Field->getType();
3328 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003329 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003330 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003331 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003332 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003333 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003334 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003335 return;
3336 }
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003338 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003339 if (FD && FD->isBitField())
3340 EncodeBitField(this, S, FD);
3341 else
3342 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003343 return;
3344 }
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003346 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003347 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003348 return;
3349 }
Mike Stump1eb44332009-09-09 15:08:12 +00003350
John McCall0953e762009-09-24 19:53:00 +00003351 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003352 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003353 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003354 S += '{';
3355 const IdentifierInfo *II = OI->getIdentifier();
3356 S += II->getName();
3357 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003358 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003359 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003360 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003361 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003362 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003363 RecFields[i]);
3364 else
Mike Stump1eb44332009-09-09 15:08:12 +00003365 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003366 FD);
3367 }
3368 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003369 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCall183700f2009-09-21 23:43:11 +00003372 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003373 if (OPT->isObjCIdType()) {
3374 S += '@';
3375 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003376 }
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003378 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003379 S += '#';
3380 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003381 }
Mike Stump1eb44332009-09-09 15:08:12 +00003382
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003383 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003384 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003385 ExpandPointedToStructures,
3386 ExpandStructures, FD);
3387 if (FD || EncodingProperty) {
3388 // Note that we do extended encoding of protocol qualifer list
3389 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003390 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003391 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3392 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003393 S += '<';
3394 S += (*I)->getNameAsString();
3395 S += '>';
3396 }
3397 S += '"';
3398 }
3399 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003400 }
Mike Stump1eb44332009-09-09 15:08:12 +00003401
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003402 QualType PointeeTy = OPT->getPointeeType();
3403 if (!EncodingProperty &&
3404 isa<TypedefType>(PointeeTy.getTypePtr())) {
3405 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003406 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003407 // {...};
3408 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003409 getObjCEncodingForTypeImpl(PointeeTy, S,
3410 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003411 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003412 return;
3413 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003414
3415 S += '@';
3416 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003417 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003418 S += OPT->getInterfaceDecl()->getNameAsCString();
3419 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3420 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003421 S += '<';
3422 S += (*I)->getNameAsString();
3423 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003424 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003425 S += '"';
3426 }
3427 return;
3428 }
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003430 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003431}
3432
Mike Stump1eb44332009-09-09 15:08:12 +00003433void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003434 std::string& S) const {
3435 if (QT & Decl::OBJC_TQ_In)
3436 S += 'n';
3437 if (QT & Decl::OBJC_TQ_Inout)
3438 S += 'N';
3439 if (QT & Decl::OBJC_TQ_Out)
3440 S += 'o';
3441 if (QT & Decl::OBJC_TQ_Bycopy)
3442 S += 'O';
3443 if (QT & Decl::OBJC_TQ_Byref)
3444 S += 'R';
3445 if (QT & Decl::OBJC_TQ_Oneway)
3446 S += 'V';
3447}
3448
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003449void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003450 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003452 BuiltinVaListType = T;
3453}
3454
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003455void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003456 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003457}
3458
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003459void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003460 ObjCSelType = T;
3461
John McCall183700f2009-09-21 23:43:11 +00003462 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003463 if (!TT)
3464 return;
3465 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003466
3467 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003468 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003469 if (!ptr)
3470 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003471 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003472 if (!rec)
3473 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003474 SelStructType = rec;
3475}
3476
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003477void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003478 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003479}
3480
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003481void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003482 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003483}
3484
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003485void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003486 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003487 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003489 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003490}
3491
Douglas Gregor7532dc62009-03-30 22:58:21 +00003492/// \brief Retrieve the template name that represents a qualified
3493/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003494TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003495 bool TemplateKeyword,
3496 TemplateDecl *Template) {
3497 llvm::FoldingSetNodeID ID;
3498 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3499
3500 void *InsertPos = 0;
3501 QualifiedTemplateName *QTN =
3502 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3503 if (!QTN) {
3504 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3505 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3506 }
3507
3508 return TemplateName(QTN);
3509}
3510
Douglas Gregord99cbe62009-07-29 18:26:50 +00003511/// \brief Retrieve the template name that represents a qualified
3512/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003513TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003514 bool TemplateKeyword,
3515 OverloadedFunctionDecl *Template) {
3516 llvm::FoldingSetNodeID ID;
3517 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Douglas Gregord99cbe62009-07-29 18:26:50 +00003519 void *InsertPos = 0;
3520 QualifiedTemplateName *QTN =
3521 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3522 if (!QTN) {
3523 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3524 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3525 }
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Douglas Gregord99cbe62009-07-29 18:26:50 +00003527 return TemplateName(QTN);
3528}
3529
Douglas Gregor7532dc62009-03-30 22:58:21 +00003530/// \brief Retrieve the template name that represents a dependent
3531/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003532TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003533 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003534 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003535 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003536
3537 llvm::FoldingSetNodeID ID;
3538 DependentTemplateName::Profile(ID, NNS, Name);
3539
3540 void *InsertPos = 0;
3541 DependentTemplateName *QTN =
3542 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3543
3544 if (QTN)
3545 return TemplateName(QTN);
3546
3547 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3548 if (CanonNNS == NNS) {
3549 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3550 } else {
3551 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3552 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3553 }
3554
3555 DependentTemplateNames.InsertNode(QTN, InsertPos);
3556 return TemplateName(QTN);
3557}
3558
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003559/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003560/// TargetInfo, produce the corresponding type. The unsigned @p Type
3561/// is actually a value of type @c TargetInfo::IntType.
3562QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003563 switch (Type) {
Mike Stump1eb44332009-09-09 15:08:12 +00003564 case TargetInfo::NoInt: return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003565 case TargetInfo::SignedShort: return ShortTy;
3566 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3567 case TargetInfo::SignedInt: return IntTy;
3568 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3569 case TargetInfo::SignedLong: return LongTy;
3570 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3571 case TargetInfo::SignedLongLong: return LongLongTy;
3572 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3573 }
3574
3575 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003576 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003577}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003578
3579//===----------------------------------------------------------------------===//
3580// Type Predicates.
3581//===----------------------------------------------------------------------===//
3582
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003583/// isObjCNSObjectType - Return true if this is an NSObject object using
3584/// NSObject attribute on a c-style pointer type.
3585/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003586/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003587///
3588bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3589 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3590 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003591 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003592 return true;
3593 }
Mike Stump1eb44332009-09-09 15:08:12 +00003594 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003595}
3596
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003597/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3598/// garbage collection attribute.
3599///
John McCall0953e762009-09-24 19:53:00 +00003600Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3601 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003602 if (getLangOptions().ObjC1 &&
3603 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003604 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003605 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003606 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003607 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003608 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003609 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003610 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003611 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003612 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003613 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003614 // Non-pointers have none gc'able attribute regardless of the attribute
3615 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003616 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003617 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003618 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003619 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003620}
3621
Chris Lattner6ac46a42008-04-07 06:51:04 +00003622//===----------------------------------------------------------------------===//
3623// Type Compatibility Testing
3624//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003625
Mike Stump1eb44332009-09-09 15:08:12 +00003626/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003627/// compatible.
3628static bool areCompatVectorTypes(const VectorType *LHS,
3629 const VectorType *RHS) {
3630 assert(LHS->isCanonical() && RHS->isCanonical());
3631 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003632 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003633}
3634
Steve Naroff4084c302009-07-23 01:01:38 +00003635//===----------------------------------------------------------------------===//
3636// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3637//===----------------------------------------------------------------------===//
3638
3639/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3640/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003641bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3642 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003643 if (lProto == rProto)
3644 return true;
3645 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3646 E = rProto->protocol_end(); PI != E; ++PI)
3647 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3648 return true;
3649 return false;
3650}
3651
Steve Naroff4084c302009-07-23 01:01:38 +00003652/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3653/// return true if lhs's protocols conform to rhs's protocol; false
3654/// otherwise.
3655bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3656 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3657 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3658 return false;
3659}
3660
3661/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3662/// ObjCQualifiedIDType.
3663bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3664 bool compare) {
3665 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003666 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003667 lhs->isObjCIdType() || lhs->isObjCClassType())
3668 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003669 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003670 rhs->isObjCIdType() || rhs->isObjCClassType())
3671 return true;
3672
3673 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003674 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Steve Naroff4084c302009-07-23 01:01:38 +00003676 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003677
Steve Naroff4084c302009-07-23 01:01:38 +00003678 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003679 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003680 // make sure we check the class hierarchy.
3681 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3682 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3683 E = lhsQID->qual_end(); I != E; ++I) {
3684 // when comparing an id<P> on lhs with a static type on rhs,
3685 // see if static class implements all of id's protocols, directly or
3686 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003687 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003688 return false;
3689 }
3690 }
3691 // If there are no qualifiers and no interface, we have an 'id'.
3692 return true;
3693 }
Mike Stump1eb44332009-09-09 15:08:12 +00003694 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003695 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3696 E = lhsQID->qual_end(); I != E; ++I) {
3697 ObjCProtocolDecl *lhsProto = *I;
3698 bool match = false;
3699
3700 // when comparing an id<P> on lhs with a static type on rhs,
3701 // see if static class implements all of id's protocols, directly or
3702 // through its super class and categories.
3703 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3704 E = rhsOPT->qual_end(); J != E; ++J) {
3705 ObjCProtocolDecl *rhsProto = *J;
3706 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3707 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3708 match = true;
3709 break;
3710 }
3711 }
Mike Stump1eb44332009-09-09 15:08:12 +00003712 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003713 // make sure we check the class hierarchy.
3714 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3715 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3716 E = lhsQID->qual_end(); I != E; ++I) {
3717 // when comparing an id<P> on lhs with a static type on rhs,
3718 // see if static class implements all of id's protocols, directly or
3719 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003720 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003721 match = true;
3722 break;
3723 }
3724 }
3725 }
3726 if (!match)
3727 return false;
3728 }
Mike Stump1eb44332009-09-09 15:08:12 +00003729
Steve Naroff4084c302009-07-23 01:01:38 +00003730 return true;
3731 }
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Steve Naroff4084c302009-07-23 01:01:38 +00003733 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3734 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3735
Mike Stump1eb44332009-09-09 15:08:12 +00003736 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003737 lhs->getAsObjCInterfacePointerType()) {
3738 if (lhsOPT->qual_empty()) {
3739 bool match = false;
3740 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3741 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3742 E = rhsQID->qual_end(); I != E; ++I) {
3743 // when comparing an id<P> on lhs with a static type on rhs,
3744 // see if static class implements all of id's protocols, directly or
3745 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003746 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003747 match = true;
3748 break;
3749 }
3750 }
3751 if (!match)
3752 return false;
3753 }
3754 return true;
3755 }
Mike Stump1eb44332009-09-09 15:08:12 +00003756 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003757 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3758 E = lhsOPT->qual_end(); I != E; ++I) {
3759 ObjCProtocolDecl *lhsProto = *I;
3760 bool match = false;
3761
3762 // when comparing an id<P> on lhs with a static type on rhs,
3763 // see if static class implements all of id's protocols, directly or
3764 // through its super class and categories.
3765 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3766 E = rhsQID->qual_end(); J != E; ++J) {
3767 ObjCProtocolDecl *rhsProto = *J;
3768 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3769 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3770 match = true;
3771 break;
3772 }
3773 }
3774 if (!match)
3775 return false;
3776 }
3777 return true;
3778 }
3779 return false;
3780}
3781
Eli Friedman3d815e72008-08-22 00:56:42 +00003782/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003783/// compatible for assignment from RHS to LHS. This handles validation of any
3784/// protocol qualifiers on the LHS or RHS.
3785///
Steve Naroff14108da2009-07-10 23:34:53 +00003786bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3787 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003788 // If either type represents the built-in 'id' or 'Class' types, return true.
3789 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003790 return true;
3791
Steve Naroff4084c302009-07-23 01:01:38 +00003792 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003793 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3794 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003795 false);
3796
Steve Naroff14108da2009-07-10 23:34:53 +00003797 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3798 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003799 if (LHS && RHS) // We have 2 user-defined types.
3800 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Steve Naroff4084c302009-07-23 01:01:38 +00003802 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003803}
3804
Eli Friedman3d815e72008-08-22 00:56:42 +00003805bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3806 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003807 // Verify that the base decls are compatible: the RHS must be a subclass of
3808 // the LHS.
3809 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3810 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003811
Chris Lattner6ac46a42008-04-07 06:51:04 +00003812 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3813 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003814 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003815 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Chris Lattner6ac46a42008-04-07 06:51:04 +00003817 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3818 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003819 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003820 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003822 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3823 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003824 LHSPI != LHSPE; LHSPI++) {
3825 bool RHSImplementsProtocol = false;
3826
3827 // If the RHS doesn't implement the protocol on the left, the types
3828 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003829 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003830 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003831 RHSPI != RHSPE; RHSPI++) {
3832 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003833 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003834 break;
3835 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003836 }
3837 // FIXME: For better diagnostics, consider passing back the protocol name.
3838 if (!RHSImplementsProtocol)
3839 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003840 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003841 // The RHS implements all protocols listed on the LHS.
3842 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003843}
3844
Steve Naroff389bf462009-02-12 17:52:19 +00003845bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3846 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00003847 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
3848 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Steve Naroff14108da2009-07-10 23:34:53 +00003850 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003851 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003852
3853 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3854 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003855}
3856
Mike Stump1eb44332009-09-09 15:08:12 +00003857/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00003858/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00003859/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00003860/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003861bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3862 return !mergeTypes(LHS, RHS).isNull();
3863}
3864
3865QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00003866 const FunctionType *lbase = lhs->getAs<FunctionType>();
3867 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00003868 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3869 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003870 bool allLTypes = true;
3871 bool allRTypes = true;
3872
3873 // Check return type
3874 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3875 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003876 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3877 allLTypes = false;
3878 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3879 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003880 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003881 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3882 if (NoReturn != lbase->getNoReturnAttr())
3883 allLTypes = false;
3884 if (NoReturn != rbase->getNoReturnAttr())
3885 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Eli Friedman3d815e72008-08-22 00:56:42 +00003887 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003888 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3889 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003890 unsigned lproto_nargs = lproto->getNumArgs();
3891 unsigned rproto_nargs = rproto->getNumArgs();
3892
3893 // Compatible functions must have the same number of arguments
3894 if (lproto_nargs != rproto_nargs)
3895 return QualType();
3896
3897 // Variadic and non-variadic functions aren't compatible
3898 if (lproto->isVariadic() != rproto->isVariadic())
3899 return QualType();
3900
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003901 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3902 return QualType();
3903
Eli Friedman3d815e72008-08-22 00:56:42 +00003904 // Check argument compatibility
3905 llvm::SmallVector<QualType, 10> types;
3906 for (unsigned i = 0; i < lproto_nargs; i++) {
3907 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3908 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3909 QualType argtype = mergeTypes(largtype, rargtype);
3910 if (argtype.isNull()) return QualType();
3911 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003912 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3913 allLTypes = false;
3914 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3915 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003916 }
3917 if (allLTypes) return lhs;
3918 if (allRTypes) return rhs;
3919 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003920 lproto->isVariadic(), lproto->getTypeQuals(),
3921 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003922 }
3923
3924 if (lproto) allRTypes = false;
3925 if (rproto) allLTypes = false;
3926
Douglas Gregor72564e72009-02-26 23:50:07 +00003927 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003928 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003929 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003930 if (proto->isVariadic()) return QualType();
3931 // Check that the types are compatible with the types that
3932 // would result from default argument promotions (C99 6.7.5.3p15).
3933 // The only types actually affected are promotable integer
3934 // types and floats, which would be passed as a different
3935 // type depending on whether the prototype is visible.
3936 unsigned proto_nargs = proto->getNumArgs();
3937 for (unsigned i = 0; i < proto_nargs; ++i) {
3938 QualType argTy = proto->getArgType(i);
3939 if (argTy->isPromotableIntegerType() ||
3940 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3941 return QualType();
3942 }
3943
3944 if (allLTypes) return lhs;
3945 if (allRTypes) return rhs;
3946 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003947 proto->getNumArgs(), proto->isVariadic(),
3948 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003949 }
3950
3951 if (allLTypes) return lhs;
3952 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003953 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003954}
3955
3956QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003957 // C++ [expr]: If an expression initially has the type "reference to T", the
3958 // type is adjusted to "T" prior to any further analysis, the expression
3959 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003960 // expression is an lvalue unless the reference is an rvalue reference and
3961 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003962 // FIXME: C++ shouldn't be going through here! The rules are different
3963 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003964 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3965 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003966 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003967 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003968 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003969 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003970
Eli Friedman3d815e72008-08-22 00:56:42 +00003971 QualType LHSCan = getCanonicalType(LHS),
3972 RHSCan = getCanonicalType(RHS);
3973
3974 // If two types are identical, they are compatible.
3975 if (LHSCan == RHSCan)
3976 return LHS;
3977
John McCall0953e762009-09-24 19:53:00 +00003978 // If the qualifiers are different, the types aren't compatible... mostly.
3979 Qualifiers LQuals = LHSCan.getQualifiers();
3980 Qualifiers RQuals = RHSCan.getQualifiers();
3981 if (LQuals != RQuals) {
3982 // If any of these qualifiers are different, we have a type
3983 // mismatch.
3984 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
3985 LQuals.getAddressSpace() != RQuals.getAddressSpace())
3986 return QualType();
3987
3988 // Exactly one GC qualifier difference is allowed: __strong is
3989 // okay if the other type has no GC qualifier but is an Objective
3990 // C object pointer (i.e. implicitly strong by default). We fix
3991 // this by pretending that the unqualified type was actually
3992 // qualified __strong.
3993 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
3994 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
3995 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
3996
3997 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
3998 return QualType();
3999
4000 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4001 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4002 }
4003 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4004 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4005 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004006 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004007 }
4008
4009 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004010
Eli Friedman852d63b2009-06-01 01:22:52 +00004011 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4012 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004013
Chris Lattner1adb8832008-01-14 05:45:46 +00004014 // We want to consider the two function types to be the same for these
4015 // comparisons, just force one to the other.
4016 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4017 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004018
4019 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004020 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4021 LHSClass = Type::ConstantArray;
4022 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4023 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Nate Begeman213541a2008-04-18 23:10:10 +00004025 // Canonicalize ExtVector -> Vector.
4026 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4027 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Chris Lattnera36a61f2008-04-07 05:43:21 +00004029 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004030 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004031 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004032 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004033 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004034 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4035 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004036 }
John McCall183700f2009-09-21 23:43:11 +00004037 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004038 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4039 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004040 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004041
Eli Friedman3d815e72008-08-22 00:56:42 +00004042 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004043 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004044
Steve Naroff4a746782008-01-09 22:43:08 +00004045 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004046 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004047#define TYPE(Class, Base)
4048#define ABSTRACT_TYPE(Class, Base)
4049#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4050#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4051#include "clang/AST/TypeNodes.def"
4052 assert(false && "Non-canonical and dependent types shouldn't get here");
4053 return QualType();
4054
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004055 case Type::LValueReference:
4056 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004057 case Type::MemberPointer:
4058 assert(false && "C++ should never be in mergeTypes");
4059 return QualType();
4060
4061 case Type::IncompleteArray:
4062 case Type::VariableArray:
4063 case Type::FunctionProto:
4064 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004065 assert(false && "Types are eliminated above");
4066 return QualType();
4067
Chris Lattner1adb8832008-01-14 05:45:46 +00004068 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004069 {
4070 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004071 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4072 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004073 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4074 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004075 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004076 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004077 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004078 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004079 return getPointerType(ResultType);
4080 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004081 case Type::BlockPointer:
4082 {
4083 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004084 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4085 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004086 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4087 if (ResultType.isNull()) return QualType();
4088 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4089 return LHS;
4090 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4091 return RHS;
4092 return getBlockPointerType(ResultType);
4093 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004094 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004095 {
4096 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4097 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4098 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4099 return QualType();
4100
4101 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4102 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4103 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4104 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004105 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4106 return LHS;
4107 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4108 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004109 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4110 ArrayType::ArraySizeModifier(), 0);
4111 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4112 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004113 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4114 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004115 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4116 return LHS;
4117 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4118 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004119 if (LVAT) {
4120 // FIXME: This isn't correct! But tricky to implement because
4121 // the array's size has to be the size of LHS, but the type
4122 // has to be different.
4123 return LHS;
4124 }
4125 if (RVAT) {
4126 // FIXME: This isn't correct! But tricky to implement because
4127 // the array's size has to be the size of RHS, but the type
4128 // has to be different.
4129 return RHS;
4130 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004131 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4132 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004133 return getIncompleteArrayType(ResultType,
4134 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004135 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004136 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004137 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004138 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004139 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004140 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004141 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004142 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004143 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004144 case Type::Complex:
4145 // Distinct complex types are incompatible.
4146 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004147 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004148 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004149 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004150 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004151 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004152 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004153 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004154 // FIXME: This should be type compatibility, e.g. whether
4155 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004156 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4157 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004158 if (LHSIface && RHSIface &&
4159 canAssignObjCInterfaces(LHSIface, RHSIface))
4160 return LHS;
4161
Eli Friedman3d815e72008-08-22 00:56:42 +00004162 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004163 }
Steve Naroff14108da2009-07-10 23:34:53 +00004164 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004165 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4166 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004167 return LHS;
4168
Steve Naroffbc76dd02008-12-10 22:14:21 +00004169 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004170 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004171 case Type::FixedWidthInt:
4172 // Distinct fixed-width integers are not compatible.
4173 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004174 case Type::TemplateSpecialization:
4175 assert(false && "Dependent types have no size");
4176 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004177 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004178
4179 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004180}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004181
Chris Lattner5426bf62008-04-07 07:01:58 +00004182//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004183// Integer Predicates
4184//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004185
Eli Friedmanad74a752008-06-28 06:23:08 +00004186unsigned ASTContext::getIntWidth(QualType T) {
4187 if (T == BoolTy)
4188 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004189 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004190 return FWIT->getWidth();
4191 }
4192 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004193 return (unsigned)getTypeSize(T);
4194}
4195
4196QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4197 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004198
4199 // Turn <4 x signed int> -> <4 x unsigned int>
4200 if (const VectorType *VTy = T->getAs<VectorType>())
4201 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4202 VTy->getNumElements());
4203
4204 // For enums, we return the unsigned version of the base type.
4205 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004206 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004207
4208 const BuiltinType *BTy = T->getAs<BuiltinType>();
4209 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004210 switch (BTy->getKind()) {
4211 case BuiltinType::Char_S:
4212 case BuiltinType::SChar:
4213 return UnsignedCharTy;
4214 case BuiltinType::Short:
4215 return UnsignedShortTy;
4216 case BuiltinType::Int:
4217 return UnsignedIntTy;
4218 case BuiltinType::Long:
4219 return UnsignedLongTy;
4220 case BuiltinType::LongLong:
4221 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004222 case BuiltinType::Int128:
4223 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004224 default:
4225 assert(0 && "Unexpected signed integer type");
4226 return QualType();
4227 }
4228}
4229
Douglas Gregor2cf26342009-04-09 22:27:44 +00004230ExternalASTSource::~ExternalASTSource() { }
4231
4232void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004233
4234
4235//===----------------------------------------------------------------------===//
4236// Builtin Type Computation
4237//===----------------------------------------------------------------------===//
4238
4239/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4240/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004241static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004242 ASTContext::GetBuiltinTypeError &Error,
4243 bool AllowTypeModifiers = true) {
4244 // Modifiers.
4245 int HowLong = 0;
4246 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004247
Chris Lattner86df27b2009-06-14 00:45:47 +00004248 // Read the modifiers first.
4249 bool Done = false;
4250 while (!Done) {
4251 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004252 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004253 case 'S':
4254 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4255 assert(!Signed && "Can't use 'S' modifier multiple times!");
4256 Signed = true;
4257 break;
4258 case 'U':
4259 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4260 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4261 Unsigned = true;
4262 break;
4263 case 'L':
4264 assert(HowLong <= 2 && "Can't have LLLL modifier");
4265 ++HowLong;
4266 break;
4267 }
4268 }
4269
4270 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Chris Lattner86df27b2009-06-14 00:45:47 +00004272 // Read the base type.
4273 switch (*Str++) {
4274 default: assert(0 && "Unknown builtin type letter!");
4275 case 'v':
4276 assert(HowLong == 0 && !Signed && !Unsigned &&
4277 "Bad modifiers used with 'v'!");
4278 Type = Context.VoidTy;
4279 break;
4280 case 'f':
4281 assert(HowLong == 0 && !Signed && !Unsigned &&
4282 "Bad modifiers used with 'f'!");
4283 Type = Context.FloatTy;
4284 break;
4285 case 'd':
4286 assert(HowLong < 2 && !Signed && !Unsigned &&
4287 "Bad modifiers used with 'd'!");
4288 if (HowLong)
4289 Type = Context.LongDoubleTy;
4290 else
4291 Type = Context.DoubleTy;
4292 break;
4293 case 's':
4294 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4295 if (Unsigned)
4296 Type = Context.UnsignedShortTy;
4297 else
4298 Type = Context.ShortTy;
4299 break;
4300 case 'i':
4301 if (HowLong == 3)
4302 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4303 else if (HowLong == 2)
4304 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4305 else if (HowLong == 1)
4306 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4307 else
4308 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4309 break;
4310 case 'c':
4311 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4312 if (Signed)
4313 Type = Context.SignedCharTy;
4314 else if (Unsigned)
4315 Type = Context.UnsignedCharTy;
4316 else
4317 Type = Context.CharTy;
4318 break;
4319 case 'b': // boolean
4320 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4321 Type = Context.BoolTy;
4322 break;
4323 case 'z': // size_t.
4324 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4325 Type = Context.getSizeType();
4326 break;
4327 case 'F':
4328 Type = Context.getCFConstantStringType();
4329 break;
4330 case 'a':
4331 Type = Context.getBuiltinVaListType();
4332 assert(!Type.isNull() && "builtin va list type not initialized!");
4333 break;
4334 case 'A':
4335 // This is a "reference" to a va_list; however, what exactly
4336 // this means depends on how va_list is defined. There are two
4337 // different kinds of va_list: ones passed by value, and ones
4338 // passed by reference. An example of a by-value va_list is
4339 // x86, where va_list is a char*. An example of by-ref va_list
4340 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4341 // we want this argument to be a char*&; for x86-64, we want
4342 // it to be a __va_list_tag*.
4343 Type = Context.getBuiltinVaListType();
4344 assert(!Type.isNull() && "builtin va list type not initialized!");
4345 if (Type->isArrayType()) {
4346 Type = Context.getArrayDecayedType(Type);
4347 } else {
4348 Type = Context.getLValueReferenceType(Type);
4349 }
4350 break;
4351 case 'V': {
4352 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004353 unsigned NumElements = strtoul(Str, &End, 10);
4354 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004355
Chris Lattner86df27b2009-06-14 00:45:47 +00004356 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Chris Lattner86df27b2009-06-14 00:45:47 +00004358 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4359 Type = Context.getVectorType(ElementType, NumElements);
4360 break;
4361 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004362 case 'X': {
4363 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4364 Type = Context.getComplexType(ElementType);
4365 break;
4366 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004367 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004368 Type = Context.getFILEType();
4369 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004370 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004371 return QualType();
4372 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004373 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004374 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004375 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004376 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004377 else
4378 Type = Context.getjmp_bufType();
4379
Mike Stumpfd612db2009-07-28 23:47:15 +00004380 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004381 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004382 return QualType();
4383 }
4384 break;
Mike Stump782fa302009-07-28 02:25:19 +00004385 }
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Chris Lattner86df27b2009-06-14 00:45:47 +00004387 if (!AllowTypeModifiers)
4388 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Chris Lattner86df27b2009-06-14 00:45:47 +00004390 Done = false;
4391 while (!Done) {
4392 switch (*Str++) {
4393 default: Done = true; --Str; break;
4394 case '*':
4395 Type = Context.getPointerType(Type);
4396 break;
4397 case '&':
4398 Type = Context.getLValueReferenceType(Type);
4399 break;
4400 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4401 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004402 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004403 break;
4404 }
4405 }
Mike Stump1eb44332009-09-09 15:08:12 +00004406
Chris Lattner86df27b2009-06-14 00:45:47 +00004407 return Type;
4408}
4409
4410/// GetBuiltinType - Return the type for the specified builtin.
4411QualType ASTContext::GetBuiltinType(unsigned id,
4412 GetBuiltinTypeError &Error) {
4413 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004414
Chris Lattner86df27b2009-06-14 00:45:47 +00004415 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004416
Chris Lattner86df27b2009-06-14 00:45:47 +00004417 Error = GE_None;
4418 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4419 if (Error != GE_None)
4420 return QualType();
4421 while (TypeStr[0] && TypeStr[0] != '.') {
4422 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4423 if (Error != GE_None)
4424 return QualType();
4425
4426 // Do array -> pointer decay. The builtin should use the decayed type.
4427 if (Ty->isArrayType())
4428 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004429
Chris Lattner86df27b2009-06-14 00:45:47 +00004430 ArgTypes.push_back(Ty);
4431 }
4432
4433 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4434 "'.' should only occur at end of builtin type list!");
4435
4436 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4437 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4438 return getFunctionNoProtoType(ResType);
4439 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4440 TypeStr[0] == '.', 0);
4441}
Eli Friedmana95d7572009-08-19 07:44:53 +00004442
4443QualType
4444ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4445 // Perform the usual unary conversions. We do this early so that
4446 // integral promotions to "int" can allow us to exit early, in the
4447 // lhs == rhs check. Also, for conversion purposes, we ignore any
4448 // qualifiers. For example, "const float" and "float" are
4449 // equivalent.
4450 if (lhs->isPromotableIntegerType())
4451 lhs = getPromotedIntegerType(lhs);
4452 else
4453 lhs = lhs.getUnqualifiedType();
4454 if (rhs->isPromotableIntegerType())
4455 rhs = getPromotedIntegerType(rhs);
4456 else
4457 rhs = rhs.getUnqualifiedType();
4458
4459 // If both types are identical, no conversion is needed.
4460 if (lhs == rhs)
4461 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Eli Friedmana95d7572009-08-19 07:44:53 +00004463 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4464 // The caller can deal with this (e.g. pointer + int).
4465 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4466 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004467
4468 // At this point, we have two different arithmetic types.
4469
Eli Friedmana95d7572009-08-19 07:44:53 +00004470 // Handle complex types first (C99 6.3.1.8p1).
4471 if (lhs->isComplexType() || rhs->isComplexType()) {
4472 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004473 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004474 // convert the rhs to the lhs complex type.
4475 return lhs;
4476 }
Mike Stump1eb44332009-09-09 15:08:12 +00004477 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004478 // convert the lhs to the rhs complex type.
4479 return rhs;
4480 }
4481 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004482 // When both operands are complex, the shorter operand is converted to the
4483 // type of the longer, and that is the type of the result. This corresponds
4484 // to what is done when combining two real floating-point operands.
4485 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004486 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004487 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004488 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004489 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004490 // "double _Complex" is promoted to "long double _Complex".
4491 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004492
4493 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004494 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004495 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004496 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004497 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004498 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4499 // domains match. This is a requirement for our implementation, C99
4500 // does not require this promotion.
4501 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4502 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4503 return rhs;
4504 } else { // handle "_Complex double, double".
4505 return lhs;
4506 }
4507 }
4508 return lhs; // The domain/size match exactly.
4509 }
4510 // Now handle "real" floating types (i.e. float, double, long double).
4511 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4512 // if we have an integer operand, the result is the real floating type.
4513 if (rhs->isIntegerType()) {
4514 // convert rhs to the lhs floating point type.
4515 return lhs;
4516 }
4517 if (rhs->isComplexIntegerType()) {
4518 // convert rhs to the complex floating point type.
4519 return getComplexType(lhs);
4520 }
4521 if (lhs->isIntegerType()) {
4522 // convert lhs to the rhs floating point type.
4523 return rhs;
4524 }
Mike Stump1eb44332009-09-09 15:08:12 +00004525 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004526 // convert lhs to the complex floating point type.
4527 return getComplexType(rhs);
4528 }
4529 // We have two real floating types, float/complex combos were handled above.
4530 // Convert the smaller operand to the bigger result.
4531 int result = getFloatingTypeOrder(lhs, rhs);
4532 if (result > 0) // convert the rhs
4533 return lhs;
4534 assert(result < 0 && "illegal float comparison");
4535 return rhs; // convert the lhs
4536 }
4537 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4538 // Handle GCC complex int extension.
4539 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4540 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4541
4542 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004543 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004544 rhsComplexInt->getElementType()) >= 0)
4545 return lhs; // convert the rhs
4546 return rhs;
4547 } else if (lhsComplexInt && rhs->isIntegerType()) {
4548 // convert the rhs to the lhs complex type.
4549 return lhs;
4550 } else if (rhsComplexInt && lhs->isIntegerType()) {
4551 // convert the lhs to the rhs complex type.
4552 return rhs;
4553 }
4554 }
4555 // Finally, we have two differing integer types.
4556 // The rules for this case are in C99 6.3.1.8
4557 int compare = getIntegerTypeOrder(lhs, rhs);
4558 bool lhsSigned = lhs->isSignedIntegerType(),
4559 rhsSigned = rhs->isSignedIntegerType();
4560 QualType destType;
4561 if (lhsSigned == rhsSigned) {
4562 // Same signedness; use the higher-ranked type
4563 destType = compare >= 0 ? lhs : rhs;
4564 } else if (compare != (lhsSigned ? 1 : -1)) {
4565 // The unsigned type has greater than or equal rank to the
4566 // signed type, so use the unsigned type
4567 destType = lhsSigned ? rhs : lhs;
4568 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4569 // The two types are different widths; if we are here, that
4570 // means the signed type is larger than the unsigned type, so
4571 // use the signed type.
4572 destType = lhsSigned ? lhs : rhs;
4573 } else {
4574 // The signed type is higher-ranked than the unsigned type,
4575 // but isn't actually any bigger (like unsigned int and long
4576 // on most 32-bit systems). Use the unsigned type corresponding
4577 // to the signed type.
4578 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4579 }
4580 return destType;
4581}