blob: 7d9bc0f47255377982c9e61ff10e2f3d84a2724f [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: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000585 const VectorType *VT = cast<VectorType>(T);
586 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
587 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000588 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000589 // If the alignment is not a power of 2, round up to the next power of 2.
590 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000591 if (VT->getNumElements() & (VT->getNumElements()-1)) {
592 Align = llvm::NextPowerOf2(Align);
593 Width = llvm::RoundUpToAlignment(Width, Align);
594 }
Chris Lattner030d8842007-07-19 22:06:24 +0000595 break;
596 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000597
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000598 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000599 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000600 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000601 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000602 // GCC extension: alignof(void) = 8 bits.
603 Width = 0;
604 Align = 8;
605 break;
606
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000607 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000608 Width = Target.getBoolWidth();
609 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000610 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000611 case BuiltinType::Char_S:
612 case BuiltinType::Char_U:
613 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000614 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000615 Width = Target.getCharWidth();
616 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000617 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000618 case BuiltinType::WChar:
619 Width = Target.getWCharWidth();
620 Align = Target.getWCharAlign();
621 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000622 case BuiltinType::Char16:
623 Width = Target.getChar16Width();
624 Align = Target.getChar16Align();
625 break;
626 case BuiltinType::Char32:
627 Width = Target.getChar32Width();
628 Align = Target.getChar32Align();
629 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000630 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getShortWidth();
633 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000636 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000637 Width = Target.getIntWidth();
638 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000640 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000642 Width = Target.getLongWidth();
643 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000645 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000646 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000647 Width = Target.getLongLongWidth();
648 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000649 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000650 case BuiltinType::Int128:
651 case BuiltinType::UInt128:
652 Width = 128;
653 Align = 128; // int128_t is 128-bit aligned on all targets.
654 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getFloatWidth();
657 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
659 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000660 Width = Target.getDoubleWidth();
661 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 break;
663 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000664 Width = Target.getLongDoubleWidth();
665 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000666 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000667 case BuiltinType::NullPtr:
668 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
669 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000670 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000671 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000672 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000673 case Type::FixedWidthInt:
674 // FIXME: This isn't precisely correct; the width/alignment should depend
675 // on the available types for the target
676 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000677 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000678 Align = Width;
679 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000680 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000681 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000682 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000684 case Type::BlockPointer: {
685 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
686 Width = Target.getPointerWidth(AS);
687 Align = Target.getPointerAlign(AS);
688 break;
689 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000690 case Type::Pointer: {
691 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000692 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000693 Align = Target.getPointerAlign(AS);
694 break;
695 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000696 case Type::LValueReference:
697 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000698 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000699 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000700 // FIXME: This is wrong for struct layout: a reference in a struct has
701 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000702 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000703 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000704 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
705 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
706 // If we ever want to support other ABIs this needs to be abstracted.
707
Sebastian Redlf30208a2009-01-24 21:16:55 +0000708 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000709 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000710 getTypeInfo(getPointerDiffType());
711 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000712 if (Pointee->isFunctionType())
713 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000714 Align = PtrDiffInfo.second;
715 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000716 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000717 case Type::Complex: {
718 // Complex types have the same alignment as their elements, but twice the
719 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000720 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000721 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000722 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000723 Align = EltInfo.second;
724 break;
725 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000726 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000727 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000728 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
729 Width = Layout.getSize();
730 Align = Layout.getAlignment();
731 break;
732 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000733 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000734 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000735 const TagType *TT = cast<TagType>(T);
736
737 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000738 Width = 1;
739 Align = 1;
740 break;
741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Daniel Dunbar1d751182008-11-08 05:48:37 +0000743 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000744 return getTypeInfo(ET->getDecl()->getIntegerType());
745
Daniel Dunbar1d751182008-11-08 05:48:37 +0000746 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000747 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
748 Width = Layout.getSize();
749 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000750 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000751 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000752
Chris Lattner9fcfe922009-10-22 05:17:15 +0000753 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000754 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
755 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000756
Chris Lattner9fcfe922009-10-22 05:17:15 +0000757 case Type::Elaborated:
758 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
759 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000760
Douglas Gregor18857642009-04-30 17:32:17 +0000761 case Type::Typedef: {
762 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000763 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000764 Align = Aligned->getAlignment();
765 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
766 } else
767 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000768 break;
Chris Lattner71763312008-04-06 22:05:18 +0000769 }
Douglas Gregor18857642009-04-30 17:32:17 +0000770
771 case Type::TypeOfExpr:
772 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
773 .getTypePtr());
774
775 case Type::TypeOf:
776 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
777
Anders Carlsson395b4752009-06-24 19:06:50 +0000778 case Type::Decltype:
779 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
780 .getTypePtr());
781
Douglas Gregor18857642009-04-30 17:32:17 +0000782 case Type::QualifiedName:
783 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregor18857642009-04-30 17:32:17 +0000785 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000786 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000787 "Cannot request the size of a dependent type");
788 // FIXME: this is likely to be wrong once we support template
789 // aliases, since a template alias could refer to a typedef that
790 // has an __aligned__ attribute on it.
791 return getTypeInfo(getCanonicalType(T));
792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Chris Lattner464175b2007-07-18 17:52:12 +0000794 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000795 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000796}
797
Chris Lattner34ebde42009-01-27 18:08:34 +0000798/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
799/// type for the current target in bits. This can be different than the ABI
800/// alignment in cases where it is beneficial for performance to overalign
801/// a data type.
802unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
803 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000804
805 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000806 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000807 T = CT->getElementType().getTypePtr();
808 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
809 T->isSpecificBuiltinType(BuiltinType::LongLong))
810 return std::max(ABIAlign, (unsigned)getTypeSize(T));
811
Chris Lattner34ebde42009-01-27 18:08:34 +0000812 return ABIAlign;
813}
814
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000815static void CollectLocalObjCIvars(ASTContext *Ctx,
816 const ObjCInterfaceDecl *OI,
817 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000818 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
819 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000820 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000821 if (!IVDecl->isInvalidDecl())
822 Fields.push_back(cast<FieldDecl>(IVDecl));
823 }
824}
825
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000826void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
827 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
828 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
829 CollectObjCIvars(SuperClass, Fields);
830 CollectLocalObjCIvars(this, OI, Fields);
831}
832
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000833/// ShallowCollectObjCIvars -
834/// Collect all ivars, including those synthesized, in the current class.
835///
836void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
837 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
838 bool CollectSynthesized) {
839 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
840 E = OI->ivar_end(); I != E; ++I) {
841 Ivars.push_back(*I);
842 }
843 if (CollectSynthesized)
844 CollectSynthesizedIvars(OI, Ivars);
845}
846
Fariborz Jahanian98200742009-05-12 18:14:29 +0000847void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
848 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000849 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
850 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000851 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
852 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Fariborz Jahanian98200742009-05-12 18:14:29 +0000854 // Also look into nested protocols.
855 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
856 E = PD->protocol_end(); P != E; ++P)
857 CollectProtocolSynthesizedIvars(*P, Ivars);
858}
859
860/// CollectSynthesizedIvars -
861/// This routine collect synthesized ivars for the designated class.
862///
863void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
864 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000865 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
866 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000867 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
868 Ivars.push_back(Ivar);
869 }
870 // Also look into interface's protocol list for properties declared
871 // in the protocol and whose ivars are synthesized.
872 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
873 PE = OI->protocol_end(); P != PE; ++P) {
874 ObjCProtocolDecl *PD = (*P);
875 CollectProtocolSynthesizedIvars(PD, Ivars);
876 }
877}
878
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000879unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
880 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000881 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
882 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000883 if ((*I)->getPropertyIvarDecl())
884 ++count;
885
886 // Also look into nested protocols.
887 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
888 E = PD->protocol_end(); P != E; ++P)
889 count += CountProtocolSynthesizedIvars(*P);
890 return count;
891}
892
Mike Stump1eb44332009-09-09 15:08:12 +0000893unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000894 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000895 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
896 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000897 if ((*I)->getPropertyIvarDecl())
898 ++count;
899 }
900 // Also look into interface's protocol list for properties declared
901 // in the protocol and whose ivars are synthesized.
902 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
903 PE = OI->protocol_end(); P != PE; ++P) {
904 ObjCProtocolDecl *PD = (*P);
905 count += CountProtocolSynthesizedIvars(PD);
906 }
907 return count;
908}
909
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000910/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
911ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
912 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
913 I = ObjCImpls.find(D);
914 if (I != ObjCImpls.end())
915 return cast<ObjCImplementationDecl>(I->second);
916 return 0;
917}
918/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
919ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
920 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
921 I = ObjCImpls.find(D);
922 if (I != ObjCImpls.end())
923 return cast<ObjCCategoryImplDecl>(I->second);
924 return 0;
925}
926
927/// \brief Set the implementation of ObjCInterfaceDecl.
928void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
929 ObjCImplementationDecl *ImplD) {
930 assert(IFaceD && ImplD && "Passed null params");
931 ObjCImpls[IFaceD] = ImplD;
932}
933/// \brief Set the implementation of ObjCCategoryDecl.
934void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
935 ObjCCategoryImplDecl *ImplD) {
936 assert(CatD && ImplD && "Passed null params");
937 ObjCImpls[CatD] = ImplD;
938}
939
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000940/// \brief Allocate an uninitialized DeclaratorInfo.
941///
942/// The caller should initialize the memory held by DeclaratorInfo using
943/// the TypeLoc wrappers.
944///
945/// \param T the type that will be the basis for type source info. This type
946/// should refer to how the declarator was written in source code, not to
947/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +0000948DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
949 unsigned DataSize) {
950 if (!DataSize)
951 DataSize = TypeLoc::getFullDataSizeForType(T);
952 else
953 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
954 "incorrect data size provided to CreateDeclaratorInfo!");
955
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000956 DeclaratorInfo *DInfo =
957 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
958 new (DInfo) DeclaratorInfo(T);
959 return DInfo;
960}
961
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000962/// getInterfaceLayoutImpl - Get or compute information about the
963/// layout of the given interface.
964///
965/// \param Impl - If given, also include the layout of the interface's
966/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000967const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000968ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
969 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000970 assert(!D->isForwardDecl() && "Invalid interface decl!");
971
Devang Patel44a3dde2008-06-04 21:54:36 +0000972 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +0000973 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000974 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
975 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
976 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000977
Daniel Dunbar453addb2009-05-03 11:16:44 +0000978 // Add in synthesized ivar count if laying out an implementation.
979 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000980 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000981 unsigned SynthCount = CountSynthesizedIvars(D);
982 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000983 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000984 // entry. Note we can't cache this because we simply free all
985 // entries later; however we shouldn't look up implementations
986 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000987 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000988 return getObjCLayout(D, 0);
989 }
990
Mike Stump1eb44332009-09-09 15:08:12 +0000991 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +0000992 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
993 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Devang Patel44a3dde2008-06-04 21:54:36 +0000995 return *NewEntry;
996}
997
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000998const ASTRecordLayout &
999ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1000 return getObjCLayout(D, 0);
1001}
1002
1003const ASTRecordLayout &
1004ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1005 return getObjCLayout(D->getClassInterface(), D);
1006}
1007
Devang Patel88a981b2007-11-01 19:11:01 +00001008/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001009/// specified record (struct/union/class), which indicates its size and field
1010/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001011const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001012 D = D->getDefinition(*this);
1013 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001014
Chris Lattner464175b2007-07-18 17:52:12 +00001015 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001016 // Note that we can't save a reference to the entry because this function
1017 // is recursive.
1018 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001019 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001020
Mike Stump1eb44332009-09-09 15:08:12 +00001021 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001022 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001023 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattner5d2a6302007-07-18 18:26:58 +00001025 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001026}
1027
Chris Lattnera7674d82007-07-13 22:13:22 +00001028//===----------------------------------------------------------------------===//
1029// Type creation/memoization methods
1030//===----------------------------------------------------------------------===//
1031
John McCall0953e762009-09-24 19:53:00 +00001032QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1033 unsigned Fast = Quals.getFastQualifiers();
1034 Quals.removeFastQualifiers();
1035
1036 // Check if we've already instantiated this type.
1037 llvm::FoldingSetNodeID ID;
1038 ExtQuals::Profile(ID, TypeNode, Quals);
1039 void *InsertPos = 0;
1040 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1041 assert(EQ->getQualifiers() == Quals);
1042 QualType T = QualType(EQ, Fast);
1043 return T;
1044 }
1045
John McCall6b304a02009-09-24 23:30:46 +00001046 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001047 ExtQualNodes.InsertNode(New, InsertPos);
1048 QualType T = QualType(New, Fast);
1049 return T;
1050}
1051
1052QualType ASTContext::getVolatileType(QualType T) {
1053 QualType CanT = getCanonicalType(T);
1054 if (CanT.isVolatileQualified()) return T;
1055
1056 QualifierCollector Quals;
1057 const Type *TypeNode = Quals.strip(T);
1058 Quals.addVolatile();
1059
1060 return getExtQualType(TypeNode, Quals);
1061}
1062
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001063QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001064 QualType CanT = getCanonicalType(T);
1065 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001066 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001067
John McCall0953e762009-09-24 19:53:00 +00001068 // If we are composing extended qualifiers together, merge together
1069 // into one ExtQuals node.
1070 QualifierCollector Quals;
1071 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
John McCall0953e762009-09-24 19:53:00 +00001073 // If this type already has an address space specified, it cannot get
1074 // another one.
1075 assert(!Quals.hasAddressSpace() &&
1076 "Type cannot be in multiple addr spaces!");
1077 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001078
John McCall0953e762009-09-24 19:53:00 +00001079 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001080}
1081
Chris Lattnerb7d25532009-02-18 22:53:11 +00001082QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001083 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001084 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001085 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001086 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001088 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001089 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001090 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001091 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1092 return getPointerType(ResultType);
1093 }
1094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
John McCall0953e762009-09-24 19:53:00 +00001096 // If we are composing extended qualifiers together, merge together
1097 // into one ExtQuals node.
1098 QualifierCollector Quals;
1099 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001100
John McCall0953e762009-09-24 19:53:00 +00001101 // If this type already has an ObjCGC specified, it cannot get
1102 // another one.
1103 assert(!Quals.hasObjCGCAttr() &&
1104 "Type cannot have multiple ObjCGCs!");
1105 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
John McCall0953e762009-09-24 19:53:00 +00001107 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001108}
Chris Lattnera7674d82007-07-13 22:13:22 +00001109
Mike Stump24556362009-07-25 21:26:53 +00001110QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001111 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001112 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001113 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001114 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001115 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001116 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001117 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001118 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001119 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001120 } else {
1121 assert (T->isFunctionType()
1122 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001124 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1125 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001126 } else {
1127 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1128 ResultType
1129 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1130 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1131 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1132 F->getNumExceptions(), F->exception_begin(), true);
1133 }
Mike Stump24556362009-07-25 21:26:53 +00001134 }
John McCall0953e762009-09-24 19:53:00 +00001135
1136 return getQualifiedType(ResultType, T.getQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001137}
1138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139/// getComplexType - Return the uniqued reference to the type for a complex
1140/// number with the specified element type.
1141QualType ASTContext::getComplexType(QualType T) {
1142 // Unique pointers, to guarantee there is only one pointer of a particular
1143 // structure.
1144 llvm::FoldingSetNodeID ID;
1145 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 void *InsertPos = 0;
1148 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1149 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 // If the pointee type isn't canonical, this won't be a canonical type either,
1152 // so fill in the canonical type field.
1153 QualType Canonical;
1154 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001155 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 // Get the new insert position for the node we care about.
1158 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001159 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 }
John McCall6b304a02009-09-24 23:30:46 +00001161 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 Types.push_back(New);
1163 ComplexTypes.InsertNode(New, InsertPos);
1164 return QualType(New, 0);
1165}
1166
Eli Friedmanf98aba32009-02-13 02:31:07 +00001167QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1168 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1169 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1170 FixedWidthIntType *&Entry = Map[Width];
1171 if (!Entry)
1172 Entry = new FixedWidthIntType(Width, Signed);
1173 return QualType(Entry, 0);
1174}
Reid Spencer5f016e22007-07-11 17:01:13 +00001175
1176/// getPointerType - Return the uniqued reference to the type for a pointer to
1177/// the specified type.
1178QualType ASTContext::getPointerType(QualType T) {
1179 // Unique pointers, to guarantee there is only one pointer of a particular
1180 // structure.
1181 llvm::FoldingSetNodeID ID;
1182 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 void *InsertPos = 0;
1185 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1186 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 // If the pointee type isn't canonical, this won't be a canonical type either,
1189 // so fill in the canonical type field.
1190 QualType Canonical;
1191 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001192 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 // Get the new insert position for the node we care about.
1195 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001196 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 }
John McCall6b304a02009-09-24 23:30:46 +00001198 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 Types.push_back(New);
1200 PointerTypes.InsertNode(New, InsertPos);
1201 return QualType(New, 0);
1202}
1203
Mike Stump1eb44332009-09-09 15:08:12 +00001204/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001205/// a pointer to the specified block.
1206QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001207 assert(T->isFunctionType() && "block of function types only");
1208 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001209 // structure.
1210 llvm::FoldingSetNodeID ID;
1211 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Steve Naroff5618bd42008-08-27 16:04:49 +00001213 void *InsertPos = 0;
1214 if (BlockPointerType *PT =
1215 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1216 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
1218 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001219 // type either so fill in the canonical type field.
1220 QualType Canonical;
1221 if (!T->isCanonical()) {
1222 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Steve Naroff5618bd42008-08-27 16:04:49 +00001224 // Get the new insert position for the node we care about.
1225 BlockPointerType *NewIP =
1226 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001227 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001228 }
John McCall6b304a02009-09-24 23:30:46 +00001229 BlockPointerType *New
1230 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001231 Types.push_back(New);
1232 BlockPointerTypes.InsertNode(New, InsertPos);
1233 return QualType(New, 0);
1234}
1235
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001236/// getLValueReferenceType - Return the uniqued reference to the type for an
1237/// lvalue reference to the specified type.
1238QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // Unique pointers, to guarantee there is only one pointer of a particular
1240 // structure.
1241 llvm::FoldingSetNodeID ID;
1242 ReferenceType::Profile(ID, T);
1243
1244 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001245 if (LValueReferenceType *RT =
1246 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // If the referencee type isn't canonical, this won't be a canonical type
1250 // either, so fill in the canonical type field.
1251 QualType Canonical;
1252 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001253 Canonical = getLValueReferenceType(getCanonicalType(T));
1254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001256 LValueReferenceType *NewIP =
1257 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001258 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 }
1260
John McCall6b304a02009-09-24 23:30:46 +00001261 LValueReferenceType *New
1262 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001264 LValueReferenceTypes.InsertNode(New, InsertPos);
1265 return QualType(New, 0);
1266}
1267
1268/// getRValueReferenceType - Return the uniqued reference to the type for an
1269/// rvalue reference to the specified type.
1270QualType ASTContext::getRValueReferenceType(QualType T) {
1271 // Unique pointers, to guarantee there is only one pointer of a particular
1272 // structure.
1273 llvm::FoldingSetNodeID ID;
1274 ReferenceType::Profile(ID, T);
1275
1276 void *InsertPos = 0;
1277 if (RValueReferenceType *RT =
1278 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1279 return QualType(RT, 0);
1280
1281 // If the referencee type isn't canonical, this won't be a canonical type
1282 // either, so fill in the canonical type field.
1283 QualType Canonical;
1284 if (!T->isCanonical()) {
1285 Canonical = getRValueReferenceType(getCanonicalType(T));
1286
1287 // Get the new insert position for the node we care about.
1288 RValueReferenceType *NewIP =
1289 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1290 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1291 }
1292
John McCall6b304a02009-09-24 23:30:46 +00001293 RValueReferenceType *New
1294 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001295 Types.push_back(New);
1296 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 return QualType(New, 0);
1298}
1299
Sebastian Redlf30208a2009-01-24 21:16:55 +00001300/// getMemberPointerType - Return the uniqued reference to the type for a
1301/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001302QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001303 // Unique pointers, to guarantee there is only one pointer of a particular
1304 // structure.
1305 llvm::FoldingSetNodeID ID;
1306 MemberPointerType::Profile(ID, T, Cls);
1307
1308 void *InsertPos = 0;
1309 if (MemberPointerType *PT =
1310 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1311 return QualType(PT, 0);
1312
1313 // If the pointee or class type isn't canonical, this won't be a canonical
1314 // type either, so fill in the canonical type field.
1315 QualType Canonical;
1316 if (!T->isCanonical()) {
1317 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1318
1319 // Get the new insert position for the node we care about.
1320 MemberPointerType *NewIP =
1321 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1322 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1323 }
John McCall6b304a02009-09-24 23:30:46 +00001324 MemberPointerType *New
1325 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001326 Types.push_back(New);
1327 MemberPointerTypes.InsertNode(New, InsertPos);
1328 return QualType(New, 0);
1329}
1330
Mike Stump1eb44332009-09-09 15:08:12 +00001331/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001332/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001333QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001334 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001335 ArrayType::ArraySizeModifier ASM,
1336 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001337 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1338 "Constant array of VLAs is illegal!");
1339
Chris Lattner38aeec72009-05-13 04:12:56 +00001340 // Convert the array size into a canonical width matching the pointer size for
1341 // the target.
1342 llvm::APInt ArySize(ArySizeIn);
1343 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001346 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001349 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001350 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // If the element type isn't canonical, this won't be a canonical type either,
1354 // so fill in the canonical type field.
1355 QualType Canonical;
1356 if (!EltTy->isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001357 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001358 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001360 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001361 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001362 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
John McCall6b304a02009-09-24 23:30:46 +00001365 ConstantArrayType *New = new(*this,TypeAlignment)
1366 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001367 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 Types.push_back(New);
1369 return QualType(New, 0);
1370}
1371
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001372/// getVariableArrayType - Returns a non-unique reference to the type for a
1373/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001374QualType ASTContext::getVariableArrayType(QualType EltTy,
1375 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001376 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001377 unsigned EltTypeQuals,
1378 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001379 // Since we don't unique expressions, it isn't possible to unique VLA's
1380 // that have an expression provided for their size.
1381
John McCall6b304a02009-09-24 23:30:46 +00001382 VariableArrayType *New = new(*this, TypeAlignment)
1383 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001384
1385 VariableArrayTypes.push_back(New);
1386 Types.push_back(New);
1387 return QualType(New, 0);
1388}
1389
Douglas Gregor898574e2008-12-05 23:32:09 +00001390/// getDependentSizedArrayType - Returns a non-unique reference to
1391/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001392/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001393QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1394 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001395 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001396 unsigned EltTypeQuals,
1397 SourceRange Brackets) {
Mike Stump1eb44332009-09-09 15:08:12 +00001398 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001399 "Size must be type- or value-dependent!");
1400
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001401 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001402 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001403 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001404
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001405 void *InsertPos = 0;
1406 DependentSizedArrayType *Canon
1407 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1408 DependentSizedArrayType *New;
1409 if (Canon) {
1410 // We already have a canonical version of this array type; use it as
1411 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001412 New = new (*this, TypeAlignment)
1413 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1414 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001415 } else {
1416 QualType CanonEltTy = getCanonicalType(EltTy);
1417 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001418 New = new (*this, TypeAlignment)
1419 DependentSizedArrayType(*this, EltTy, QualType(),
1420 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001421 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1422 } else {
1423 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1424 ASM, EltTypeQuals,
1425 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001426 New = new (*this, TypeAlignment)
1427 DependentSizedArrayType(*this, EltTy, Canon,
1428 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001429 }
1430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Douglas Gregor898574e2008-12-05 23:32:09 +00001432 Types.push_back(New);
1433 return QualType(New, 0);
1434}
1435
Eli Friedmanc5773c42008-02-15 18:16:39 +00001436QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1437 ArrayType::ArraySizeModifier ASM,
1438 unsigned EltTypeQuals) {
1439 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001440 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001441
1442 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001443 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001444 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1445 return QualType(ATP, 0);
1446
1447 // If the element type isn't canonical, this won't be a canonical type
1448 // either, so fill in the canonical type field.
1449 QualType Canonical;
1450
1451 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001452 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001453 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001454
1455 // Get the new insert position for the node we care about.
1456 IncompleteArrayType *NewIP =
1457 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001458 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001459 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001460
John McCall6b304a02009-09-24 23:30:46 +00001461 IncompleteArrayType *New = new (*this, TypeAlignment)
1462 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001463
1464 IncompleteArrayTypes.InsertNode(New, InsertPos);
1465 Types.push_back(New);
1466 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001467}
1468
Steve Naroff73322922007-07-18 18:00:27 +00001469/// getVectorType - Return the unique reference to a vector type of
1470/// the specified element type and size. VectorType must be a built-in type.
1471QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Chris Lattnerf52ab252008-04-06 22:59:24 +00001474 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001475 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 // Check if we've already instantiated a vector of this type.
1478 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001479 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 void *InsertPos = 0;
1481 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1482 return QualType(VTP, 0);
1483
1484 // If the element type isn't canonical, this won't be a canonical type either,
1485 // so fill in the canonical type field.
1486 QualType Canonical;
1487 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001488 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // Get the new insert position for the node we care about.
1491 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001492 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 }
John McCall6b304a02009-09-24 23:30:46 +00001494 VectorType *New = new (*this, TypeAlignment)
1495 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 VectorTypes.InsertNode(New, InsertPos);
1497 Types.push_back(New);
1498 return QualType(New, 0);
1499}
1500
Nate Begeman213541a2008-04-18 23:10:10 +00001501/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001502/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001503QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001504 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattnerf52ab252008-04-06 22:59:24 +00001506 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001507 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Steve Naroff73322922007-07-18 18:00:27 +00001509 // Check if we've already instantiated a vector of this type.
1510 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001511 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001512 void *InsertPos = 0;
1513 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1514 return QualType(VTP, 0);
1515
1516 // If the element type isn't canonical, this won't be a canonical type either,
1517 // so fill in the canonical type field.
1518 QualType Canonical;
1519 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001520 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Steve Naroff73322922007-07-18 18:00:27 +00001522 // Get the new insert position for the node we care about.
1523 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001524 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001525 }
John McCall6b304a02009-09-24 23:30:46 +00001526 ExtVectorType *New = new (*this, TypeAlignment)
1527 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001528 VectorTypes.InsertNode(New, InsertPos);
1529 Types.push_back(New);
1530 return QualType(New, 0);
1531}
1532
Mike Stump1eb44332009-09-09 15:08:12 +00001533QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001534 Expr *SizeExpr,
1535 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001536 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001537 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001538 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001540 void *InsertPos = 0;
1541 DependentSizedExtVectorType *Canon
1542 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1543 DependentSizedExtVectorType *New;
1544 if (Canon) {
1545 // We already have a canonical version of this array type; use it as
1546 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001547 New = new (*this, TypeAlignment)
1548 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1549 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001550 } else {
1551 QualType CanonVecTy = getCanonicalType(vecType);
1552 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001553 New = new (*this, TypeAlignment)
1554 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1555 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001556 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1557 } else {
1558 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1559 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001560 New = new (*this, TypeAlignment)
1561 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001562 }
1563 }
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001565 Types.push_back(New);
1566 return QualType(New, 0);
1567}
1568
Douglas Gregor72564e72009-02-26 23:50:07 +00001569/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001570///
Mike Stump24556362009-07-25 21:26:53 +00001571QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // Unique functions, to guarantee there is only one function of a particular
1573 // structure.
1574 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001575 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001578 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001579 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 QualType Canonical;
1583 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001584 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001587 FunctionNoProtoType *NewIP =
1588 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001589 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 }
Mike Stump1eb44332009-09-09 15:08:12 +00001591
John McCall6b304a02009-09-24 23:30:46 +00001592 FunctionNoProtoType *New = new (*this, TypeAlignment)
1593 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001595 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 return QualType(New, 0);
1597}
1598
1599/// getFunctionType - Return a normal function type with a typed argument
1600/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001601QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001602 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001603 unsigned TypeQuals, bool hasExceptionSpec,
1604 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001605 const QualType *ExArray, bool NoReturn) {
Anders Carlsson83913e32009-09-16 23:47:08 +00001606 if (LangOpts.CPlusPlus) {
1607 for (unsigned i = 0; i != NumArgs; ++i)
John McCall0953e762009-09-24 19:53:00 +00001608 assert(!ArgArray[i].hasQualifiers() &&
1609 "C++ arguments can't have toplevel qualifiers!");
Anders Carlsson83913e32009-09-16 23:47:08 +00001610 }
1611
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 // Unique functions, to guarantee there is only one function of a particular
1613 // structure.
1614 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001615 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001616 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001617 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001618
1619 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001620 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001621 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001623
1624 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001626 if (hasExceptionSpec)
1627 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1629 if (!ArgArray[i]->isCanonical())
1630 isCanonical = false;
1631
1632 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001633 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 QualType Canonical;
1635 if (!isCanonical) {
1636 llvm::SmallVector<QualType, 16> CanonicalArgs;
1637 CanonicalArgs.reserve(NumArgs);
1638 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001639 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001640
Chris Lattnerf52ab252008-04-06 22:59:24 +00001641 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001642 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001643 isVariadic, TypeQuals, false,
1644 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001647 FunctionProtoType *NewIP =
1648 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001649 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001651
Douglas Gregor72564e72009-02-26 23:50:07 +00001652 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001653 // for two variable size arrays (for parameter and exception types) at the
1654 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001655 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001656 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1657 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001658 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001659 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001660 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001661 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001663 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 return QualType(FTP, 0);
1665}
1666
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001667/// getTypeDeclType - Return the unique reference to the type for the
1668/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001669QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001670 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001671 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001673 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001674 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001675 else if (isa<TemplateTypeParmDecl>(Decl)) {
1676 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001677 } else if (ObjCInterfaceDecl *ObjCInterface
1678 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001679 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001680
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001681 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001682 if (PrevDecl)
1683 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001684 else
John McCall6b304a02009-09-24 23:30:46 +00001685 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001686 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001687 if (PrevDecl)
1688 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001689 else
John McCall6b304a02009-09-24 23:30:46 +00001690 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001691 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001692 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001693
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001694 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001695 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001696}
1697
Reid Spencer5f016e22007-07-11 17:01:13 +00001698/// getTypedefType - Return the unique reference to the type for the
1699/// specified typename decl.
1700QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1701 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Chris Lattnerf52ab252008-04-06 22:59:24 +00001703 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001704 Decl->TypeForDecl = new(*this, TypeAlignment)
1705 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 Types.push_back(Decl->TypeForDecl);
1707 return QualType(Decl->TypeForDecl, 0);
1708}
1709
John McCall49a832b2009-10-18 09:09:24 +00001710/// \brief Retrieve a substitution-result type.
1711QualType
1712ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1713 QualType Replacement) {
1714 assert(Replacement->isCanonical()
1715 && "replacement types must always be canonical");
1716
1717 llvm::FoldingSetNodeID ID;
1718 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1719 void *InsertPos = 0;
1720 SubstTemplateTypeParmType *SubstParm
1721 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1722
1723 if (!SubstParm) {
1724 SubstParm = new (*this, TypeAlignment)
1725 SubstTemplateTypeParmType(Parm, Replacement);
1726 Types.push_back(SubstParm);
1727 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1728 }
1729
1730 return QualType(SubstParm, 0);
1731}
1732
Douglas Gregorfab9d672009-02-05 23:33:38 +00001733/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001734/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001735/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001736QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001737 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001738 IdentifierInfo *Name) {
1739 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001740 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001741 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001742 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001743 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1744
1745 if (TypeParm)
1746 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001748 if (Name) {
1749 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001750 TypeParm = new (*this, TypeAlignment)
1751 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001752 } else
John McCall6b304a02009-09-24 23:30:46 +00001753 TypeParm = new (*this, TypeAlignment)
1754 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001755
1756 Types.push_back(TypeParm);
1757 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1758
1759 return QualType(TypeParm, 0);
1760}
1761
Mike Stump1eb44332009-09-09 15:08:12 +00001762QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001763ASTContext::getTemplateSpecializationType(TemplateName Template,
1764 const TemplateArgument *Args,
1765 unsigned NumArgs,
1766 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001767 if (!Canon.isNull())
1768 Canon = getCanonicalType(Canon);
1769 else {
1770 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001771 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1772 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1773 CanonArgs.reserve(NumArgs);
1774 for (unsigned I = 0; I != NumArgs; ++I)
1775 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1776
1777 // Determine whether this canonical template specialization type already
1778 // exists.
1779 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001780 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001781 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001782
1783 void *InsertPos = 0;
1784 TemplateSpecializationType *Spec
1785 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor1275ae02009-07-28 23:00:59 +00001787 if (!Spec) {
1788 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001789 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001790 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001791 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001792 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001793 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001794 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001795 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001796 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001797 }
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Douglas Gregorb88e8882009-07-30 17:40:51 +00001799 if (Canon.isNull())
1800 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001801 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001802 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001803 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001804
Douglas Gregor1275ae02009-07-28 23:00:59 +00001805 // Allocate the (non-canonical) template specialization type, but don't
1806 // try to unique it: these types typically have location information that
1807 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001808 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001809 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001810 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001811 TemplateSpecializationType *Spec
1812 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001813 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregor55f6b142009-02-09 18:46:07 +00001815 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001816 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001817}
1818
Mike Stump1eb44332009-09-09 15:08:12 +00001819QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001820ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001821 QualType NamedType) {
1822 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001823 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001824
1825 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001826 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001827 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1828 if (T)
1829 return QualType(T, 0);
1830
Mike Stump1eb44332009-09-09 15:08:12 +00001831 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001832 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001833 Types.push_back(T);
1834 QualifiedNameTypes.InsertNode(T, InsertPos);
1835 return QualType(T, 0);
1836}
1837
Mike Stump1eb44332009-09-09 15:08:12 +00001838QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001839 const IdentifierInfo *Name,
1840 QualType Canon) {
1841 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1842
1843 if (Canon.isNull()) {
1844 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1845 if (CanonNNS != NNS)
1846 Canon = getTypenameType(CanonNNS, Name);
1847 }
1848
1849 llvm::FoldingSetNodeID ID;
1850 TypenameType::Profile(ID, NNS, Name);
1851
1852 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001853 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001854 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1855 if (T)
1856 return QualType(T, 0);
1857
1858 T = new (*this) TypenameType(NNS, Name, Canon);
1859 Types.push_back(T);
1860 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001861 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001862}
1863
Mike Stump1eb44332009-09-09 15:08:12 +00001864QualType
1865ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001866 const TemplateSpecializationType *TemplateId,
1867 QualType Canon) {
1868 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1869
1870 if (Canon.isNull()) {
1871 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1872 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1873 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1874 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001875 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001876 assert(CanonTemplateId &&
1877 "Canonical type must also be a template specialization type");
1878 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1879 }
1880 }
1881
1882 llvm::FoldingSetNodeID ID;
1883 TypenameType::Profile(ID, NNS, TemplateId);
1884
1885 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001886 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001887 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1888 if (T)
1889 return QualType(T, 0);
1890
1891 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1892 Types.push_back(T);
1893 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001894 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001895}
1896
John McCall7da24312009-09-05 00:15:47 +00001897QualType
1898ASTContext::getElaboratedType(QualType UnderlyingType,
1899 ElaboratedType::TagKind Tag) {
1900 llvm::FoldingSetNodeID ID;
1901 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001902
John McCall7da24312009-09-05 00:15:47 +00001903 void *InsertPos = 0;
1904 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1905 if (T)
1906 return QualType(T, 0);
1907
1908 QualType Canon = getCanonicalType(UnderlyingType);
1909
1910 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1911 Types.push_back(T);
1912 ElaboratedTypes.InsertNode(T, InsertPos);
1913 return QualType(T, 0);
1914}
1915
Chris Lattner88cb27a2008-04-07 04:56:42 +00001916/// CmpProtocolNames - Comparison predicate for sorting protocols
1917/// alphabetically.
1918static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1919 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001920 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001921}
1922
1923static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1924 unsigned &NumProtocols) {
1925 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Chris Lattner88cb27a2008-04-07 04:56:42 +00001927 // Sort protocols, keyed by name.
1928 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1929
1930 // Remove duplicates.
1931 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1932 NumProtocols = ProtocolsEnd-Protocols;
1933}
1934
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001935/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1936/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001937QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00001938 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001939 unsigned NumProtocols) {
1940 // Sort the protocol list alphabetically to canonicalize it.
1941 if (NumProtocols)
1942 SortAndUniqueProtocols(Protocols, NumProtocols);
1943
1944 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001945 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001946
1947 void *InsertPos = 0;
1948 if (ObjCObjectPointerType *QT =
1949 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1950 return QualType(QT, 0);
1951
1952 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00001953 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
1954 ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001956 Types.push_back(QType);
1957 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1958 return QualType(QType, 0);
1959}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001960
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001961/// getObjCInterfaceType - Return the unique reference to the type for the
1962/// specified ObjC interface decl. The list of protocols is optional.
1963QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001964 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Mike Stump1eb44332009-09-09 15:08:12 +00001965 if (NumProtocols)
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001966 // Sort the protocol list alphabetically to canonicalize it.
1967 SortAndUniqueProtocols(Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001969 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001970 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001972 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001973 if (ObjCInterfaceType *QT =
1974 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001975 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001977 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00001978 ObjCInterfaceType *QType = new (*this, TypeAlignment)
1979 ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1980 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001981 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001982 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001983 return QualType(QType, 0);
1984}
1985
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001986QualType ASTContext::getObjCProtocolListType(QualType T,
1987 ObjCProtocolDecl **Protocols,
1988 unsigned NumProtocols) {
1989 llvm::FoldingSetNodeID ID;
1990 ObjCProtocolListType::Profile(ID, T, Protocols, NumProtocols);
1991
1992 void *InsertPos = 0;
1993 if (ObjCProtocolListType *QT =
1994 ObjCProtocolListTypes.FindNodeOrInsertPos(ID, InsertPos))
1995 return QualType(QT, 0);
1996
1997 // No Match;
1998 ObjCProtocolListType *QType = new (*this, TypeAlignment)
1999 ObjCProtocolListType(T, Protocols, NumProtocols);
2000 Types.push_back(QType);
2001 ObjCProtocolListTypes.InsertNode(QType, InsertPos);
2002 return QualType(QType, 0);
2003}
2004
Douglas Gregor72564e72009-02-26 23:50:07 +00002005/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2006/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002007/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002008/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002009/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002010QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002011 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002012 if (tofExpr->isTypeDependent()) {
2013 llvm::FoldingSetNodeID ID;
2014 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Douglas Gregorb1975722009-07-30 23:18:24 +00002016 void *InsertPos = 0;
2017 DependentTypeOfExprType *Canon
2018 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2019 if (Canon) {
2020 // We already have a "canonical" version of an identical, dependent
2021 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002022 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002023 QualType((TypeOfExprType*)Canon, 0));
2024 }
2025 else {
2026 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002027 Canon
2028 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002029 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2030 toe = Canon;
2031 }
2032 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002033 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002034 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002035 }
Steve Naroff9752f252007-08-01 18:02:17 +00002036 Types.push_back(toe);
2037 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002038}
2039
Steve Naroff9752f252007-08-01 18:02:17 +00002040/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2041/// TypeOfType AST's. The only motivation to unique these nodes would be
2042/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002043/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002044/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002045QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002046 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002047 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002048 Types.push_back(tot);
2049 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002050}
2051
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002052/// getDecltypeForExpr - Given an expr, will return the decltype for that
2053/// expression, according to the rules in C++0x [dcl.type.simple]p4
2054static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002055 if (e->isTypeDependent())
2056 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002058 // If e is an id expression or a class member access, decltype(e) is defined
2059 // as the type of the entity named by e.
2060 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2061 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2062 return VD->getType();
2063 }
2064 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2065 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2066 return FD->getType();
2067 }
2068 // If e is a function call or an invocation of an overloaded operator,
2069 // (parentheses around e are ignored), decltype(e) is defined as the
2070 // return type of that function.
2071 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2072 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002074 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002075
2076 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002077 // defined as T&, otherwise decltype(e) is defined as T.
2078 if (e->isLvalue(Context) == Expr::LV_Valid)
2079 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002081 return T;
2082}
2083
Anders Carlsson395b4752009-06-24 19:06:50 +00002084/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2085/// DecltypeType AST's. The only motivation to unique these nodes would be
2086/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002087/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002088/// on canonical type's (which are always unique).
2089QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002090 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002091 if (e->isTypeDependent()) {
2092 llvm::FoldingSetNodeID ID;
2093 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002095 void *InsertPos = 0;
2096 DependentDecltypeType *Canon
2097 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2098 if (Canon) {
2099 // We already have a "canonical" version of an equivalent, dependent
2100 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002101 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002102 QualType((DecltypeType*)Canon, 0));
2103 }
2104 else {
2105 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002106 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002107 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2108 dt = Canon;
2109 }
2110 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002111 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002112 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002113 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002114 Types.push_back(dt);
2115 return QualType(dt, 0);
2116}
2117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118/// getTagDeclType - Return the unique reference to the type for the
2119/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002120QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002121 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002122 // FIXME: What is the design on getTagDeclType when it requires casting
2123 // away const? mutable?
2124 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002125}
2126
Mike Stump1eb44332009-09-09 15:08:12 +00002127/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2128/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2129/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002130QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002131 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002132}
2133
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002134/// getSignedWCharType - Return the type of "signed wchar_t".
2135/// Used when in C++, as a GCC extension.
2136QualType ASTContext::getSignedWCharType() const {
2137 // FIXME: derive from "Target" ?
2138 return WCharTy;
2139}
2140
2141/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2142/// Used when in C++, as a GCC extension.
2143QualType ASTContext::getUnsignedWCharType() const {
2144 // FIXME: derive from "Target" ?
2145 return UnsignedIntTy;
2146}
2147
Chris Lattner8b9023b2007-07-13 03:05:23 +00002148/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2149/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2150QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002151 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002152}
2153
Chris Lattnere6327742008-04-02 05:18:44 +00002154//===----------------------------------------------------------------------===//
2155// Type Operators
2156//===----------------------------------------------------------------------===//
2157
Chris Lattner77c96472008-04-06 22:41:35 +00002158/// getCanonicalType - Return the canonical (structural) type corresponding to
2159/// the specified potentially non-canonical type. The non-canonical version
2160/// of a type may have many "decorated" versions of types. Decorators can
2161/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2162/// to be free of any of these, allowing two canonical types to be compared
2163/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002164CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002165 QualifierCollector Quals;
2166 const Type *Ptr = Quals.strip(T);
2167 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002168
John McCall0953e762009-09-24 19:53:00 +00002169 // The canonical internal type will be the canonical type *except*
2170 // that we push type qualifiers down through array types.
2171
2172 // If there are no new qualifiers to push down, stop here.
2173 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002174 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002175
John McCall0953e762009-09-24 19:53:00 +00002176 // If the type qualifiers are on an array type, get the canonical
2177 // type of the array with the qualifiers applied to the element
2178 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002179 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2180 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002181 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002183 // Get the canonical version of the element with the extra qualifiers on it.
2184 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002185 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002186 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002188 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002189 return CanQualType::CreateUnsafe(
2190 getConstantArrayType(NewEltTy, CAT->getSize(),
2191 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002192 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002193 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002194 return CanQualType::CreateUnsafe(
2195 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002196 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Douglas Gregor898574e2008-12-05 23:32:09 +00002198 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002199 return CanQualType::CreateUnsafe(
2200 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002201 DSAT->getSizeExpr() ?
2202 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002203 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002204 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002205 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002206
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002207 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002208 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002209 VAT->getSizeExpr() ?
2210 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002211 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002212 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002213 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002214}
2215
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002216TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2217 // If this template name refers to a template, the canonical
2218 // template name merely stores the template itself.
2219 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002220 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002221
Mike Stump1eb44332009-09-09 15:08:12 +00002222 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002223 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002224 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2225 OverloadedFunctionDecl *CanonOvl = 0;
2226 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2227 FEnd = Ovl->function_end();
2228 F != FEnd; ++F) {
2229 Decl *Canon = F->get()->getCanonicalDecl();
2230 if (CanonOvl || Canon != F->get()) {
2231 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002232 CanonOvl = OverloadedFunctionDecl::Create(*this,
2233 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002234 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002236 CanonOvl->addOverload(
2237 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2238 }
2239 }
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002241 return TemplateName(CanonOvl? CanonOvl : Ovl);
2242 }
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002244 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2245 assert(DTN && "Non-dependent template names must refer to template decls.");
2246 return DTN->CanonicalTemplateName;
2247}
2248
Mike Stump1eb44332009-09-09 15:08:12 +00002249TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002250ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2251 switch (Arg.getKind()) {
2252 case TemplateArgument::Null:
2253 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregor1275ae02009-07-28 23:00:59 +00002255 case TemplateArgument::Expression:
2256 // FIXME: Build canonical expression?
2257 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Douglas Gregor1275ae02009-07-28 23:00:59 +00002259 case TemplateArgument::Declaration:
2260 return TemplateArgument(SourceLocation(),
2261 Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Douglas Gregor1275ae02009-07-28 23:00:59 +00002263 case TemplateArgument::Integral:
2264 return TemplateArgument(SourceLocation(),
2265 *Arg.getAsIntegral(),
2266 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Douglas Gregor1275ae02009-07-28 23:00:59 +00002268 case TemplateArgument::Type:
2269 return TemplateArgument(SourceLocation(),
2270 getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Douglas Gregor1275ae02009-07-28 23:00:59 +00002272 case TemplateArgument::Pack: {
2273 // FIXME: Allocate in ASTContext
2274 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2275 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002276 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002277 AEnd = Arg.pack_end();
2278 A != AEnd; (void)++A, ++Idx)
2279 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Douglas Gregor1275ae02009-07-28 23:00:59 +00002281 TemplateArgument Result;
2282 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2283 return Result;
2284 }
2285 }
2286
2287 // Silence GCC warning
2288 assert(false && "Unhandled template argument kind");
2289 return TemplateArgument();
2290}
2291
Douglas Gregord57959a2009-03-27 23:10:48 +00002292NestedNameSpecifier *
2293ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002294 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002295 return 0;
2296
2297 switch (NNS->getKind()) {
2298 case NestedNameSpecifier::Identifier:
2299 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002300 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002301 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2302 NNS->getAsIdentifier());
2303
2304 case NestedNameSpecifier::Namespace:
2305 // A namespace is canonical; build a nested-name-specifier with
2306 // this namespace and no prefix.
2307 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2308
2309 case NestedNameSpecifier::TypeSpec:
2310 case NestedNameSpecifier::TypeSpecWithTemplate: {
2311 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002312 return NestedNameSpecifier::Create(*this, 0,
2313 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002314 T.getTypePtr());
2315 }
2316
2317 case NestedNameSpecifier::Global:
2318 // The global specifier is canonical and unique.
2319 return NNS;
2320 }
2321
2322 // Required to silence a GCC warning
2323 return 0;
2324}
2325
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002326
2327const ArrayType *ASTContext::getAsArrayType(QualType T) {
2328 // Handle the non-qualified case efficiently.
John McCall0953e762009-09-24 19:53:00 +00002329 if (!T.hasQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002330 // Handle the common positive case fast.
2331 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2332 return AT;
2333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
John McCall0953e762009-09-24 19:53:00 +00002335 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002336 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002337 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002338 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
John McCall0953e762009-09-24 19:53:00 +00002340 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002341 // implements C99 6.7.3p8: "If the specification of an array type includes
2342 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002344 // If we get here, we either have type qualifiers on the type, or we have
2345 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002346 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002347
John McCall0953e762009-09-24 19:53:00 +00002348 QualifierCollector Qs;
2349 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002351 // If we have a simple case, just return now.
2352 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002353 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002354 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002356 // Otherwise, we have an array and we have qualifiers on it. Push the
2357 // qualifiers into the array element type and return a new array type.
2358 // Get the canonical version of the element with the extra qualifiers on it.
2359 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002360 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002362 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2363 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2364 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002365 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002366 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2367 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2368 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002369 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002370
Mike Stump1eb44332009-09-09 15:08:12 +00002371 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002372 = dyn_cast<DependentSizedArrayType>(ATy))
2373 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002374 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002375 DSAT->getSizeExpr() ?
2376 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002377 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002378 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002379 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002381 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002382 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002383 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002384 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002385 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002386 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002387 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002388}
2389
2390
Chris Lattnere6327742008-04-02 05:18:44 +00002391/// getArrayDecayedType - Return the properly qualified result of decaying the
2392/// specified array type to a pointer. This operation is non-trivial when
2393/// handling typedefs etc. The canonical type of "T" must be an array type,
2394/// this returns a pointer to a properly qualified element of the array.
2395///
2396/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2397QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002398 // Get the element type with 'getAsArrayType' so that we don't lose any
2399 // typedefs in the element type of the array. This also handles propagation
2400 // of type qualifiers from the array type into the element type if present
2401 // (C99 6.7.3p8).
2402 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2403 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002405 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002406
2407 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002408 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002409}
2410
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002411QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002412 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002413 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002414 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002415 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2416 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002417 } else {
John McCall0953e762009-09-24 19:53:00 +00002418 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002419 }
2420 }
2421}
2422
Anders Carlssonfbbce492009-09-25 01:23:32 +00002423QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2424 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Anders Carlssonfbbce492009-09-25 01:23:32 +00002426 if (const ArrayType *AT = getAsArrayType(ElemTy))
2427 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Anders Carlsson6183a992008-12-21 03:44:36 +00002429 return ElemTy;
2430}
2431
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002432/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002433uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002434ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2435 uint64_t ElementCount = 1;
2436 do {
2437 ElementCount *= CA->getSize().getZExtValue();
2438 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2439 } while (CA);
2440 return ElementCount;
2441}
2442
Reid Spencer5f016e22007-07-11 17:01:13 +00002443/// getFloatingRank - Return a relative rank for floating point types.
2444/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002445static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002446 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002448
John McCall183700f2009-09-21 23:43:11 +00002449 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2450 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002451 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002452 case BuiltinType::Float: return FloatRank;
2453 case BuiltinType::Double: return DoubleRank;
2454 case BuiltinType::LongDouble: return LongDoubleRank;
2455 }
2456}
2457
Mike Stump1eb44332009-09-09 15:08:12 +00002458/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2459/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002460/// 'typeDomain' is a real floating point or complex type.
2461/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002462QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2463 QualType Domain) const {
2464 FloatingRank EltRank = getFloatingRank(Size);
2465 if (Domain->isComplexType()) {
2466 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002467 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002468 case FloatRank: return FloatComplexTy;
2469 case DoubleRank: return DoubleComplexTy;
2470 case LongDoubleRank: return LongDoubleComplexTy;
2471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 }
Chris Lattner1361b112008-04-06 23:58:54 +00002473
2474 assert(Domain->isRealFloatingType() && "Unknown domain!");
2475 switch (EltRank) {
2476 default: assert(0 && "getFloatingRank(): illegal value for rank");
2477 case FloatRank: return FloatTy;
2478 case DoubleRank: return DoubleTy;
2479 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002480 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002481}
2482
Chris Lattner7cfeb082008-04-06 23:55:33 +00002483/// getFloatingTypeOrder - Compare the rank of the two specified floating
2484/// point types, ignoring the domain of the type (i.e. 'double' ==
2485/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002486/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002487int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2488 FloatingRank LHSR = getFloatingRank(LHS);
2489 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Chris Lattnera75cea32008-04-06 23:38:49 +00002491 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002492 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002493 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002494 return 1;
2495 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002496}
2497
Chris Lattnerf52ab252008-04-06 22:59:24 +00002498/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2499/// routine will assert if passed a built-in type that isn't an integer or enum,
2500/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002501unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002502 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002503 if (EnumType* ET = dyn_cast<EnumType>(T))
2504 T = ET->getDecl()->getIntegerType().getTypePtr();
2505
Eli Friedmana3426752009-07-05 23:44:27 +00002506 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2507 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2508
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002509 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2510 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2511
2512 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2513 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2514
Eli Friedmanf98aba32009-02-13 02:31:07 +00002515 // There are two things which impact the integer rank: the width, and
2516 // the ordering of builtins. The builtin ordering is encoded in the
2517 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002518 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002519 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002520
Chris Lattnerf52ab252008-04-06 22:59:24 +00002521 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002522 default: assert(0 && "getIntegerRank(): not a built-in integer");
2523 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002524 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002525 case BuiltinType::Char_S:
2526 case BuiltinType::Char_U:
2527 case BuiltinType::SChar:
2528 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002529 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002530 case BuiltinType::Short:
2531 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002532 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002533 case BuiltinType::Int:
2534 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002535 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002536 case BuiltinType::Long:
2537 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002538 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002539 case BuiltinType::LongLong:
2540 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002541 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002542 case BuiltinType::Int128:
2543 case BuiltinType::UInt128:
2544 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002545 }
2546}
2547
Eli Friedman04e83572009-08-20 04:21:42 +00002548/// \brief Whether this is a promotable bitfield reference according
2549/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2550///
2551/// \returns the type this bit-field will promote to, or NULL if no
2552/// promotion occurs.
2553QualType ASTContext::isPromotableBitField(Expr *E) {
2554 FieldDecl *Field = E->getBitField();
2555 if (!Field)
2556 return QualType();
2557
2558 QualType FT = Field->getType();
2559
2560 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2561 uint64_t BitWidth = BitWidthAP.getZExtValue();
2562 uint64_t IntSize = getTypeSize(IntTy);
2563 // GCC extension compatibility: if the bit-field size is less than or equal
2564 // to the size of int, it gets promoted no matter what its type is.
2565 // For instance, unsigned long bf : 4 gets promoted to signed int.
2566 if (BitWidth < IntSize)
2567 return IntTy;
2568
2569 if (BitWidth == IntSize)
2570 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2571
2572 // Types bigger than int are not subject to promotions, and therefore act
2573 // like the base type.
2574 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2575 // is ridiculous.
2576 return QualType();
2577}
2578
Eli Friedmana95d7572009-08-19 07:44:53 +00002579/// getPromotedIntegerType - Returns the type that Promotable will
2580/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2581/// integer type.
2582QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2583 assert(!Promotable.isNull());
2584 assert(Promotable->isPromotableIntegerType());
2585 if (Promotable->isSignedIntegerType())
2586 return IntTy;
2587 uint64_t PromotableSize = getTypeSize(Promotable);
2588 uint64_t IntSize = getTypeSize(IntTy);
2589 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2590 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2591}
2592
Mike Stump1eb44332009-09-09 15:08:12 +00002593/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002594/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002595/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002596int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002597 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2598 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002599 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002600
Chris Lattnerf52ab252008-04-06 22:59:24 +00002601 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2602 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Chris Lattner7cfeb082008-04-06 23:55:33 +00002604 unsigned LHSRank = getIntegerRank(LHSC);
2605 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Chris Lattner7cfeb082008-04-06 23:55:33 +00002607 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2608 if (LHSRank == RHSRank) return 0;
2609 return LHSRank > RHSRank ? 1 : -1;
2610 }
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Chris Lattner7cfeb082008-04-06 23:55:33 +00002612 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2613 if (LHSUnsigned) {
2614 // If the unsigned [LHS] type is larger, return it.
2615 if (LHSRank >= RHSRank)
2616 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Chris Lattner7cfeb082008-04-06 23:55:33 +00002618 // If the signed type can represent all values of the unsigned type, it
2619 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002620 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002621 return -1;
2622 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002623
Chris Lattner7cfeb082008-04-06 23:55:33 +00002624 // If the unsigned [RHS] type is larger, return it.
2625 if (RHSRank >= LHSRank)
2626 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Chris Lattner7cfeb082008-04-06 23:55:33 +00002628 // If the signed type can represent all values of the unsigned type, it
2629 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002630 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002631 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002632}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002633
Mike Stump1eb44332009-09-09 15:08:12 +00002634// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002635QualType ASTContext::getCFConstantStringType() {
2636 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002637 CFConstantStringTypeDecl =
2638 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002639 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002640 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Anders Carlsson71993dd2007-08-17 05:31:46 +00002642 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002643 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002644 // int flags;
2645 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002646 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002647 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002648 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002649 FieldTypes[3] = LongTy;
2650
Anders Carlsson71993dd2007-08-17 05:31:46 +00002651 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002652 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002653 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002654 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002655 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002656 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002657 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002658 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002659 }
2660
2661 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002662 }
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Anders Carlsson71993dd2007-08-17 05:31:46 +00002664 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002665}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002666
Douglas Gregor319ac892009-04-23 22:29:11 +00002667void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002668 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002669 assert(Rec && "Invalid CFConstantStringType");
2670 CFConstantStringTypeDecl = Rec->getDecl();
2671}
2672
Mike Stump1eb44332009-09-09 15:08:12 +00002673QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002674 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002675 ObjCFastEnumerationStateTypeDecl =
2676 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2677 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002679 QualType FieldTypes[] = {
2680 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002681 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002682 getPointerType(UnsignedLongTy),
2683 getConstantArrayType(UnsignedLongTy,
2684 llvm::APInt(32, 5), ArrayType::Normal, 0)
2685 };
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Douglas Gregor44b43212008-12-11 16:49:14 +00002687 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002688 FieldDecl *Field = FieldDecl::Create(*this,
2689 ObjCFastEnumerationStateTypeDecl,
2690 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002691 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002692 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002693 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002694 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002695 }
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Douglas Gregor44b43212008-12-11 16:49:14 +00002697 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002698 }
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002700 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2701}
2702
Mike Stumpadaaad32009-10-20 02:12:22 +00002703QualType ASTContext::getBlockDescriptorType() {
2704 if (BlockDescriptorType)
2705 return getTagDeclType(BlockDescriptorType);
2706
2707 RecordDecl *T;
2708 // FIXME: Needs the FlagAppleBlock bit.
2709 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2710 &Idents.get("__block_descriptor"));
2711
2712 QualType FieldTypes[] = {
2713 UnsignedLongTy,
2714 UnsignedLongTy,
2715 };
2716
2717 const char *FieldNames[] = {
2718 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002719 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002720 };
2721
2722 for (size_t i = 0; i < 2; ++i) {
2723 FieldDecl *Field = FieldDecl::Create(*this,
2724 T,
2725 SourceLocation(),
2726 &Idents.get(FieldNames[i]),
2727 FieldTypes[i], /*DInfo=*/0,
2728 /*BitWidth=*/0,
2729 /*Mutable=*/false);
2730 T->addDecl(Field);
2731 }
2732
2733 T->completeDefinition(*this);
2734
2735 BlockDescriptorType = T;
2736
2737 return getTagDeclType(BlockDescriptorType);
2738}
2739
2740void ASTContext::setBlockDescriptorType(QualType T) {
2741 const RecordType *Rec = T->getAs<RecordType>();
2742 assert(Rec && "Invalid BlockDescriptorType");
2743 BlockDescriptorType = Rec->getDecl();
2744}
2745
Mike Stump083c25e2009-10-22 00:49:09 +00002746QualType ASTContext::getBlockDescriptorExtendedType() {
2747 if (BlockDescriptorExtendedType)
2748 return getTagDeclType(BlockDescriptorExtendedType);
2749
2750 RecordDecl *T;
2751 // FIXME: Needs the FlagAppleBlock bit.
2752 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2753 &Idents.get("__block_descriptor_withcopydispose"));
2754
2755 QualType FieldTypes[] = {
2756 UnsignedLongTy,
2757 UnsignedLongTy,
2758 getPointerType(VoidPtrTy),
2759 getPointerType(VoidPtrTy)
2760 };
2761
2762 const char *FieldNames[] = {
2763 "reserved",
2764 "Size",
2765 "CopyFuncPtr",
2766 "DestroyFuncPtr"
2767 };
2768
2769 for (size_t i = 0; i < 4; ++i) {
2770 FieldDecl *Field = FieldDecl::Create(*this,
2771 T,
2772 SourceLocation(),
2773 &Idents.get(FieldNames[i]),
2774 FieldTypes[i], /*DInfo=*/0,
2775 /*BitWidth=*/0,
2776 /*Mutable=*/false);
2777 T->addDecl(Field);
2778 }
2779
2780 T->completeDefinition(*this);
2781
2782 BlockDescriptorExtendedType = T;
2783
2784 return getTagDeclType(BlockDescriptorExtendedType);
2785}
2786
2787void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2788 const RecordType *Rec = T->getAs<RecordType>();
2789 assert(Rec && "Invalid BlockDescriptorType");
2790 BlockDescriptorExtendedType = Rec->getDecl();
2791}
2792
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002793bool ASTContext::BlockRequiresCopying(QualType Ty) {
2794 if (Ty->isBlockPointerType())
2795 return true;
2796 if (isObjCNSObjectType(Ty))
2797 return true;
2798 if (Ty->isObjCObjectPointerType())
2799 return true;
2800 return false;
2801}
2802
2803QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2804 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002805 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002806 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002807 // unsigned int __flags;
2808 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002809 // void *__copy_helper; // as needed
2810 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002811 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002812 // } *
2813
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002814 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2815
2816 // FIXME: Move up
2817 static int UniqueBlockByRefTypeID = 0;
2818 char Name[36];
2819 sprintf(Name, "__Block_byref_%d_%s", ++UniqueBlockByRefTypeID, DeclName);
2820 RecordDecl *T;
2821 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2822 &Idents.get(Name));
2823 T->startDefinition();
2824 QualType Int32Ty = IntTy;
2825 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2826 QualType FieldTypes[] = {
2827 getPointerType(VoidPtrTy),
2828 getPointerType(getTagDeclType(T)),
2829 Int32Ty,
2830 Int32Ty,
2831 getPointerType(VoidPtrTy),
2832 getPointerType(VoidPtrTy),
2833 Ty
2834 };
2835
2836 const char *FieldNames[] = {
2837 "__isa",
2838 "__forwarding",
2839 "__flags",
2840 "__size",
2841 "__copy_helper",
2842 "__destroy_helper",
2843 DeclName,
2844 };
2845
2846 for (size_t i = 0; i < 7; ++i) {
2847 if (!HasCopyAndDispose && i >=4 && i <= 5)
2848 continue;
2849 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2850 &Idents.get(FieldNames[i]),
2851 FieldTypes[i], /*DInfo=*/0,
2852 /*BitWidth=*/0, /*Mutable=*/false);
2853 T->addDecl(Field);
2854 }
2855
2856 T->completeDefinition(*this);
2857
2858 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002859}
2860
2861
2862QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002863 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002864 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002865 // FIXME: Move up
2866 static int UniqueBlockParmTypeID = 0;
2867 char Name[36];
2868 sprintf(Name, "__block_literal_%u", ++UniqueBlockParmTypeID);
2869 RecordDecl *T;
2870 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2871 &Idents.get(Name));
Mike Stumpadaaad32009-10-20 02:12:22 +00002872 QualType FieldTypes[] = {
2873 getPointerType(VoidPtrTy),
2874 IntTy,
2875 IntTy,
2876 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00002877 (BlockHasCopyDispose ?
2878 getPointerType(getBlockDescriptorExtendedType()) :
2879 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00002880 };
2881
2882 const char *FieldNames[] = {
2883 "__isa",
2884 "__flags",
2885 "__reserved",
2886 "__FuncPtr",
2887 "__descriptor"
2888 };
2889
2890 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00002891 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00002892 &Idents.get(FieldNames[i]),
2893 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00002894 /*BitWidth=*/0, /*Mutable=*/false);
2895 T->addDecl(Field);
2896 }
2897
2898 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
2899 const Expr *E = BlockDeclRefDecls[i];
2900 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2901 clang::IdentifierInfo *Name = 0;
2902 if (BDRE) {
2903 const ValueDecl *D = BDRE->getDecl();
2904 Name = &Idents.get(D->getName());
2905 }
2906 QualType FieldType = E->getType();
2907
2908 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002909 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
2910 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00002911
2912 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2913 Name, FieldType, /*DInfo=*/0,
2914 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00002915 T->addDecl(Field);
2916 }
2917
2918 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00002919
2920 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00002921}
2922
Douglas Gregor319ac892009-04-23 22:29:11 +00002923void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002924 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002925 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2926 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2927}
2928
Anders Carlssone8c49532007-10-29 06:33:42 +00002929// This returns true if a type has been typedefed to BOOL:
2930// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002931static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002932 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002933 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2934 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002936 return false;
2937}
2938
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002939/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002940/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002941int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002942 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002944 // Make all integer and enum types at least as large as an int
2945 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002946 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002947 // Treat arrays as pointers, since that's how they're passed in.
2948 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002949 sz = getTypeSize(VoidPtrTy);
2950 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002951}
2952
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002953/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002954/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002955void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002956 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002957 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002958 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002959 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002960 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002961 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002962 // Compute size of all parameters.
2963 // Start with computing size of a pointer in number of bytes.
2964 // FIXME: There might(should) be a better way of doing this computation!
2965 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002966 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002967 // The first two arguments (self and _cmd) are pointers; account for
2968 // their size.
2969 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002970 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2971 E = Decl->param_end(); PI != E; ++PI) {
2972 QualType PType = (*PI)->getType();
2973 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002974 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002975 ParmOffset += sz;
2976 }
2977 S += llvm::utostr(ParmOffset);
2978 S += "@0:";
2979 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002981 // Argument types.
2982 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002983 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2984 E = Decl->param_end(); PI != E; ++PI) {
2985 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00002986 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002987 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002988 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2989 // Use array's original type only if it has known number of
2990 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002991 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002992 PType = PVDecl->getType();
2993 } else if (PType->isFunctionType())
2994 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002995 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002996 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002997 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002998 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002999 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003001 }
3002}
3003
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003004/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003005/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003006/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3007/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003008/// Property attributes are stored as a comma-delimited C string. The simple
3009/// attributes readonly and bycopy are encoded as single characters. The
3010/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3011/// encoded as single characters, followed by an identifier. Property types
3012/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003013/// these attributes are defined by the following enumeration:
3014/// @code
3015/// enum PropertyAttributes {
3016/// kPropertyReadOnly = 'R', // property is read-only.
3017/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3018/// kPropertyByref = '&', // property is a reference to the value last assigned
3019/// kPropertyDynamic = 'D', // property is dynamic
3020/// kPropertyGetter = 'G', // followed by getter selector name
3021/// kPropertySetter = 'S', // followed by setter selector name
3022/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3023/// kPropertyType = 't' // followed by old-style type encoding.
3024/// kPropertyWeak = 'W' // 'weak' property
3025/// kPropertyStrong = 'P' // property GC'able
3026/// kPropertyNonAtomic = 'N' // property non-atomic
3027/// };
3028/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003029void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003030 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003031 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003032 // Collect information from the property implementation decl(s).
3033 bool Dynamic = false;
3034 ObjCPropertyImplDecl *SynthesizePID = 0;
3035
3036 // FIXME: Duplicated code due to poor abstraction.
3037 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003038 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003039 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3040 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003041 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003042 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003043 ObjCPropertyImplDecl *PID = *i;
3044 if (PID->getPropertyDecl() == PD) {
3045 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3046 Dynamic = true;
3047 } else {
3048 SynthesizePID = PID;
3049 }
3050 }
3051 }
3052 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003053 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003054 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003055 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003056 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003057 ObjCPropertyImplDecl *PID = *i;
3058 if (PID->getPropertyDecl() == PD) {
3059 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3060 Dynamic = true;
3061 } else {
3062 SynthesizePID = PID;
3063 }
3064 }
Mike Stump1eb44332009-09-09 15:08:12 +00003065 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003066 }
3067 }
3068
3069 // FIXME: This is not very efficient.
3070 S = "T";
3071
3072 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003073 // GCC has some special rules regarding encoding of properties which
3074 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003075 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003076 true /* outermost type */,
3077 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003078
3079 if (PD->isReadOnly()) {
3080 S += ",R";
3081 } else {
3082 switch (PD->getSetterKind()) {
3083 case ObjCPropertyDecl::Assign: break;
3084 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003085 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003086 }
3087 }
3088
3089 // It really isn't clear at all what this means, since properties
3090 // are "dynamic by default".
3091 if (Dynamic)
3092 S += ",D";
3093
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003094 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3095 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003096
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003097 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3098 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003099 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003100 }
3101
3102 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3103 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003104 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003105 }
3106
3107 if (SynthesizePID) {
3108 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3109 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003110 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003111 }
3112
3113 // FIXME: OBJCGC: weak & strong
3114}
3115
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003116/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003117/// Another legacy compatibility encoding: 32-bit longs are encoded as
3118/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003119/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3120///
3121void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003122 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003123 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003124 if (BT->getKind() == BuiltinType::ULong &&
3125 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003126 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003127 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003128 if (BT->getKind() == BuiltinType::Long &&
3129 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003130 PointeeTy = IntTy;
3131 }
3132 }
3133}
3134
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003135void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003136 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003137 // We follow the behavior of gcc, expanding structures which are
3138 // directly pointed to, and expanding embedded structures. Note that
3139 // these rules are sufficient to prevent recursive encoding of the
3140 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003141 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003142 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003143}
3144
Mike Stump1eb44332009-09-09 15:08:12 +00003145static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003146 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003147 const Expr *E = FD->getBitWidth();
3148 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3149 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003150 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003151 S += 'b';
3152 S += llvm::utostr(N);
3153}
3154
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003155// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003156void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3157 bool ExpandPointedToStructures,
3158 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003159 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003160 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003161 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003162 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003163 if (FD && FD->isBitField())
3164 return EncodeBitField(this, S, FD);
3165 char encoding;
3166 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003167 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003168 case BuiltinType::Void: encoding = 'v'; break;
3169 case BuiltinType::Bool: encoding = 'B'; break;
3170 case BuiltinType::Char_U:
3171 case BuiltinType::UChar: encoding = 'C'; break;
3172 case BuiltinType::UShort: encoding = 'S'; break;
3173 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003174 case BuiltinType::ULong:
3175 encoding =
3176 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003177 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003178 case BuiltinType::UInt128: encoding = 'T'; break;
3179 case BuiltinType::ULongLong: encoding = 'Q'; break;
3180 case BuiltinType::Char_S:
3181 case BuiltinType::SChar: encoding = 'c'; break;
3182 case BuiltinType::Short: encoding = 's'; break;
3183 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003184 case BuiltinType::Long:
3185 encoding =
3186 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003187 break;
3188 case BuiltinType::LongLong: encoding = 'q'; break;
3189 case BuiltinType::Int128: encoding = 't'; break;
3190 case BuiltinType::Float: encoding = 'f'; break;
3191 case BuiltinType::Double: encoding = 'd'; break;
3192 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003193 }
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003195 S += encoding;
3196 return;
3197 }
Mike Stump1eb44332009-09-09 15:08:12 +00003198
John McCall183700f2009-09-21 23:43:11 +00003199 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003200 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003201 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003202 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003203 return;
3204 }
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Ted Kremenek6217b802009-07-29 21:53:49 +00003206 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003207 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003208 bool isReadOnly = false;
3209 // For historical/compatibility reasons, the read-only qualifier of the
3210 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3211 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003212 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003213 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003214 if (OutermostType && T.isConstQualified()) {
3215 isReadOnly = true;
3216 S += 'r';
3217 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003218 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003219 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003220 while (P->getAs<PointerType>())
3221 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003222 if (P.isConstQualified()) {
3223 isReadOnly = true;
3224 S += 'r';
3225 }
3226 }
3227 if (isReadOnly) {
3228 // Another legacy compatibility encoding. Some ObjC qualifier and type
3229 // combinations need to be rearranged.
3230 // Rewrite "in const" from "nr" to "rn"
3231 const char * s = S.c_str();
3232 int len = S.length();
3233 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3234 std::string replace = "rn";
3235 S.replace(S.end()-2, S.end(), replace);
3236 }
3237 }
Steve Naroff14108da2009-07-10 23:34:53 +00003238 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003239 S += ':';
3240 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003241 }
Mike Stump1eb44332009-09-09 15:08:12 +00003242
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003243 if (PointeeTy->isCharType()) {
3244 // char pointer types should be encoded as '*' unless it is a
3245 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003246 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003247 S += '*';
3248 return;
3249 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003250 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003251 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3252 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3253 S += '#';
3254 return;
3255 }
3256 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3257 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3258 S += '@';
3259 return;
3260 }
3261 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003262 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003263 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003264 getLegacyIntegralTypeEncoding(PointeeTy);
3265
Mike Stump1eb44332009-09-09 15:08:12 +00003266 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003267 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003268 return;
3269 }
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003271 if (const ArrayType *AT =
3272 // Ignore type qualifiers etc.
3273 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003274 if (isa<IncompleteArrayType>(AT)) {
3275 // Incomplete arrays are encoded as a pointer to the array element.
3276 S += '^';
3277
Mike Stump1eb44332009-09-09 15:08:12 +00003278 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003279 false, ExpandStructures, FD);
3280 } else {
3281 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Anders Carlsson559a8332009-02-22 01:38:57 +00003283 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3284 S += llvm::utostr(CAT->getSize().getZExtValue());
3285 else {
3286 //Variable length arrays are encoded as a regular array with 0 elements.
3287 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3288 S += '0';
3289 }
Mike Stump1eb44332009-09-09 15:08:12 +00003290
3291 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003292 false, ExpandStructures, FD);
3293 S += ']';
3294 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003295 return;
3296 }
Mike Stump1eb44332009-09-09 15:08:12 +00003297
John McCall183700f2009-09-21 23:43:11 +00003298 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003299 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003300 return;
3301 }
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Ted Kremenek6217b802009-07-29 21:53:49 +00003303 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003304 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003305 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003306 // Anonymous structures print as '?'
3307 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3308 S += II->getName();
3309 } else {
3310 S += '?';
3311 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003312 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003313 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003314 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3315 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003316 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003317 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003318 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003319 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003320 S += '"';
3321 }
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003323 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003324 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003325 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003326 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003327 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003328 QualType qt = Field->getType();
3329 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003330 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003331 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003332 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003333 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003334 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003335 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003336 return;
3337 }
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003339 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003340 if (FD && FD->isBitField())
3341 EncodeBitField(this, S, FD);
3342 else
3343 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003344 return;
3345 }
Mike Stump1eb44332009-09-09 15:08:12 +00003346
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003347 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003348 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003349 return;
3350 }
Mike Stump1eb44332009-09-09 15:08:12 +00003351
John McCall0953e762009-09-24 19:53:00 +00003352 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003353 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003354 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003355 S += '{';
3356 const IdentifierInfo *II = OI->getIdentifier();
3357 S += II->getName();
3358 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003359 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003360 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003361 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003362 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003363 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003364 RecFields[i]);
3365 else
Mike Stump1eb44332009-09-09 15:08:12 +00003366 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003367 FD);
3368 }
3369 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003370 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003371 }
Mike Stump1eb44332009-09-09 15:08:12 +00003372
John McCall183700f2009-09-21 23:43:11 +00003373 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003374 if (OPT->isObjCIdType()) {
3375 S += '@';
3376 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003377 }
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003379 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003380 S += '#';
3381 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003382 }
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003384 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003385 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003386 ExpandPointedToStructures,
3387 ExpandStructures, FD);
3388 if (FD || EncodingProperty) {
3389 // Note that we do extended encoding of protocol qualifer list
3390 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003391 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003392 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3393 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003394 S += '<';
3395 S += (*I)->getNameAsString();
3396 S += '>';
3397 }
3398 S += '"';
3399 }
3400 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003401 }
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003403 QualType PointeeTy = OPT->getPointeeType();
3404 if (!EncodingProperty &&
3405 isa<TypedefType>(PointeeTy.getTypePtr())) {
3406 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003407 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003408 // {...};
3409 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003410 getObjCEncodingForTypeImpl(PointeeTy, S,
3411 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003412 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003413 return;
3414 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003415
3416 S += '@';
3417 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003418 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003419 S += OPT->getInterfaceDecl()->getNameAsCString();
3420 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3421 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003422 S += '<';
3423 S += (*I)->getNameAsString();
3424 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003425 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003426 S += '"';
3427 }
3428 return;
3429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003431 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003432}
3433
Mike Stump1eb44332009-09-09 15:08:12 +00003434void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003435 std::string& S) const {
3436 if (QT & Decl::OBJC_TQ_In)
3437 S += 'n';
3438 if (QT & Decl::OBJC_TQ_Inout)
3439 S += 'N';
3440 if (QT & Decl::OBJC_TQ_Out)
3441 S += 'o';
3442 if (QT & Decl::OBJC_TQ_Bycopy)
3443 S += 'O';
3444 if (QT & Decl::OBJC_TQ_Byref)
3445 S += 'R';
3446 if (QT & Decl::OBJC_TQ_Oneway)
3447 S += 'V';
3448}
3449
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003450void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003451 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003453 BuiltinVaListType = T;
3454}
3455
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003456void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003457 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003458}
3459
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003460void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003461 ObjCSelType = T;
3462
John McCall183700f2009-09-21 23:43:11 +00003463 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003464 if (!TT)
3465 return;
3466 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003467
3468 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003469 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003470 if (!ptr)
3471 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003472 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003473 if (!rec)
3474 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003475 SelStructType = rec;
3476}
3477
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003478void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003479 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003480}
3481
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003482void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003483 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003484}
3485
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003486void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003487 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003488 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003490 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003491}
3492
Douglas Gregor7532dc62009-03-30 22:58:21 +00003493/// \brief Retrieve the template name that represents a qualified
3494/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003495TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003496 bool TemplateKeyword,
3497 TemplateDecl *Template) {
3498 llvm::FoldingSetNodeID ID;
3499 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3500
3501 void *InsertPos = 0;
3502 QualifiedTemplateName *QTN =
3503 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3504 if (!QTN) {
3505 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3506 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3507 }
3508
3509 return TemplateName(QTN);
3510}
3511
Douglas Gregord99cbe62009-07-29 18:26:50 +00003512/// \brief Retrieve the template name that represents a qualified
3513/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003514TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003515 bool TemplateKeyword,
3516 OverloadedFunctionDecl *Template) {
3517 llvm::FoldingSetNodeID ID;
3518 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003519
Douglas Gregord99cbe62009-07-29 18:26:50 +00003520 void *InsertPos = 0;
3521 QualifiedTemplateName *QTN =
3522 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3523 if (!QTN) {
3524 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3525 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3526 }
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Douglas Gregord99cbe62009-07-29 18:26:50 +00003528 return TemplateName(QTN);
3529}
3530
Douglas Gregor7532dc62009-03-30 22:58:21 +00003531/// \brief Retrieve the template name that represents a dependent
3532/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003533TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003534 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003535 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003536 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003537
3538 llvm::FoldingSetNodeID ID;
3539 DependentTemplateName::Profile(ID, NNS, Name);
3540
3541 void *InsertPos = 0;
3542 DependentTemplateName *QTN =
3543 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3544
3545 if (QTN)
3546 return TemplateName(QTN);
3547
3548 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3549 if (CanonNNS == NNS) {
3550 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3551 } else {
3552 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3553 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3554 }
3555
3556 DependentTemplateNames.InsertNode(QTN, InsertPos);
3557 return TemplateName(QTN);
3558}
3559
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003560/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003561/// TargetInfo, produce the corresponding type. The unsigned @p Type
3562/// is actually a value of type @c TargetInfo::IntType.
3563QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003564 switch (Type) {
Mike Stump1eb44332009-09-09 15:08:12 +00003565 case TargetInfo::NoInt: return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003566 case TargetInfo::SignedShort: return ShortTy;
3567 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3568 case TargetInfo::SignedInt: return IntTy;
3569 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3570 case TargetInfo::SignedLong: return LongTy;
3571 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3572 case TargetInfo::SignedLongLong: return LongLongTy;
3573 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3574 }
3575
3576 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003577 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003578}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003579
3580//===----------------------------------------------------------------------===//
3581// Type Predicates.
3582//===----------------------------------------------------------------------===//
3583
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003584/// isObjCNSObjectType - Return true if this is an NSObject object using
3585/// NSObject attribute on a c-style pointer type.
3586/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003587/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003588///
3589bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3590 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3591 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003592 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003593 return true;
3594 }
Mike Stump1eb44332009-09-09 15:08:12 +00003595 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003596}
3597
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003598/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3599/// garbage collection attribute.
3600///
John McCall0953e762009-09-24 19:53:00 +00003601Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3602 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003603 if (getLangOptions().ObjC1 &&
3604 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003605 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003606 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003607 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003608 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003609 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003610 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003611 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003612 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003613 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003614 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003615 // Non-pointers have none gc'able attribute regardless of the attribute
3616 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003617 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003618 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003619 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003620 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003621}
3622
Chris Lattner6ac46a42008-04-07 06:51:04 +00003623//===----------------------------------------------------------------------===//
3624// Type Compatibility Testing
3625//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003626
Mike Stump1eb44332009-09-09 15:08:12 +00003627/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003628/// compatible.
3629static bool areCompatVectorTypes(const VectorType *LHS,
3630 const VectorType *RHS) {
3631 assert(LHS->isCanonical() && RHS->isCanonical());
3632 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003633 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003634}
3635
Steve Naroff4084c302009-07-23 01:01:38 +00003636//===----------------------------------------------------------------------===//
3637// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3638//===----------------------------------------------------------------------===//
3639
3640/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3641/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003642bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3643 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003644 if (lProto == rProto)
3645 return true;
3646 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3647 E = rProto->protocol_end(); PI != E; ++PI)
3648 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3649 return true;
3650 return false;
3651}
3652
Steve Naroff4084c302009-07-23 01:01:38 +00003653/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3654/// return true if lhs's protocols conform to rhs's protocol; false
3655/// otherwise.
3656bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3657 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3658 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3659 return false;
3660}
3661
3662/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3663/// ObjCQualifiedIDType.
3664bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3665 bool compare) {
3666 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003667 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003668 lhs->isObjCIdType() || lhs->isObjCClassType())
3669 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003670 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003671 rhs->isObjCIdType() || rhs->isObjCClassType())
3672 return true;
3673
3674 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003675 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Steve Naroff4084c302009-07-23 01:01:38 +00003677 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003678
Steve Naroff4084c302009-07-23 01:01:38 +00003679 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003680 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003681 // make sure we check the class hierarchy.
3682 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3683 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3684 E = lhsQID->qual_end(); I != E; ++I) {
3685 // when comparing an id<P> on lhs with a static type on rhs,
3686 // see if static class implements all of id's protocols, directly or
3687 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003688 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003689 return false;
3690 }
3691 }
3692 // If there are no qualifiers and no interface, we have an 'id'.
3693 return true;
3694 }
Mike Stump1eb44332009-09-09 15:08:12 +00003695 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003696 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3697 E = lhsQID->qual_end(); I != E; ++I) {
3698 ObjCProtocolDecl *lhsProto = *I;
3699 bool match = false;
3700
3701 // when comparing an id<P> on lhs with a static type on rhs,
3702 // see if static class implements all of id's protocols, directly or
3703 // through its super class and categories.
3704 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3705 E = rhsOPT->qual_end(); J != E; ++J) {
3706 ObjCProtocolDecl *rhsProto = *J;
3707 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3708 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3709 match = true;
3710 break;
3711 }
3712 }
Mike Stump1eb44332009-09-09 15:08:12 +00003713 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003714 // make sure we check the class hierarchy.
3715 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3716 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3717 E = lhsQID->qual_end(); I != E; ++I) {
3718 // when comparing an id<P> on lhs with a static type on rhs,
3719 // see if static class implements all of id's protocols, directly or
3720 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003721 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003722 match = true;
3723 break;
3724 }
3725 }
3726 }
3727 if (!match)
3728 return false;
3729 }
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Steve Naroff4084c302009-07-23 01:01:38 +00003731 return true;
3732 }
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Steve Naroff4084c302009-07-23 01:01:38 +00003734 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3735 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3736
Mike Stump1eb44332009-09-09 15:08:12 +00003737 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003738 lhs->getAsObjCInterfacePointerType()) {
3739 if (lhsOPT->qual_empty()) {
3740 bool match = false;
3741 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3742 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3743 E = rhsQID->qual_end(); I != E; ++I) {
3744 // when comparing an id<P> on lhs with a static type on rhs,
3745 // see if static class implements all of id's protocols, directly or
3746 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003747 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003748 match = true;
3749 break;
3750 }
3751 }
3752 if (!match)
3753 return false;
3754 }
3755 return true;
3756 }
Mike Stump1eb44332009-09-09 15:08:12 +00003757 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003758 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3759 E = lhsOPT->qual_end(); I != E; ++I) {
3760 ObjCProtocolDecl *lhsProto = *I;
3761 bool match = false;
3762
3763 // when comparing an id<P> on lhs with a static type on rhs,
3764 // see if static class implements all of id's protocols, directly or
3765 // through its super class and categories.
3766 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3767 E = rhsQID->qual_end(); J != E; ++J) {
3768 ObjCProtocolDecl *rhsProto = *J;
3769 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3770 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3771 match = true;
3772 break;
3773 }
3774 }
3775 if (!match)
3776 return false;
3777 }
3778 return true;
3779 }
3780 return false;
3781}
3782
Eli Friedman3d815e72008-08-22 00:56:42 +00003783/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003784/// compatible for assignment from RHS to LHS. This handles validation of any
3785/// protocol qualifiers on the LHS or RHS.
3786///
Steve Naroff14108da2009-07-10 23:34:53 +00003787bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3788 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003789 // If either type represents the built-in 'id' or 'Class' types, return true.
3790 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003791 return true;
3792
Steve Naroff4084c302009-07-23 01:01:38 +00003793 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003794 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3795 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003796 false);
3797
Steve Naroff14108da2009-07-10 23:34:53 +00003798 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3799 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003800 if (LHS && RHS) // We have 2 user-defined types.
3801 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Steve Naroff4084c302009-07-23 01:01:38 +00003803 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003804}
3805
Eli Friedman3d815e72008-08-22 00:56:42 +00003806bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3807 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003808 // Verify that the base decls are compatible: the RHS must be a subclass of
3809 // the LHS.
3810 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3811 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003812
Chris Lattner6ac46a42008-04-07 06:51:04 +00003813 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3814 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003815 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003816 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Chris Lattner6ac46a42008-04-07 06:51:04 +00003818 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3819 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003820 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003821 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003823 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3824 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003825 LHSPI != LHSPE; LHSPI++) {
3826 bool RHSImplementsProtocol = false;
3827
3828 // If the RHS doesn't implement the protocol on the left, the types
3829 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003830 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003831 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003832 RHSPI != RHSPE; RHSPI++) {
3833 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003834 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003835 break;
3836 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003837 }
3838 // FIXME: For better diagnostics, consider passing back the protocol name.
3839 if (!RHSImplementsProtocol)
3840 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003841 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003842 // The RHS implements all protocols listed on the LHS.
3843 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003844}
3845
Steve Naroff389bf462009-02-12 17:52:19 +00003846bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3847 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00003848 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
3849 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Steve Naroff14108da2009-07-10 23:34:53 +00003851 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003852 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003853
3854 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3855 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003856}
3857
Mike Stump1eb44332009-09-09 15:08:12 +00003858/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00003859/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00003860/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00003861/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003862bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3863 return !mergeTypes(LHS, RHS).isNull();
3864}
3865
3866QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00003867 const FunctionType *lbase = lhs->getAs<FunctionType>();
3868 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00003869 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3870 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003871 bool allLTypes = true;
3872 bool allRTypes = true;
3873
3874 // Check return type
3875 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3876 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003877 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3878 allLTypes = false;
3879 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3880 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003881 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003882 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3883 if (NoReturn != lbase->getNoReturnAttr())
3884 allLTypes = false;
3885 if (NoReturn != rbase->getNoReturnAttr())
3886 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Eli Friedman3d815e72008-08-22 00:56:42 +00003888 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003889 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3890 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003891 unsigned lproto_nargs = lproto->getNumArgs();
3892 unsigned rproto_nargs = rproto->getNumArgs();
3893
3894 // Compatible functions must have the same number of arguments
3895 if (lproto_nargs != rproto_nargs)
3896 return QualType();
3897
3898 // Variadic and non-variadic functions aren't compatible
3899 if (lproto->isVariadic() != rproto->isVariadic())
3900 return QualType();
3901
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003902 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3903 return QualType();
3904
Eli Friedman3d815e72008-08-22 00:56:42 +00003905 // Check argument compatibility
3906 llvm::SmallVector<QualType, 10> types;
3907 for (unsigned i = 0; i < lproto_nargs; i++) {
3908 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3909 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3910 QualType argtype = mergeTypes(largtype, rargtype);
3911 if (argtype.isNull()) return QualType();
3912 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003913 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3914 allLTypes = false;
3915 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3916 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003917 }
3918 if (allLTypes) return lhs;
3919 if (allRTypes) return rhs;
3920 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003921 lproto->isVariadic(), lproto->getTypeQuals(),
3922 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003923 }
3924
3925 if (lproto) allRTypes = false;
3926 if (rproto) allLTypes = false;
3927
Douglas Gregor72564e72009-02-26 23:50:07 +00003928 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003929 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003930 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003931 if (proto->isVariadic()) return QualType();
3932 // Check that the types are compatible with the types that
3933 // would result from default argument promotions (C99 6.7.5.3p15).
3934 // The only types actually affected are promotable integer
3935 // types and floats, which would be passed as a different
3936 // type depending on whether the prototype is visible.
3937 unsigned proto_nargs = proto->getNumArgs();
3938 for (unsigned i = 0; i < proto_nargs; ++i) {
3939 QualType argTy = proto->getArgType(i);
3940 if (argTy->isPromotableIntegerType() ||
3941 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3942 return QualType();
3943 }
3944
3945 if (allLTypes) return lhs;
3946 if (allRTypes) return rhs;
3947 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003948 proto->getNumArgs(), proto->isVariadic(),
3949 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003950 }
3951
3952 if (allLTypes) return lhs;
3953 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003954 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003955}
3956
3957QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003958 // C++ [expr]: If an expression initially has the type "reference to T", the
3959 // type is adjusted to "T" prior to any further analysis, the expression
3960 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003961 // expression is an lvalue unless the reference is an rvalue reference and
3962 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003963 // FIXME: C++ shouldn't be going through here! The rules are different
3964 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003965 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3966 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003967 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003968 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003969 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003970 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003971
Eli Friedman3d815e72008-08-22 00:56:42 +00003972 QualType LHSCan = getCanonicalType(LHS),
3973 RHSCan = getCanonicalType(RHS);
3974
3975 // If two types are identical, they are compatible.
3976 if (LHSCan == RHSCan)
3977 return LHS;
3978
John McCall0953e762009-09-24 19:53:00 +00003979 // If the qualifiers are different, the types aren't compatible... mostly.
3980 Qualifiers LQuals = LHSCan.getQualifiers();
3981 Qualifiers RQuals = RHSCan.getQualifiers();
3982 if (LQuals != RQuals) {
3983 // If any of these qualifiers are different, we have a type
3984 // mismatch.
3985 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
3986 LQuals.getAddressSpace() != RQuals.getAddressSpace())
3987 return QualType();
3988
3989 // Exactly one GC qualifier difference is allowed: __strong is
3990 // okay if the other type has no GC qualifier but is an Objective
3991 // C object pointer (i.e. implicitly strong by default). We fix
3992 // this by pretending that the unqualified type was actually
3993 // qualified __strong.
3994 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
3995 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
3996 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
3997
3998 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
3999 return QualType();
4000
4001 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4002 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4003 }
4004 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4005 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4006 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004007 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004008 }
4009
4010 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004011
Eli Friedman852d63b2009-06-01 01:22:52 +00004012 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4013 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004014
Chris Lattner1adb8832008-01-14 05:45:46 +00004015 // We want to consider the two function types to be the same for these
4016 // comparisons, just force one to the other.
4017 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4018 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004019
4020 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004021 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4022 LHSClass = Type::ConstantArray;
4023 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4024 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Nate Begeman213541a2008-04-18 23:10:10 +00004026 // Canonicalize ExtVector -> Vector.
4027 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4028 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Chris Lattnera36a61f2008-04-07 05:43:21 +00004030 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004031 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004032 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004033 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004034 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004035 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4036 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004037 }
John McCall183700f2009-09-21 23:43:11 +00004038 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004039 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4040 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004041 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004042
Eli Friedman3d815e72008-08-22 00:56:42 +00004043 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004044 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004045
Steve Naroff4a746782008-01-09 22:43:08 +00004046 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004047 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004048#define TYPE(Class, Base)
4049#define ABSTRACT_TYPE(Class, Base)
4050#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4051#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4052#include "clang/AST/TypeNodes.def"
4053 assert(false && "Non-canonical and dependent types shouldn't get here");
4054 return QualType();
4055
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004056 case Type::LValueReference:
4057 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004058 case Type::MemberPointer:
4059 assert(false && "C++ should never be in mergeTypes");
4060 return QualType();
4061
4062 case Type::IncompleteArray:
4063 case Type::VariableArray:
4064 case Type::FunctionProto:
4065 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004066 assert(false && "Types are eliminated above");
4067 return QualType();
4068
Chris Lattner1adb8832008-01-14 05:45:46 +00004069 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004070 {
4071 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004072 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4073 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004074 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4075 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004076 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004077 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004078 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004079 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004080 return getPointerType(ResultType);
4081 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004082 case Type::BlockPointer:
4083 {
4084 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004085 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4086 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004087 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4088 if (ResultType.isNull()) return QualType();
4089 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4090 return LHS;
4091 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4092 return RHS;
4093 return getBlockPointerType(ResultType);
4094 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004095 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004096 {
4097 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4098 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4099 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4100 return QualType();
4101
4102 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4103 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4104 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4105 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004106 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4107 return LHS;
4108 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4109 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004110 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4111 ArrayType::ArraySizeModifier(), 0);
4112 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4113 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004114 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4115 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004116 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4117 return LHS;
4118 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4119 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004120 if (LVAT) {
4121 // FIXME: This isn't correct! But tricky to implement because
4122 // the array's size has to be the size of LHS, but the type
4123 // has to be different.
4124 return LHS;
4125 }
4126 if (RVAT) {
4127 // FIXME: This isn't correct! But tricky to implement because
4128 // the array's size has to be the size of RHS, but the type
4129 // has to be different.
4130 return RHS;
4131 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004132 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4133 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004134 return getIncompleteArrayType(ResultType,
4135 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004136 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004137 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004138 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004139 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004140 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004141 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004142 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004143 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004144 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004145 case Type::Complex:
4146 // Distinct complex types are incompatible.
4147 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004148 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004149 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004150 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004151 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004152 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004153 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004154 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004155 // FIXME: This should be type compatibility, e.g. whether
4156 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004157 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4158 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004159 if (LHSIface && RHSIface &&
4160 canAssignObjCInterfaces(LHSIface, RHSIface))
4161 return LHS;
4162
Eli Friedman3d815e72008-08-22 00:56:42 +00004163 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004164 }
Steve Naroff14108da2009-07-10 23:34:53 +00004165 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004166 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4167 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004168 return LHS;
4169
Steve Naroffbc76dd02008-12-10 22:14:21 +00004170 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004171 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004172 case Type::FixedWidthInt:
4173 // Distinct fixed-width integers are not compatible.
4174 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004175 case Type::TemplateSpecialization:
4176 assert(false && "Dependent types have no size");
4177 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004178 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004179
4180 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004181}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004182
Chris Lattner5426bf62008-04-07 07:01:58 +00004183//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004184// Integer Predicates
4185//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004186
Eli Friedmanad74a752008-06-28 06:23:08 +00004187unsigned ASTContext::getIntWidth(QualType T) {
4188 if (T == BoolTy)
4189 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004190 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004191 return FWIT->getWidth();
4192 }
4193 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004194 return (unsigned)getTypeSize(T);
4195}
4196
4197QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4198 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004199
4200 // Turn <4 x signed int> -> <4 x unsigned int>
4201 if (const VectorType *VTy = T->getAs<VectorType>())
4202 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4203 VTy->getNumElements());
4204
4205 // For enums, we return the unsigned version of the base type.
4206 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004207 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004208
4209 const BuiltinType *BTy = T->getAs<BuiltinType>();
4210 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004211 switch (BTy->getKind()) {
4212 case BuiltinType::Char_S:
4213 case BuiltinType::SChar:
4214 return UnsignedCharTy;
4215 case BuiltinType::Short:
4216 return UnsignedShortTy;
4217 case BuiltinType::Int:
4218 return UnsignedIntTy;
4219 case BuiltinType::Long:
4220 return UnsignedLongTy;
4221 case BuiltinType::LongLong:
4222 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004223 case BuiltinType::Int128:
4224 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004225 default:
4226 assert(0 && "Unexpected signed integer type");
4227 return QualType();
4228 }
4229}
4230
Douglas Gregor2cf26342009-04-09 22:27:44 +00004231ExternalASTSource::~ExternalASTSource() { }
4232
4233void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004234
4235
4236//===----------------------------------------------------------------------===//
4237// Builtin Type Computation
4238//===----------------------------------------------------------------------===//
4239
4240/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4241/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004242static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004243 ASTContext::GetBuiltinTypeError &Error,
4244 bool AllowTypeModifiers = true) {
4245 // Modifiers.
4246 int HowLong = 0;
4247 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Chris Lattner86df27b2009-06-14 00:45:47 +00004249 // Read the modifiers first.
4250 bool Done = false;
4251 while (!Done) {
4252 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004253 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004254 case 'S':
4255 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4256 assert(!Signed && "Can't use 'S' modifier multiple times!");
4257 Signed = true;
4258 break;
4259 case 'U':
4260 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4261 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4262 Unsigned = true;
4263 break;
4264 case 'L':
4265 assert(HowLong <= 2 && "Can't have LLLL modifier");
4266 ++HowLong;
4267 break;
4268 }
4269 }
4270
4271 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Chris Lattner86df27b2009-06-14 00:45:47 +00004273 // Read the base type.
4274 switch (*Str++) {
4275 default: assert(0 && "Unknown builtin type letter!");
4276 case 'v':
4277 assert(HowLong == 0 && !Signed && !Unsigned &&
4278 "Bad modifiers used with 'v'!");
4279 Type = Context.VoidTy;
4280 break;
4281 case 'f':
4282 assert(HowLong == 0 && !Signed && !Unsigned &&
4283 "Bad modifiers used with 'f'!");
4284 Type = Context.FloatTy;
4285 break;
4286 case 'd':
4287 assert(HowLong < 2 && !Signed && !Unsigned &&
4288 "Bad modifiers used with 'd'!");
4289 if (HowLong)
4290 Type = Context.LongDoubleTy;
4291 else
4292 Type = Context.DoubleTy;
4293 break;
4294 case 's':
4295 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4296 if (Unsigned)
4297 Type = Context.UnsignedShortTy;
4298 else
4299 Type = Context.ShortTy;
4300 break;
4301 case 'i':
4302 if (HowLong == 3)
4303 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4304 else if (HowLong == 2)
4305 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4306 else if (HowLong == 1)
4307 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4308 else
4309 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4310 break;
4311 case 'c':
4312 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4313 if (Signed)
4314 Type = Context.SignedCharTy;
4315 else if (Unsigned)
4316 Type = Context.UnsignedCharTy;
4317 else
4318 Type = Context.CharTy;
4319 break;
4320 case 'b': // boolean
4321 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4322 Type = Context.BoolTy;
4323 break;
4324 case 'z': // size_t.
4325 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4326 Type = Context.getSizeType();
4327 break;
4328 case 'F':
4329 Type = Context.getCFConstantStringType();
4330 break;
4331 case 'a':
4332 Type = Context.getBuiltinVaListType();
4333 assert(!Type.isNull() && "builtin va list type not initialized!");
4334 break;
4335 case 'A':
4336 // This is a "reference" to a va_list; however, what exactly
4337 // this means depends on how va_list is defined. There are two
4338 // different kinds of va_list: ones passed by value, and ones
4339 // passed by reference. An example of a by-value va_list is
4340 // x86, where va_list is a char*. An example of by-ref va_list
4341 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4342 // we want this argument to be a char*&; for x86-64, we want
4343 // it to be a __va_list_tag*.
4344 Type = Context.getBuiltinVaListType();
4345 assert(!Type.isNull() && "builtin va list type not initialized!");
4346 if (Type->isArrayType()) {
4347 Type = Context.getArrayDecayedType(Type);
4348 } else {
4349 Type = Context.getLValueReferenceType(Type);
4350 }
4351 break;
4352 case 'V': {
4353 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004354 unsigned NumElements = strtoul(Str, &End, 10);
4355 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Chris Lattner86df27b2009-06-14 00:45:47 +00004357 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Chris Lattner86df27b2009-06-14 00:45:47 +00004359 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4360 Type = Context.getVectorType(ElementType, NumElements);
4361 break;
4362 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004363 case 'X': {
4364 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4365 Type = Context.getComplexType(ElementType);
4366 break;
4367 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004368 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004369 Type = Context.getFILEType();
4370 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004371 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004372 return QualType();
4373 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004374 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004375 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004376 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004377 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004378 else
4379 Type = Context.getjmp_bufType();
4380
Mike Stumpfd612db2009-07-28 23:47:15 +00004381 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004382 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004383 return QualType();
4384 }
4385 break;
Mike Stump782fa302009-07-28 02:25:19 +00004386 }
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Chris Lattner86df27b2009-06-14 00:45:47 +00004388 if (!AllowTypeModifiers)
4389 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004390
Chris Lattner86df27b2009-06-14 00:45:47 +00004391 Done = false;
4392 while (!Done) {
4393 switch (*Str++) {
4394 default: Done = true; --Str; break;
4395 case '*':
4396 Type = Context.getPointerType(Type);
4397 break;
4398 case '&':
4399 Type = Context.getLValueReferenceType(Type);
4400 break;
4401 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4402 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004403 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004404 break;
4405 }
4406 }
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Chris Lattner86df27b2009-06-14 00:45:47 +00004408 return Type;
4409}
4410
4411/// GetBuiltinType - Return the type for the specified builtin.
4412QualType ASTContext::GetBuiltinType(unsigned id,
4413 GetBuiltinTypeError &Error) {
4414 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004415
Chris Lattner86df27b2009-06-14 00:45:47 +00004416 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Chris Lattner86df27b2009-06-14 00:45:47 +00004418 Error = GE_None;
4419 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4420 if (Error != GE_None)
4421 return QualType();
4422 while (TypeStr[0] && TypeStr[0] != '.') {
4423 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4424 if (Error != GE_None)
4425 return QualType();
4426
4427 // Do array -> pointer decay. The builtin should use the decayed type.
4428 if (Ty->isArrayType())
4429 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004430
Chris Lattner86df27b2009-06-14 00:45:47 +00004431 ArgTypes.push_back(Ty);
4432 }
4433
4434 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4435 "'.' should only occur at end of builtin type list!");
4436
4437 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4438 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4439 return getFunctionNoProtoType(ResType);
4440 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4441 TypeStr[0] == '.', 0);
4442}
Eli Friedmana95d7572009-08-19 07:44:53 +00004443
4444QualType
4445ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4446 // Perform the usual unary conversions. We do this early so that
4447 // integral promotions to "int" can allow us to exit early, in the
4448 // lhs == rhs check. Also, for conversion purposes, we ignore any
4449 // qualifiers. For example, "const float" and "float" are
4450 // equivalent.
4451 if (lhs->isPromotableIntegerType())
4452 lhs = getPromotedIntegerType(lhs);
4453 else
4454 lhs = lhs.getUnqualifiedType();
4455 if (rhs->isPromotableIntegerType())
4456 rhs = getPromotedIntegerType(rhs);
4457 else
4458 rhs = rhs.getUnqualifiedType();
4459
4460 // If both types are identical, no conversion is needed.
4461 if (lhs == rhs)
4462 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Eli Friedmana95d7572009-08-19 07:44:53 +00004464 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4465 // The caller can deal with this (e.g. pointer + int).
4466 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4467 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004468
4469 // At this point, we have two different arithmetic types.
4470
Eli Friedmana95d7572009-08-19 07:44:53 +00004471 // Handle complex types first (C99 6.3.1.8p1).
4472 if (lhs->isComplexType() || rhs->isComplexType()) {
4473 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004474 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004475 // convert the rhs to the lhs complex type.
4476 return lhs;
4477 }
Mike Stump1eb44332009-09-09 15:08:12 +00004478 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004479 // convert the lhs to the rhs complex type.
4480 return rhs;
4481 }
4482 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004483 // When both operands are complex, the shorter operand is converted to the
4484 // type of the longer, and that is the type of the result. This corresponds
4485 // to what is done when combining two real floating-point operands.
4486 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004487 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004488 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004489 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004490 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004491 // "double _Complex" is promoted to "long double _Complex".
4492 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004493
4494 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004495 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004496 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004497 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004498 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004499 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4500 // domains match. This is a requirement for our implementation, C99
4501 // does not require this promotion.
4502 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4503 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4504 return rhs;
4505 } else { // handle "_Complex double, double".
4506 return lhs;
4507 }
4508 }
4509 return lhs; // The domain/size match exactly.
4510 }
4511 // Now handle "real" floating types (i.e. float, double, long double).
4512 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4513 // if we have an integer operand, the result is the real floating type.
4514 if (rhs->isIntegerType()) {
4515 // convert rhs to the lhs floating point type.
4516 return lhs;
4517 }
4518 if (rhs->isComplexIntegerType()) {
4519 // convert rhs to the complex floating point type.
4520 return getComplexType(lhs);
4521 }
4522 if (lhs->isIntegerType()) {
4523 // convert lhs to the rhs floating point type.
4524 return rhs;
4525 }
Mike Stump1eb44332009-09-09 15:08:12 +00004526 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004527 // convert lhs to the complex floating point type.
4528 return getComplexType(rhs);
4529 }
4530 // We have two real floating types, float/complex combos were handled above.
4531 // Convert the smaller operand to the bigger result.
4532 int result = getFloatingTypeOrder(lhs, rhs);
4533 if (result > 0) // convert the rhs
4534 return lhs;
4535 assert(result < 0 && "illegal float comparison");
4536 return rhs; // convert the lhs
4537 }
4538 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4539 // Handle GCC complex int extension.
4540 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4541 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4542
4543 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004544 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004545 rhsComplexInt->getElementType()) >= 0)
4546 return lhs; // convert the rhs
4547 return rhs;
4548 } else if (lhsComplexInt && rhs->isIntegerType()) {
4549 // convert the rhs to the lhs complex type.
4550 return lhs;
4551 } else if (rhsComplexInt && lhs->isIntegerType()) {
4552 // convert the lhs to the rhs complex type.
4553 return rhs;
4554 }
4555 }
4556 // Finally, we have two differing integer types.
4557 // The rules for this case are in C99 6.3.1.8
4558 int compare = getIntegerTypeOrder(lhs, rhs);
4559 bool lhsSigned = lhs->isSignedIntegerType(),
4560 rhsSigned = rhs->isSignedIntegerType();
4561 QualType destType;
4562 if (lhsSigned == rhsSigned) {
4563 // Same signedness; use the higher-ranked type
4564 destType = compare >= 0 ? lhs : rhs;
4565 } else if (compare != (lhsSigned ? 1 : -1)) {
4566 // The unsigned type has greater than or equal rank to the
4567 // signed type, so use the unsigned type
4568 destType = lhsSigned ? rhs : lhs;
4569 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4570 // The two types are different widths; if we are here, that
4571 // means the signed type is larger than the unsigned type, so
4572 // use the signed type.
4573 destType = lhsSigned ? lhs : rhs;
4574 } else {
4575 // The signed type is higher-ranked than the unsigned type,
4576 // but isn't actually any bigger (like unsigned int and long
4577 // on most 32-bit systems). Use the unsigned type corresponding
4578 // to the signed type.
4579 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4580 }
4581 return destType;
4582}