blob: 7422ca8597366b6a95cae7f8f51617c34469da2b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000025#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000026#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000027#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000028#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000029#include "RecordLayoutBuilder.h"
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
33enum FloatingRank {
34 FloatRank, DoubleRank, LongDoubleRank
35};
36
Chris Lattner61710852008-10-05 17:34:18 +000037ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000038 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000039 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000040 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000041 bool FreeMem, unsigned size_reserve) :
42 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000043 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000044 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
45 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000046 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000047 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000048 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000049 ObjCIdRedefinitionType = QualType();
50 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000051 ObjCSELRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000052 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000053 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000054 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000055}
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057ASTContext::~ASTContext() {
58 // Deallocate all the types.
59 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000060 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000061 Types.pop_back();
62 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000063
Nuno Lopesb74668e2008-12-17 22:30:25 +000064 {
John McCall0953e762009-09-24 19:53:00 +000065 llvm::FoldingSet<ExtQuals>::iterator
66 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
67 while (I != E)
68 Deallocate(&*I++);
69 }
70
71 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000072 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
73 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
74 while (I != E) {
75 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
76 delete R;
77 }
78 }
79
80 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000081 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000083 while (I != E) {
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
86 }
87 }
88
Douglas Gregorab452ba2009-03-26 23:50:42 +000089 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000090 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
91 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000092 NNSEnd = NestedNameSpecifiers.end();
93 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 /* Increment in loop */)
95 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
Anders Carlsson0d8df782009-08-29 19:37:28 +0000263ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
Anders Carlsson0d8df782009-08-29 19:37:28 +0000265 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
273ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
John McCall7ba107a2009-11-18 02:36:19 +0000274 NamedDecl *UUD) {
275 assert((isa<UnresolvedUsingValueDecl>(UUD) ||
276 isa<UnresolvedUsingTypenameDecl>(UUD)) &&
277 "original declaration is not an unresolved using decl");
Anders Carlsson0d8df782009-08-29 19:37:28 +0000278 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
279 "Already noted what using decl what instantiated from");
280 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
281}
282
Anders Carlssond8b285f2009-09-01 04:26:58 +0000283FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
284 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
285 = InstantiatedFromUnnamedFieldDecl.find(Field);
286 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
287 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Anders Carlssond8b285f2009-09-01 04:26:58 +0000289 return Pos->second;
290}
291
292void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
293 FieldDecl *Tmpl) {
294 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
295 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
296 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
297 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Anders Carlssond8b285f2009-09-01 04:26:58 +0000299 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
300}
301
Douglas Gregor2e222532009-07-02 17:08:52 +0000302namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000303 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000304 : std::binary_function<SourceRange, SourceRange, bool> {
305 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Douglas Gregor2e222532009-07-02 17:08:52 +0000307 public:
308 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Douglas Gregor2e222532009-07-02 17:08:52 +0000310 bool operator()(SourceRange X, SourceRange Y) {
311 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
312 }
313 };
314}
315
316/// \brief Determine whether the given comment is a Doxygen-style comment.
317///
318/// \param Start the start of the comment text.
319///
320/// \param End the end of the comment text.
321///
322/// \param Member whether we want to check whether this is a member comment
323/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
324/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000325static bool
326isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000327 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000328 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000329 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
330 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
331 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Douglas Gregor2e222532009-07-02 17:08:52 +0000333 if (End - Start < 4)
334 return false;
335
336 assert(Start[0] == '/' && "Not a comment?");
337 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
338 return false;
339 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
340 return false;
341
342 return (Start[3] == '<') == Member;
343}
344
345/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000346/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000347const char *ASTContext::getCommentForDecl(const Decl *D) {
348 if (!D)
349 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Douglas Gregor2e222532009-07-02 17:08:52 +0000351 // Check whether we have cached a comment string for this declaration
352 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000353 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000354 = DeclComments.find(D);
355 if (Pos != DeclComments.end())
356 return Pos->second.c_str();
357
Mike Stump1eb44332009-09-09 15:08:12 +0000358 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000359 // that source, do so now.
360 if (ExternalSource && !LoadedExternalComments) {
361 std::vector<SourceRange> LoadedComments;
362 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Douglas Gregor2e222532009-07-02 17:08:52 +0000364 if (!LoadedComments.empty())
365 Comments.insert(Comments.begin(), LoadedComments.begin(),
366 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Douglas Gregor2e222532009-07-02 17:08:52 +0000368 LoadedExternalComments = true;
369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
371 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000372 if (Comments.empty())
373 return 0;
374
375 // If the declaration doesn't map directly to a location in a file, we
376 // can't find the comment.
377 SourceLocation DeclStartLoc = D->getLocStart();
378 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
379 return 0;
380
381 // Find the comment that occurs just before this declaration.
382 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000383 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 SourceRange(DeclStartLoc),
385 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor2e222532009-07-02 17:08:52 +0000387 // Decompose the location for the start of the declaration and find the
388 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000389 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000390 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000392 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregor2e222532009-07-02 17:08:52 +0000394 // First check whether we have a comment for a member.
395 if (LastComment != Comments.end() &&
396 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
397 isDoxygenComment(SourceMgr, *LastComment, true)) {
398 std::pair<FileID, unsigned> LastCommentEndDecomp
399 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
400 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
401 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000402 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 LastCommentEndDecomp.second)) {
404 // The Doxygen member comment comes after the declaration starts and
405 // is on the same line and in the same file as the declaration. This
406 // is the comment we want.
407 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000408 Result.append(FileBufferStart +
409 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 FileBufferStart + LastCommentEndDecomp.second + 1);
411 return Result.c_str();
412 }
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Douglas Gregor2e222532009-07-02 17:08:52 +0000415 if (LastComment == Comments.begin())
416 return 0;
417 --LastComment;
418
419 // Decompose the end of the comment.
420 std::pair<FileID, unsigned> LastCommentEndDecomp
421 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Douglas Gregor2e222532009-07-02 17:08:52 +0000423 // If the comment and the declaration aren't in the same file, then they
424 // aren't related.
425 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
426 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Douglas Gregor2e222532009-07-02 17:08:52 +0000428 // Check that we actually have a Doxygen comment.
429 if (!isDoxygenComment(SourceMgr, *LastComment))
430 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Douglas Gregor2e222532009-07-02 17:08:52 +0000432 // Compute the starting line for the declaration and for the end of the
433 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000434 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000435 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
436 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000437 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000438 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Douglas Gregor2e222532009-07-02 17:08:52 +0000440 // If the comment does not end on the line prior to the declaration, then
441 // the comment is not associated with the declaration at all.
442 if (CommentEndLine + 1 != DeclStartLine)
443 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregor2e222532009-07-02 17:08:52 +0000445 // We have a comment, but there may be more comments on the previous lines.
446 // Keep looking so long as the comments are still Doxygen comments and are
447 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000448 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000449 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
450 std::vector<SourceRange>::iterator FirstComment = LastComment;
451 while (FirstComment != Comments.begin()) {
452 // Look at the previous comment
453 --FirstComment;
454 std::pair<FileID, unsigned> Decomp
455 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Douglas Gregor2e222532009-07-02 17:08:52 +0000457 // If this previous comment is in a different file, we're done.
458 if (Decomp.first != DeclStartDecomp.first) {
459 ++FirstComment;
460 break;
461 }
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Douglas Gregor2e222532009-07-02 17:08:52 +0000463 // If this comment is not a Doxygen comment, we're done.
464 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
465 ++FirstComment;
466 break;
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregor2e222532009-07-02 17:08:52 +0000469 // If the line number is not what we expected, we're done.
470 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
471 if (Line != ExpectedLine) {
472 ++FirstComment;
473 break;
474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Douglas Gregor2e222532009-07-02 17:08:52 +0000476 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000477 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000478 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Douglas Gregor2e222532009-07-02 17:08:52 +0000481 // The iterator range [FirstComment, LastComment] contains all of the
482 // BCPL comments that, together, are associated with this declaration.
483 // Form a single comment block string for this declaration that concatenates
484 // all of these comments.
485 std::string &Result = DeclComments[D];
486 while (FirstComment != LastComment) {
487 std::pair<FileID, unsigned> DecompStart
488 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
489 std::pair<FileID, unsigned> DecompEnd
490 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
491 Result.append(FileBufferStart + DecompStart.second,
492 FileBufferStart + DecompEnd.second + 1);
493 ++FirstComment;
494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregor2e222532009-07-02 17:08:52 +0000496 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000497 Result.append(FileBufferStart +
498 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000499 FileBufferStart + LastCommentEndDecomp.second + 1);
500 return Result.c_str();
501}
502
Chris Lattner464175b2007-07-18 17:52:12 +0000503//===----------------------------------------------------------------------===//
504// Type Sizing and Analysis
505//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000506
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000507/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
508/// scalar floating point type.
509const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000510 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000511 assert(BT && "Not a floating point type!");
512 switch (BT->getKind()) {
513 default: assert(0 && "Not a floating point type!");
514 case BuiltinType::Float: return Target.getFloatFormat();
515 case BuiltinType::Double: return Target.getDoubleFormat();
516 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
517 }
518}
519
Mike Stump196efbf2009-09-22 02:43:44 +0000520/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000521/// specified decl. Note that bitfields do not have a valid alignment, so
522/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000523/// If @p RefAsPointee, references are treated like their underlying type
524/// (for alignof), else they're treated like pointers (for CodeGen).
525unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000526 unsigned Align = Target.getCharWidth();
527
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000528 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000529 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000530
Chris Lattneraf707ab2009-01-24 21:53:27 +0000531 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
532 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000533 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000534 if (RefAsPointee)
535 T = RT->getPointeeType();
536 else
537 T = getPointerType(RT->getPointeeType());
538 }
539 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000540 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000541 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
542 T = cast<ArrayType>(T)->getElementType();
543
544 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
545 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000546 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000547
548 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000549}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000550
Chris Lattnera7674d82007-07-13 22:13:22 +0000551/// getTypeSize - Return the size of the specified type, in bits. This method
552/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000553///
554/// FIXME: Pointers into different addr spaces could have different sizes and
555/// alignment requirements: getPointerInfo should take an AddrSpace, this
556/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000557std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000558ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000559 uint64_t Width=0;
560 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000561 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000562#define TYPE(Class, Base)
563#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000564#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000565#define DEPENDENT_TYPE(Class, Base) case Type::Class:
566#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000567 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000568 break;
569
Chris Lattner692233e2007-07-13 22:27:08 +0000570 case Type::FunctionNoProto:
571 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000572 // GCC extension: alignof(function) = 32 bits
573 Width = 0;
574 Align = 32;
575 break;
576
Douglas Gregor72564e72009-02-26 23:50:07 +0000577 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000578 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000579 Width = 0;
580 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
581 break;
582
Steve Narofffb22d962007-08-30 01:06:46 +0000583 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000584 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner98be4942008-03-05 18:54:05 +0000586 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000587 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000588 Align = EltInfo.second;
589 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000590 }
Nate Begeman213541a2008-04-18 23:10:10 +0000591 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000592 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000593 const VectorType *VT = cast<VectorType>(T);
594 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
595 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000596 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000597 // If the alignment is not a power of 2, round up to the next power of 2.
598 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000599 if (VT->getNumElements() & (VT->getNumElements()-1)) {
600 Align = llvm::NextPowerOf2(Align);
601 Width = llvm::RoundUpToAlignment(Width, Align);
602 }
Chris Lattner030d8842007-07-19 22:06:24 +0000603 break;
604 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000605
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000606 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000607 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000608 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000609 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000610 // GCC extension: alignof(void) = 8 bits.
611 Width = 0;
612 Align = 8;
613 break;
614
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000615 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000616 Width = Target.getBoolWidth();
617 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000618 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000619 case BuiltinType::Char_S:
620 case BuiltinType::Char_U:
621 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000622 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000623 Width = Target.getCharWidth();
624 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000625 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000626 case BuiltinType::WChar:
627 Width = Target.getWCharWidth();
628 Align = Target.getWCharAlign();
629 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000630 case BuiltinType::Char16:
631 Width = Target.getChar16Width();
632 Align = Target.getChar16Align();
633 break;
634 case BuiltinType::Char32:
635 Width = Target.getChar32Width();
636 Align = Target.getChar32Align();
637 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000638 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = Target.getShortWidth();
641 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000643 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000645 Width = Target.getIntWidth();
646 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000647 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000648 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000649 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000650 Width = Target.getLongWidth();
651 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000653 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000654 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000655 Width = Target.getLongLongWidth();
656 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000657 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000658 case BuiltinType::Int128:
659 case BuiltinType::UInt128:
660 Width = 128;
661 Align = 128; // int128_t is 128-bit aligned on all targets.
662 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000664 Width = Target.getFloatWidth();
665 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000666 break;
667 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000668 Width = Target.getDoubleWidth();
669 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 break;
671 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000672 Width = Target.getLongDoubleWidth();
673 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000675 case BuiltinType::NullPtr:
676 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
677 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000678 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000679 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000680 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000681 case Type::FixedWidthInt:
682 // FIXME: This isn't precisely correct; the width/alignment should depend
683 // on the available types for the target
684 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000685 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000686 Align = Width;
687 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000688 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000689 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000690 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000691 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000692 case Type::BlockPointer: {
693 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
694 Width = Target.getPointerWidth(AS);
695 Align = Target.getPointerAlign(AS);
696 break;
697 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000698 case Type::LValueReference:
699 case Type::RValueReference: {
700 // alignof and sizeof should never enter this code path here, so we go
701 // the pointer route.
702 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
703 Width = Target.getPointerWidth(AS);
704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000707 case Type::Pointer: {
708 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000709 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000710 Align = Target.getPointerAlign(AS);
711 break;
712 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000713 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000714 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
715 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
716 // If we ever want to support other ABIs this needs to be abstracted.
717
Sebastian Redlf30208a2009-01-24 21:16:55 +0000718 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000719 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000720 getTypeInfo(getPointerDiffType());
721 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000722 if (Pointee->isFunctionType())
723 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000724 Align = PtrDiffInfo.second;
725 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000726 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000727 case Type::Complex: {
728 // Complex types have the same alignment as their elements, but twice the
729 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000730 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000731 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000732 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000733 Align = EltInfo.second;
734 break;
735 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000736 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000737 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000738 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
739 Width = Layout.getSize();
740 Align = Layout.getAlignment();
741 break;
742 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000743 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000744 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000745 const TagType *TT = cast<TagType>(T);
746
747 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000748 Width = 1;
749 Align = 1;
750 break;
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Daniel Dunbar1d751182008-11-08 05:48:37 +0000753 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000754 return getTypeInfo(ET->getDecl()->getIntegerType());
755
Daniel Dunbar1d751182008-11-08 05:48:37 +0000756 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000757 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
758 Width = Layout.getSize();
759 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000760 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000761 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000762
Chris Lattner9fcfe922009-10-22 05:17:15 +0000763 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000764 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
765 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000766
Chris Lattner9fcfe922009-10-22 05:17:15 +0000767 case Type::Elaborated:
768 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
769 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000770
Douglas Gregor18857642009-04-30 17:32:17 +0000771 case Type::Typedef: {
772 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000773 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000774 Align = std::max(Aligned->getMaxAlignment(),
775 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000776 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
777 } else
778 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000779 break;
Chris Lattner71763312008-04-06 22:05:18 +0000780 }
Douglas Gregor18857642009-04-30 17:32:17 +0000781
782 case Type::TypeOfExpr:
783 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
784 .getTypePtr());
785
786 case Type::TypeOf:
787 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
788
Anders Carlsson395b4752009-06-24 19:06:50 +0000789 case Type::Decltype:
790 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
791 .getTypePtr());
792
Douglas Gregor18857642009-04-30 17:32:17 +0000793 case Type::QualifiedName:
794 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Douglas Gregor18857642009-04-30 17:32:17 +0000796 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000797 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000798 "Cannot request the size of a dependent type");
799 // FIXME: this is likely to be wrong once we support template
800 // aliases, since a template alias could refer to a typedef that
801 // has an __aligned__ attribute on it.
802 return getTypeInfo(getCanonicalType(T));
803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Chris Lattner464175b2007-07-18 17:52:12 +0000805 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000806 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000807}
808
Chris Lattner34ebde42009-01-27 18:08:34 +0000809/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
810/// type for the current target in bits. This can be different than the ABI
811/// alignment in cases where it is beneficial for performance to overalign
812/// a data type.
813unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
814 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000815
816 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000817 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000818 T = CT->getElementType().getTypePtr();
819 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
820 T->isSpecificBuiltinType(BuiltinType::LongLong))
821 return std::max(ABIAlign, (unsigned)getTypeSize(T));
822
Chris Lattner34ebde42009-01-27 18:08:34 +0000823 return ABIAlign;
824}
825
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000826static void CollectLocalObjCIvars(ASTContext *Ctx,
827 const ObjCInterfaceDecl *OI,
828 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000829 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
830 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000831 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000832 if (!IVDecl->isInvalidDecl())
833 Fields.push_back(cast<FieldDecl>(IVDecl));
834 }
835}
836
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000837void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
838 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
839 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
840 CollectObjCIvars(SuperClass, Fields);
841 CollectLocalObjCIvars(this, OI, Fields);
842}
843
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000844/// ShallowCollectObjCIvars -
845/// Collect all ivars, including those synthesized, in the current class.
846///
847void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
848 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
849 bool CollectSynthesized) {
850 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
851 E = OI->ivar_end(); I != E; ++I) {
852 Ivars.push_back(*I);
853 }
854 if (CollectSynthesized)
855 CollectSynthesizedIvars(OI, Ivars);
856}
857
Fariborz Jahanian98200742009-05-12 18:14:29 +0000858void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
859 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000860 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
861 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000862 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
863 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Fariborz Jahanian98200742009-05-12 18:14:29 +0000865 // Also look into nested protocols.
866 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
867 E = PD->protocol_end(); P != E; ++P)
868 CollectProtocolSynthesizedIvars(*P, Ivars);
869}
870
871/// CollectSynthesizedIvars -
872/// This routine collect synthesized ivars for the designated class.
873///
874void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000876 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
877 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000878 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
879 Ivars.push_back(Ivar);
880 }
881 // Also look into interface's protocol list for properties declared
882 // in the protocol and whose ivars are synthesized.
883 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
884 PE = OI->protocol_end(); P != PE; ++P) {
885 ObjCProtocolDecl *PD = (*P);
886 CollectProtocolSynthesizedIvars(PD, Ivars);
887 }
888}
889
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000890/// CollectInheritedProtocols - Collect all protocols in current class and
891/// those inherited by it.
892void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
893 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
894 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
895 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
896 PE = OI->protocol_end(); P != PE; ++P) {
897 ObjCProtocolDecl *Proto = (*P);
898 Protocols.push_back(Proto);
899 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
900 PE = Proto->protocol_end(); P != PE; ++P)
901 CollectInheritedProtocols(*P, Protocols);
902 }
903
904 // Categories of this Interface.
905 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
906 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
907 CollectInheritedProtocols(CDeclChain, Protocols);
908 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
909 while (SD) {
910 CollectInheritedProtocols(SD, Protocols);
911 SD = SD->getSuperClass();
912 }
913 return;
914 }
915 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
916 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
917 PE = OC->protocol_end(); P != PE; ++P) {
918 ObjCProtocolDecl *Proto = (*P);
919 Protocols.push_back(Proto);
920 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
921 PE = Proto->protocol_end(); P != PE; ++P)
922 CollectInheritedProtocols(*P, Protocols);
923 }
924 return;
925 }
926 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
927 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
928 PE = OP->protocol_end(); P != PE; ++P) {
929 ObjCProtocolDecl *Proto = (*P);
930 Protocols.push_back(Proto);
931 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
932 PE = Proto->protocol_end(); P != PE; ++P)
933 CollectInheritedProtocols(*P, Protocols);
934 }
935 return;
936 }
937}
938
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000939unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
940 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000941 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
942 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000943 if ((*I)->getPropertyIvarDecl())
944 ++count;
945
946 // Also look into nested protocols.
947 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
948 E = PD->protocol_end(); P != E; ++P)
949 count += CountProtocolSynthesizedIvars(*P);
950 return count;
951}
952
Mike Stump1eb44332009-09-09 15:08:12 +0000953unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000954 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000955 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
956 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000957 if ((*I)->getPropertyIvarDecl())
958 ++count;
959 }
960 // Also look into interface's protocol list for properties declared
961 // in the protocol and whose ivars are synthesized.
962 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
963 PE = OI->protocol_end(); P != PE; ++P) {
964 ObjCProtocolDecl *PD = (*P);
965 count += CountProtocolSynthesizedIvars(PD);
966 }
967 return count;
968}
969
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000970/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
971ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
973 I = ObjCImpls.find(D);
974 if (I != ObjCImpls.end())
975 return cast<ObjCImplementationDecl>(I->second);
976 return 0;
977}
978/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
979ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
980 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
981 I = ObjCImpls.find(D);
982 if (I != ObjCImpls.end())
983 return cast<ObjCCategoryImplDecl>(I->second);
984 return 0;
985}
986
987/// \brief Set the implementation of ObjCInterfaceDecl.
988void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
989 ObjCImplementationDecl *ImplD) {
990 assert(IFaceD && ImplD && "Passed null params");
991 ObjCImpls[IFaceD] = ImplD;
992}
993/// \brief Set the implementation of ObjCCategoryDecl.
994void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
995 ObjCCategoryImplDecl *ImplD) {
996 assert(CatD && ImplD && "Passed null params");
997 ObjCImpls[CatD] = ImplD;
998}
999
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001000/// \brief Allocate an uninitialized DeclaratorInfo.
1001///
1002/// The caller should initialize the memory held by DeclaratorInfo using
1003/// the TypeLoc wrappers.
1004///
1005/// \param T the type that will be the basis for type source info. This type
1006/// should refer to how the declarator was written in source code, not to
1007/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +00001008DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
1009 unsigned DataSize) {
1010 if (!DataSize)
1011 DataSize = TypeLoc::getFullDataSizeForType(T);
1012 else
1013 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1014 "incorrect data size provided to CreateDeclaratorInfo!");
1015
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001016 DeclaratorInfo *DInfo =
1017 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1018 new (DInfo) DeclaratorInfo(T);
1019 return DInfo;
1020}
1021
John McCalla4eb74d2009-10-23 21:14:09 +00001022DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1023 SourceLocation L) {
1024 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1025 DI->getTypeLoc().initialize(L);
1026 return DI;
1027}
1028
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001029/// getInterfaceLayoutImpl - Get or compute information about the
1030/// layout of the given interface.
1031///
1032/// \param Impl - If given, also include the layout of the interface's
1033/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001034const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001035ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1036 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001037 assert(!D->isForwardDecl() && "Invalid interface decl!");
1038
Devang Patel44a3dde2008-06-04 21:54:36 +00001039 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001040 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001041 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1042 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1043 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001044
Daniel Dunbar453addb2009-05-03 11:16:44 +00001045 // Add in synthesized ivar count if laying out an implementation.
1046 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001047 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001048 unsigned SynthCount = CountSynthesizedIvars(D);
1049 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001050 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001051 // entry. Note we can't cache this because we simply free all
1052 // entries later; however we shouldn't look up implementations
1053 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001054 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001055 return getObjCLayout(D, 0);
1056 }
1057
Mike Stump1eb44332009-09-09 15:08:12 +00001058 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001059 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1060 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Devang Patel44a3dde2008-06-04 21:54:36 +00001062 return *NewEntry;
1063}
1064
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001065const ASTRecordLayout &
1066ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1067 return getObjCLayout(D, 0);
1068}
1069
1070const ASTRecordLayout &
1071ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1072 return getObjCLayout(D->getClassInterface(), D);
1073}
1074
Devang Patel88a981b2007-11-01 19:11:01 +00001075/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001076/// specified record (struct/union/class), which indicates its size and field
1077/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001078const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001079 D = D->getDefinition(*this);
1080 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001081
Chris Lattner464175b2007-07-18 17:52:12 +00001082 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001083 // Note that we can't save a reference to the entry because this function
1084 // is recursive.
1085 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001086 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001087
Mike Stump1eb44332009-09-09 15:08:12 +00001088 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001089 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001090 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Chris Lattner5d2a6302007-07-18 18:26:58 +00001092 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001093}
1094
Chris Lattnera7674d82007-07-13 22:13:22 +00001095//===----------------------------------------------------------------------===//
1096// Type creation/memoization methods
1097//===----------------------------------------------------------------------===//
1098
John McCall0953e762009-09-24 19:53:00 +00001099QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1100 unsigned Fast = Quals.getFastQualifiers();
1101 Quals.removeFastQualifiers();
1102
1103 // Check if we've already instantiated this type.
1104 llvm::FoldingSetNodeID ID;
1105 ExtQuals::Profile(ID, TypeNode, Quals);
1106 void *InsertPos = 0;
1107 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1108 assert(EQ->getQualifiers() == Quals);
1109 QualType T = QualType(EQ, Fast);
1110 return T;
1111 }
1112
John McCall6b304a02009-09-24 23:30:46 +00001113 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001114 ExtQualNodes.InsertNode(New, InsertPos);
1115 QualType T = QualType(New, Fast);
1116 return T;
1117}
1118
1119QualType ASTContext::getVolatileType(QualType T) {
1120 QualType CanT = getCanonicalType(T);
1121 if (CanT.isVolatileQualified()) return T;
1122
1123 QualifierCollector Quals;
1124 const Type *TypeNode = Quals.strip(T);
1125 Quals.addVolatile();
1126
1127 return getExtQualType(TypeNode, Quals);
1128}
1129
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001130QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001131 QualType CanT = getCanonicalType(T);
1132 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001133 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001134
John McCall0953e762009-09-24 19:53:00 +00001135 // If we are composing extended qualifiers together, merge together
1136 // into one ExtQuals node.
1137 QualifierCollector Quals;
1138 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
John McCall0953e762009-09-24 19:53:00 +00001140 // If this type already has an address space specified, it cannot get
1141 // another one.
1142 assert(!Quals.hasAddressSpace() &&
1143 "Type cannot be in multiple addr spaces!");
1144 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
John McCall0953e762009-09-24 19:53:00 +00001146 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001147}
1148
Chris Lattnerb7d25532009-02-18 22:53:11 +00001149QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001150 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001151 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001152 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001153 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001155 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001156 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001157 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001158 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1159 return getPointerType(ResultType);
1160 }
1161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
John McCall0953e762009-09-24 19:53:00 +00001163 // If we are composing extended qualifiers together, merge together
1164 // into one ExtQuals node.
1165 QualifierCollector Quals;
1166 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
John McCall0953e762009-09-24 19:53:00 +00001168 // If this type already has an ObjCGC specified, it cannot get
1169 // another one.
1170 assert(!Quals.hasObjCGCAttr() &&
1171 "Type cannot have multiple ObjCGCs!");
1172 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001173
John McCall0953e762009-09-24 19:53:00 +00001174 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001175}
Chris Lattnera7674d82007-07-13 22:13:22 +00001176
Mike Stump24556362009-07-25 21:26:53 +00001177QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001178 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001179 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001180 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001181 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001182 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001183 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001184 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001185 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001186 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001187 } else {
1188 assert (T->isFunctionType()
1189 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001191 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1192 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001193 } else {
1194 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1195 ResultType
1196 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1197 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1198 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1199 F->getNumExceptions(), F->exception_begin(), true);
1200 }
Mike Stump24556362009-07-25 21:26:53 +00001201 }
John McCall0953e762009-09-24 19:53:00 +00001202
Douglas Gregora4923eb2009-11-16 21:35:15 +00001203 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001204}
1205
Reid Spencer5f016e22007-07-11 17:01:13 +00001206/// getComplexType - Return the uniqued reference to the type for a complex
1207/// number with the specified element type.
1208QualType ASTContext::getComplexType(QualType T) {
1209 // Unique pointers, to guarantee there is only one pointer of a particular
1210 // structure.
1211 llvm::FoldingSetNodeID ID;
1212 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 void *InsertPos = 0;
1215 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1216 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // If the pointee type isn't canonical, this won't be a canonical type either,
1219 // so fill in the canonical type field.
1220 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001221 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001222 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 // Get the new insert position for the node we care about.
1225 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001226 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 }
John McCall6b304a02009-09-24 23:30:46 +00001228 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 Types.push_back(New);
1230 ComplexTypes.InsertNode(New, InsertPos);
1231 return QualType(New, 0);
1232}
1233
Eli Friedmanf98aba32009-02-13 02:31:07 +00001234QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1235 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1236 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1237 FixedWidthIntType *&Entry = Map[Width];
1238 if (!Entry)
1239 Entry = new FixedWidthIntType(Width, Signed);
1240 return QualType(Entry, 0);
1241}
Reid Spencer5f016e22007-07-11 17:01:13 +00001242
1243/// getPointerType - Return the uniqued reference to the type for a pointer to
1244/// the specified type.
1245QualType ASTContext::getPointerType(QualType T) {
1246 // Unique pointers, to guarantee there is only one pointer of a particular
1247 // structure.
1248 llvm::FoldingSetNodeID ID;
1249 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 void *InsertPos = 0;
1252 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1253 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 // If the pointee type isn't canonical, this won't be a canonical type either,
1256 // so fill in the canonical type field.
1257 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001258 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001259 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // Get the new insert position for the node we care about.
1262 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001263 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 }
John McCall6b304a02009-09-24 23:30:46 +00001265 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 Types.push_back(New);
1267 PointerTypes.InsertNode(New, InsertPos);
1268 return QualType(New, 0);
1269}
1270
Mike Stump1eb44332009-09-09 15:08:12 +00001271/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001272/// a pointer to the specified block.
1273QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001274 assert(T->isFunctionType() && "block of function types only");
1275 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001276 // structure.
1277 llvm::FoldingSetNodeID ID;
1278 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Steve Naroff5618bd42008-08-27 16:04:49 +00001280 void *InsertPos = 0;
1281 if (BlockPointerType *PT =
1282 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1283 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
1285 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001286 // type either so fill in the canonical type field.
1287 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001288 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001289 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Steve Naroff5618bd42008-08-27 16:04:49 +00001291 // Get the new insert position for the node we care about.
1292 BlockPointerType *NewIP =
1293 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001294 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001295 }
John McCall6b304a02009-09-24 23:30:46 +00001296 BlockPointerType *New
1297 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001298 Types.push_back(New);
1299 BlockPointerTypes.InsertNode(New, InsertPos);
1300 return QualType(New, 0);
1301}
1302
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303/// getLValueReferenceType - Return the uniqued reference to the type for an
1304/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001305QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001309 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001312 if (LValueReferenceType *RT =
1313 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315
John McCall54e14c42009-10-22 22:37:11 +00001316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // If the referencee type isn't canonical, this won't be a canonical type
1319 // either, so fill in the canonical type field.
1320 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001321 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1323 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001324
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001326 LValueReferenceType *NewIP =
1327 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001328 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 }
1330
John McCall6b304a02009-09-24 23:30:46 +00001331 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001332 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1333 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001335 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001336
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001337 return QualType(New, 0);
1338}
1339
1340/// getRValueReferenceType - Return the uniqued reference to the type for an
1341/// rvalue reference to the specified type.
1342QualType ASTContext::getRValueReferenceType(QualType T) {
1343 // Unique pointers, to guarantee there is only one pointer of a particular
1344 // structure.
1345 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001346 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001347
1348 void *InsertPos = 0;
1349 if (RValueReferenceType *RT =
1350 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1351 return QualType(RT, 0);
1352
John McCall54e14c42009-10-22 22:37:11 +00001353 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1354
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001355 // If the referencee type isn't canonical, this won't be a canonical type
1356 // either, so fill in the canonical type field.
1357 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001358 if (InnerRef || !T.isCanonical()) {
1359 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1360 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001361
1362 // Get the new insert position for the node we care about.
1363 RValueReferenceType *NewIP =
1364 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1365 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1366 }
1367
John McCall6b304a02009-09-24 23:30:46 +00001368 RValueReferenceType *New
1369 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001370 Types.push_back(New);
1371 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 return QualType(New, 0);
1373}
1374
Sebastian Redlf30208a2009-01-24 21:16:55 +00001375/// getMemberPointerType - Return the uniqued reference to the type for a
1376/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001377QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001378 // Unique pointers, to guarantee there is only one pointer of a particular
1379 // structure.
1380 llvm::FoldingSetNodeID ID;
1381 MemberPointerType::Profile(ID, T, Cls);
1382
1383 void *InsertPos = 0;
1384 if (MemberPointerType *PT =
1385 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1386 return QualType(PT, 0);
1387
1388 // If the pointee or class type isn't canonical, this won't be a canonical
1389 // type either, so fill in the canonical type field.
1390 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001391 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001392 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1393
1394 // Get the new insert position for the node we care about.
1395 MemberPointerType *NewIP =
1396 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1397 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1398 }
John McCall6b304a02009-09-24 23:30:46 +00001399 MemberPointerType *New
1400 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001401 Types.push_back(New);
1402 MemberPointerTypes.InsertNode(New, InsertPos);
1403 return QualType(New, 0);
1404}
1405
Mike Stump1eb44332009-09-09 15:08:12 +00001406/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001407/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001408QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001409 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001410 ArrayType::ArraySizeModifier ASM,
1411 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001412 assert((EltTy->isDependentType() ||
1413 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001414 "Constant array of VLAs is illegal!");
1415
Chris Lattner38aeec72009-05-13 04:12:56 +00001416 // Convert the array size into a canonical width matching the pointer size for
1417 // the target.
1418 llvm::APInt ArySize(ArySizeIn);
1419 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001422 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001425 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001426 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 // If the element type isn't canonical, this won't be a canonical type either,
1430 // so fill in the canonical type field.
1431 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001432 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001433 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001434 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001436 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001437 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001438 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
John McCall6b304a02009-09-24 23:30:46 +00001441 ConstantArrayType *New = new(*this,TypeAlignment)
1442 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001443 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 Types.push_back(New);
1445 return QualType(New, 0);
1446}
1447
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001448/// getVariableArrayType - Returns a non-unique reference to the type for a
1449/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001450QualType ASTContext::getVariableArrayType(QualType EltTy,
1451 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001452 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001453 unsigned EltTypeQuals,
1454 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001455 // Since we don't unique expressions, it isn't possible to unique VLA's
1456 // that have an expression provided for their size.
1457
John McCall6b304a02009-09-24 23:30:46 +00001458 VariableArrayType *New = new(*this, TypeAlignment)
1459 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001460
1461 VariableArrayTypes.push_back(New);
1462 Types.push_back(New);
1463 return QualType(New, 0);
1464}
1465
Douglas Gregor898574e2008-12-05 23:32:09 +00001466/// getDependentSizedArrayType - Returns a non-unique reference to
1467/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001468/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001469QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1470 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001471 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001472 unsigned EltTypeQuals,
1473 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001474 assert((!NumElts || NumElts->isTypeDependent() ||
1475 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001476 "Size must be type- or value-dependent!");
1477
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001478 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001479 DependentSizedArrayType *Canon = 0;
1480
1481 if (NumElts) {
1482 // Dependently-sized array types that do not have a specified
1483 // number of elements will have their sizes deduced from an
1484 // initializer.
1485 llvm::FoldingSetNodeID ID;
1486 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1487 EltTypeQuals, NumElts);
1488
1489 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1490 }
1491
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001492 DependentSizedArrayType *New;
1493 if (Canon) {
1494 // We already have a canonical version of this array type; use it as
1495 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001496 New = new (*this, TypeAlignment)
1497 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1498 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001499 } else {
1500 QualType CanonEltTy = getCanonicalType(EltTy);
1501 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001502 New = new (*this, TypeAlignment)
1503 DependentSizedArrayType(*this, EltTy, QualType(),
1504 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001505
1506 if (NumElts)
1507 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001508 } else {
1509 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1510 ASM, EltTypeQuals,
1511 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001512 New = new (*this, TypeAlignment)
1513 DependentSizedArrayType(*this, EltTy, Canon,
1514 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001515 }
1516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregor898574e2008-12-05 23:32:09 +00001518 Types.push_back(New);
1519 return QualType(New, 0);
1520}
1521
Eli Friedmanc5773c42008-02-15 18:16:39 +00001522QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1523 ArrayType::ArraySizeModifier ASM,
1524 unsigned EltTypeQuals) {
1525 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001526 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001527
1528 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001529 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001530 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1531 return QualType(ATP, 0);
1532
1533 // If the element type isn't canonical, this won't be a canonical type
1534 // either, so fill in the canonical type field.
1535 QualType Canonical;
1536
John McCall467b27b2009-10-22 20:10:53 +00001537 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001538 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001539 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001540
1541 // Get the new insert position for the node we care about.
1542 IncompleteArrayType *NewIP =
1543 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001544 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001545 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001546
John McCall6b304a02009-09-24 23:30:46 +00001547 IncompleteArrayType *New = new (*this, TypeAlignment)
1548 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001549
1550 IncompleteArrayTypes.InsertNode(New, InsertPos);
1551 Types.push_back(New);
1552 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001553}
1554
Steve Naroff73322922007-07-18 18:00:27 +00001555/// getVectorType - Return the unique reference to a vector type of
1556/// the specified element type and size. VectorType must be a built-in type.
1557QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Chris Lattnerf52ab252008-04-06 22:59:24 +00001560 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001561 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 // Check if we've already instantiated a vector of this type.
1564 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001565 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 void *InsertPos = 0;
1567 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1568 return QualType(VTP, 0);
1569
1570 // If the element type isn't canonical, this won't be a canonical type either,
1571 // so fill in the canonical type field.
1572 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001573 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001574 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Get the new insert position for the node we care about.
1577 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001578 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 }
John McCall6b304a02009-09-24 23:30:46 +00001580 VectorType *New = new (*this, TypeAlignment)
1581 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 VectorTypes.InsertNode(New, InsertPos);
1583 Types.push_back(New);
1584 return QualType(New, 0);
1585}
1586
Nate Begeman213541a2008-04-18 23:10:10 +00001587/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001588/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001589QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001590 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Chris Lattnerf52ab252008-04-06 22:59:24 +00001592 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001593 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Steve Naroff73322922007-07-18 18:00:27 +00001595 // Check if we've already instantiated a vector of this type.
1596 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001597 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001598 void *InsertPos = 0;
1599 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1600 return QualType(VTP, 0);
1601
1602 // If the element type isn't canonical, this won't be a canonical type either,
1603 // so fill in the canonical type field.
1604 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001605 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001606 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Steve Naroff73322922007-07-18 18:00:27 +00001608 // Get the new insert position for the node we care about.
1609 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001610 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001611 }
John McCall6b304a02009-09-24 23:30:46 +00001612 ExtVectorType *New = new (*this, TypeAlignment)
1613 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001614 VectorTypes.InsertNode(New, InsertPos);
1615 Types.push_back(New);
1616 return QualType(New, 0);
1617}
1618
Mike Stump1eb44332009-09-09 15:08:12 +00001619QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001620 Expr *SizeExpr,
1621 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001622 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001623 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001624 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001626 void *InsertPos = 0;
1627 DependentSizedExtVectorType *Canon
1628 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1629 DependentSizedExtVectorType *New;
1630 if (Canon) {
1631 // We already have a canonical version of this array type; use it as
1632 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001633 New = new (*this, TypeAlignment)
1634 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1635 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001636 } else {
1637 QualType CanonVecTy = getCanonicalType(vecType);
1638 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001639 New = new (*this, TypeAlignment)
1640 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1641 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001642 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1643 } else {
1644 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1645 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001646 New = new (*this, TypeAlignment)
1647 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001648 }
1649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001651 Types.push_back(New);
1652 return QualType(New, 0);
1653}
1654
Douglas Gregor72564e72009-02-26 23:50:07 +00001655/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001656///
Mike Stump24556362009-07-25 21:26:53 +00001657QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // Unique functions, to guarantee there is only one function of a particular
1659 // structure.
1660 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001661 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001664 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001665 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001669 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001670 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001673 FunctionNoProtoType *NewIP =
1674 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001675 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
John McCall6b304a02009-09-24 23:30:46 +00001678 FunctionNoProtoType *New = new (*this, TypeAlignment)
1679 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001681 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 return QualType(New, 0);
1683}
1684
1685/// getFunctionType - Return a normal function type with a typed argument
1686/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001687QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001688 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001689 unsigned TypeQuals, bool hasExceptionSpec,
1690 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001691 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 // Unique functions, to guarantee there is only one function of a particular
1693 // structure.
1694 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001696 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001697 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698
1699 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001700 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001701 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001703
1704 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001705 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001707 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 isCanonical = false;
1709
1710 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001711 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 QualType Canonical;
1713 if (!isCanonical) {
1714 llvm::SmallVector<QualType, 16> CanonicalArgs;
1715 CanonicalArgs.reserve(NumArgs);
1716 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001717 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001718
Chris Lattnerf52ab252008-04-06 22:59:24 +00001719 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001720 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001721 isVariadic, TypeQuals, false,
1722 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001723
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001725 FunctionProtoType *NewIP =
1726 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001727 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001729
Douglas Gregor72564e72009-02-26 23:50:07 +00001730 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001731 // for two variable size arrays (for parameter and exception types) at the
1732 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001733 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001734 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1735 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001736 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001737 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001738 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001739 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001741 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 return QualType(FTP, 0);
1743}
1744
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001745/// getTypeDeclType - Return the unique reference to the type for the
1746/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001747QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001748 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001749 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001751 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001752 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001753 else if (isa<TemplateTypeParmDecl>(Decl)) {
1754 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001755 } else if (ObjCInterfaceDecl *ObjCInterface
1756 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001757 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001758
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001759 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001760 if (PrevDecl)
1761 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001762 else
John McCall6b304a02009-09-24 23:30:46 +00001763 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001764 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001765 if (PrevDecl)
1766 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001767 else
John McCall6b304a02009-09-24 23:30:46 +00001768 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001769 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001770 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001771
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001772 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001773 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001774}
1775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776/// getTypedefType - Return the unique reference to the type for the
1777/// specified typename decl.
1778QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1779 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Chris Lattnerf52ab252008-04-06 22:59:24 +00001781 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001782 Decl->TypeForDecl = new(*this, TypeAlignment)
1783 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 Types.push_back(Decl->TypeForDecl);
1785 return QualType(Decl->TypeForDecl, 0);
1786}
1787
John McCall49a832b2009-10-18 09:09:24 +00001788/// \brief Retrieve a substitution-result type.
1789QualType
1790ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1791 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001792 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001793 && "replacement types must always be canonical");
1794
1795 llvm::FoldingSetNodeID ID;
1796 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1797 void *InsertPos = 0;
1798 SubstTemplateTypeParmType *SubstParm
1799 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1800
1801 if (!SubstParm) {
1802 SubstParm = new (*this, TypeAlignment)
1803 SubstTemplateTypeParmType(Parm, Replacement);
1804 Types.push_back(SubstParm);
1805 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1806 }
1807
1808 return QualType(SubstParm, 0);
1809}
1810
Douglas Gregorfab9d672009-02-05 23:33:38 +00001811/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001812/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001813/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001814QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001815 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001816 IdentifierInfo *Name) {
1817 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001818 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001819 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001820 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001821 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1822
1823 if (TypeParm)
1824 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001826 if (Name) {
1827 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001828 TypeParm = new (*this, TypeAlignment)
1829 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001830 } else
John McCall6b304a02009-09-24 23:30:46 +00001831 TypeParm = new (*this, TypeAlignment)
1832 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001833
1834 Types.push_back(TypeParm);
1835 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1836
1837 return QualType(TypeParm, 0);
1838}
1839
Mike Stump1eb44332009-09-09 15:08:12 +00001840QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001841ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001842 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001843 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001844 unsigned NumArgs = Args.size();
1845
John McCall833ca992009-10-29 08:12:44 +00001846 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1847 ArgVec.reserve(NumArgs);
1848 for (unsigned i = 0; i != NumArgs; ++i)
1849 ArgVec.push_back(Args[i].getArgument());
1850
1851 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1852}
1853
1854QualType
1855ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001856 const TemplateArgument *Args,
1857 unsigned NumArgs,
1858 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001859 if (!Canon.isNull())
1860 Canon = getCanonicalType(Canon);
1861 else {
1862 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001863 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1864 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1865 CanonArgs.reserve(NumArgs);
1866 for (unsigned I = 0; I != NumArgs; ++I)
1867 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1868
1869 // Determine whether this canonical template specialization type already
1870 // exists.
1871 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001872 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001873 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001874
1875 void *InsertPos = 0;
1876 TemplateSpecializationType *Spec
1877 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregor1275ae02009-07-28 23:00:59 +00001879 if (!Spec) {
1880 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001881 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001882 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001883 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001884 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001885 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001886 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001887 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001888 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001889 }
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregorb88e8882009-07-30 17:40:51 +00001891 if (Canon.isNull())
1892 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001893 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001894 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001895 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001896
Douglas Gregor1275ae02009-07-28 23:00:59 +00001897 // Allocate the (non-canonical) template specialization type, but don't
1898 // try to unique it: these types typically have location information that
1899 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001900 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001901 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001902 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001903 TemplateSpecializationType *Spec
1904 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001905 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregor55f6b142009-02-09 18:46:07 +00001907 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001908 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001909}
1910
Mike Stump1eb44332009-09-09 15:08:12 +00001911QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001912ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001913 QualType NamedType) {
1914 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001915 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001916
1917 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001918 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001919 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1920 if (T)
1921 return QualType(T, 0);
1922
Mike Stump1eb44332009-09-09 15:08:12 +00001923 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001924 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001925 Types.push_back(T);
1926 QualifiedNameTypes.InsertNode(T, InsertPos);
1927 return QualType(T, 0);
1928}
1929
Mike Stump1eb44332009-09-09 15:08:12 +00001930QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001931 const IdentifierInfo *Name,
1932 QualType Canon) {
1933 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1934
1935 if (Canon.isNull()) {
1936 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1937 if (CanonNNS != NNS)
1938 Canon = getTypenameType(CanonNNS, Name);
1939 }
1940
1941 llvm::FoldingSetNodeID ID;
1942 TypenameType::Profile(ID, NNS, Name);
1943
1944 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001945 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001946 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1947 if (T)
1948 return QualType(T, 0);
1949
1950 T = new (*this) TypenameType(NNS, Name, Canon);
1951 Types.push_back(T);
1952 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001953 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001954}
1955
Mike Stump1eb44332009-09-09 15:08:12 +00001956QualType
1957ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001958 const TemplateSpecializationType *TemplateId,
1959 QualType Canon) {
1960 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1961
1962 if (Canon.isNull()) {
1963 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1964 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1965 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1966 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001967 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001968 assert(CanonTemplateId &&
1969 "Canonical type must also be a template specialization type");
1970 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1971 }
1972 }
1973
1974 llvm::FoldingSetNodeID ID;
1975 TypenameType::Profile(ID, NNS, TemplateId);
1976
1977 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001978 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001979 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1980 if (T)
1981 return QualType(T, 0);
1982
1983 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1984 Types.push_back(T);
1985 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001986 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001987}
1988
John McCall7da24312009-09-05 00:15:47 +00001989QualType
1990ASTContext::getElaboratedType(QualType UnderlyingType,
1991 ElaboratedType::TagKind Tag) {
1992 llvm::FoldingSetNodeID ID;
1993 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
John McCall7da24312009-09-05 00:15:47 +00001995 void *InsertPos = 0;
1996 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 if (T)
1998 return QualType(T, 0);
1999
2000 QualType Canon = getCanonicalType(UnderlyingType);
2001
2002 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2003 Types.push_back(T);
2004 ElaboratedTypes.InsertNode(T, InsertPos);
2005 return QualType(T, 0);
2006}
2007
Chris Lattner88cb27a2008-04-07 04:56:42 +00002008/// CmpProtocolNames - Comparison predicate for sorting protocols
2009/// alphabetically.
2010static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2011 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002012 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002013}
2014
John McCall54e14c42009-10-22 22:37:11 +00002015static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2016 unsigned NumProtocols) {
2017 if (NumProtocols == 0) return true;
2018
2019 for (unsigned i = 1; i != NumProtocols; ++i)
2020 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2021 return false;
2022 return true;
2023}
2024
2025static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002026 unsigned &NumProtocols) {
2027 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Chris Lattner88cb27a2008-04-07 04:56:42 +00002029 // Sort protocols, keyed by name.
2030 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2031
2032 // Remove duplicates.
2033 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2034 NumProtocols = ProtocolsEnd-Protocols;
2035}
2036
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002037/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2038/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002039QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002040 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002041 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002042 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002043 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002044
2045 void *InsertPos = 0;
2046 if (ObjCObjectPointerType *QT =
2047 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2048 return QualType(QT, 0);
2049
John McCall54e14c42009-10-22 22:37:11 +00002050 // Sort the protocol list alphabetically to canonicalize it.
2051 QualType Canonical;
2052 if (!InterfaceT.isCanonical() ||
2053 !areSortedAndUniqued(Protocols, NumProtocols)) {
2054 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2055 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2056 unsigned UniqueCount = NumProtocols;
2057
2058 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2059 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2060
2061 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2062 &Sorted[0], UniqueCount);
2063 } else {
2064 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2065 Protocols, NumProtocols);
2066 }
2067
2068 // Regenerate InsertPos.
2069 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2070 }
2071
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002072 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002073 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002074 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002076 Types.push_back(QType);
2077 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2078 return QualType(QType, 0);
2079}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002080
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002081/// getObjCInterfaceType - Return the unique reference to the type for the
2082/// specified ObjC interface decl. The list of protocols is optional.
2083QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002084 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002085 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002086 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002088 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002089 if (ObjCInterfaceType *QT =
2090 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002091 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002092
John McCall54e14c42009-10-22 22:37:11 +00002093 // Sort the protocol list alphabetically to canonicalize it.
2094 QualType Canonical;
2095 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2096 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2097 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2098
2099 unsigned UniqueCount = NumProtocols;
2100 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2101
2102 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2103
2104 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 }
2106
John McCall6b304a02009-09-24 23:30:46 +00002107 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002108 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002109 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002110
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002111 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002112 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002113 return QualType(QType, 0);
2114}
2115
Douglas Gregor72564e72009-02-26 23:50:07 +00002116/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2117/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002118/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002119/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002120/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002121QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002122 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002123 if (tofExpr->isTypeDependent()) {
2124 llvm::FoldingSetNodeID ID;
2125 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregorb1975722009-07-30 23:18:24 +00002127 void *InsertPos = 0;
2128 DependentTypeOfExprType *Canon
2129 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2130 if (Canon) {
2131 // We already have a "canonical" version of an identical, dependent
2132 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002133 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002134 QualType((TypeOfExprType*)Canon, 0));
2135 }
2136 else {
2137 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002138 Canon
2139 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002140 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2141 toe = Canon;
2142 }
2143 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002144 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002145 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002146 }
Steve Naroff9752f252007-08-01 18:02:17 +00002147 Types.push_back(toe);
2148 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002149}
2150
Steve Naroff9752f252007-08-01 18:02:17 +00002151/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2152/// TypeOfType AST's. The only motivation to unique these nodes would be
2153/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002154/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002155/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002156QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002157 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002158 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002159 Types.push_back(tot);
2160 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002161}
2162
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002163/// getDecltypeForExpr - Given an expr, will return the decltype for that
2164/// expression, according to the rules in C++0x [dcl.type.simple]p4
2165static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002166 if (e->isTypeDependent())
2167 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002169 // If e is an id expression or a class member access, decltype(e) is defined
2170 // as the type of the entity named by e.
2171 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2172 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2173 return VD->getType();
2174 }
2175 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2176 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2177 return FD->getType();
2178 }
2179 // If e is a function call or an invocation of an overloaded operator,
2180 // (parentheses around e are ignored), decltype(e) is defined as the
2181 // return type of that function.
2182 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2183 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002185 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002186
2187 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002188 // defined as T&, otherwise decltype(e) is defined as T.
2189 if (e->isLvalue(Context) == Expr::LV_Valid)
2190 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002192 return T;
2193}
2194
Anders Carlsson395b4752009-06-24 19:06:50 +00002195/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2196/// DecltypeType AST's. The only motivation to unique these nodes would be
2197/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002198/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002199/// on canonical type's (which are always unique).
2200QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002201 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002202 if (e->isTypeDependent()) {
2203 llvm::FoldingSetNodeID ID;
2204 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002206 void *InsertPos = 0;
2207 DependentDecltypeType *Canon
2208 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2209 if (Canon) {
2210 // We already have a "canonical" version of an equivalent, dependent
2211 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002212 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002213 QualType((DecltypeType*)Canon, 0));
2214 }
2215 else {
2216 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002217 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002218 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2219 dt = Canon;
2220 }
2221 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002222 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002223 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002224 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002225 Types.push_back(dt);
2226 return QualType(dt, 0);
2227}
2228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229/// getTagDeclType - Return the unique reference to the type for the
2230/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002231QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002232 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002233 // FIXME: What is the design on getTagDeclType when it requires casting
2234 // away const? mutable?
2235 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002236}
2237
Mike Stump1eb44332009-09-09 15:08:12 +00002238/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2239/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2240/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002241QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002242 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002243}
2244
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002245/// getSignedWCharType - Return the type of "signed wchar_t".
2246/// Used when in C++, as a GCC extension.
2247QualType ASTContext::getSignedWCharType() const {
2248 // FIXME: derive from "Target" ?
2249 return WCharTy;
2250}
2251
2252/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2253/// Used when in C++, as a GCC extension.
2254QualType ASTContext::getUnsignedWCharType() const {
2255 // FIXME: derive from "Target" ?
2256 return UnsignedIntTy;
2257}
2258
Chris Lattner8b9023b2007-07-13 03:05:23 +00002259/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2260/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2261QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002262 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002263}
2264
Chris Lattnere6327742008-04-02 05:18:44 +00002265//===----------------------------------------------------------------------===//
2266// Type Operators
2267//===----------------------------------------------------------------------===//
2268
John McCall54e14c42009-10-22 22:37:11 +00002269CanQualType ASTContext::getCanonicalParamType(QualType T) {
2270 // Push qualifiers into arrays, and then discard any remaining
2271 // qualifiers.
2272 T = getCanonicalType(T);
2273 const Type *Ty = T.getTypePtr();
2274
2275 QualType Result;
2276 if (isa<ArrayType>(Ty)) {
2277 Result = getArrayDecayedType(QualType(Ty,0));
2278 } else if (isa<FunctionType>(Ty)) {
2279 Result = getPointerType(QualType(Ty, 0));
2280 } else {
2281 Result = QualType(Ty, 0);
2282 }
2283
2284 return CanQualType::CreateUnsafe(Result);
2285}
2286
Chris Lattner77c96472008-04-06 22:41:35 +00002287/// getCanonicalType - Return the canonical (structural) type corresponding to
2288/// the specified potentially non-canonical type. The non-canonical version
2289/// of a type may have many "decorated" versions of types. Decorators can
2290/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2291/// to be free of any of these, allowing two canonical types to be compared
2292/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002293CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002294 QualifierCollector Quals;
2295 const Type *Ptr = Quals.strip(T);
2296 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002297
John McCall0953e762009-09-24 19:53:00 +00002298 // The canonical internal type will be the canonical type *except*
2299 // that we push type qualifiers down through array types.
2300
2301 // If there are no new qualifiers to push down, stop here.
2302 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002303 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002304
John McCall0953e762009-09-24 19:53:00 +00002305 // If the type qualifiers are on an array type, get the canonical
2306 // type of the array with the qualifiers applied to the element
2307 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002308 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2309 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002310 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002312 // Get the canonical version of the element with the extra qualifiers on it.
2313 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002314 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002315 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002317 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002318 return CanQualType::CreateUnsafe(
2319 getConstantArrayType(NewEltTy, CAT->getSize(),
2320 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002321 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002322 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002323 return CanQualType::CreateUnsafe(
2324 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002325 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Douglas Gregor898574e2008-12-05 23:32:09 +00002327 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002328 return CanQualType::CreateUnsafe(
2329 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002330 DSAT->getSizeExpr() ?
2331 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002332 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002333 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002334 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002335
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002336 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002337 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002338 VAT->getSizeExpr() ?
2339 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002340 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002341 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002342 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002343}
2344
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002345TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2346 // If this template name refers to a template, the canonical
2347 // template name merely stores the template itself.
2348 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002349 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002350
Mike Stump1eb44332009-09-09 15:08:12 +00002351 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002352 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002353 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2354 OverloadedFunctionDecl *CanonOvl = 0;
2355 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2356 FEnd = Ovl->function_end();
2357 F != FEnd; ++F) {
2358 Decl *Canon = F->get()->getCanonicalDecl();
2359 if (CanonOvl || Canon != F->get()) {
2360 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002361 CanonOvl = OverloadedFunctionDecl::Create(*this,
2362 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002363 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002365 CanonOvl->addOverload(
2366 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2367 }
2368 }
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002370 return TemplateName(CanonOvl? CanonOvl : Ovl);
2371 }
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002373 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2374 assert(DTN && "Non-dependent template names must refer to template decls.");
2375 return DTN->CanonicalTemplateName;
2376}
2377
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002378bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2379 X = getCanonicalTemplateName(X);
2380 Y = getCanonicalTemplateName(Y);
2381 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2382}
2383
Mike Stump1eb44332009-09-09 15:08:12 +00002384TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002385ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2386 switch (Arg.getKind()) {
2387 case TemplateArgument::Null:
2388 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor1275ae02009-07-28 23:00:59 +00002390 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002391 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Douglas Gregor1275ae02009-07-28 23:00:59 +00002393 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002394 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregor788cd062009-11-11 01:00:40 +00002396 case TemplateArgument::Template:
2397 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2398
Douglas Gregor1275ae02009-07-28 23:00:59 +00002399 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002400 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002401 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor1275ae02009-07-28 23:00:59 +00002403 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002404 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Douglas Gregor1275ae02009-07-28 23:00:59 +00002406 case TemplateArgument::Pack: {
2407 // FIXME: Allocate in ASTContext
2408 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2409 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002410 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002411 AEnd = Arg.pack_end();
2412 A != AEnd; (void)++A, ++Idx)
2413 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Douglas Gregor1275ae02009-07-28 23:00:59 +00002415 TemplateArgument Result;
2416 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2417 return Result;
2418 }
2419 }
2420
2421 // Silence GCC warning
2422 assert(false && "Unhandled template argument kind");
2423 return TemplateArgument();
2424}
2425
Douglas Gregord57959a2009-03-27 23:10:48 +00002426NestedNameSpecifier *
2427ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002428 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002429 return 0;
2430
2431 switch (NNS->getKind()) {
2432 case NestedNameSpecifier::Identifier:
2433 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002434 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002435 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2436 NNS->getAsIdentifier());
2437
2438 case NestedNameSpecifier::Namespace:
2439 // A namespace is canonical; build a nested-name-specifier with
2440 // this namespace and no prefix.
2441 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2442
2443 case NestedNameSpecifier::TypeSpec:
2444 case NestedNameSpecifier::TypeSpecWithTemplate: {
2445 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002446 return NestedNameSpecifier::Create(*this, 0,
2447 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002448 T.getTypePtr());
2449 }
2450
2451 case NestedNameSpecifier::Global:
2452 // The global specifier is canonical and unique.
2453 return NNS;
2454 }
2455
2456 // Required to silence a GCC warning
2457 return 0;
2458}
2459
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002460
2461const ArrayType *ASTContext::getAsArrayType(QualType T) {
2462 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002463 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002464 // Handle the common positive case fast.
2465 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2466 return AT;
2467 }
Mike Stump1eb44332009-09-09 15:08:12 +00002468
John McCall0953e762009-09-24 19:53:00 +00002469 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002470 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002471 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002472 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002473
John McCall0953e762009-09-24 19:53:00 +00002474 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002475 // implements C99 6.7.3p8: "If the specification of an array type includes
2476 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002478 // If we get here, we either have type qualifiers on the type, or we have
2479 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002480 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002481
John McCall0953e762009-09-24 19:53:00 +00002482 QualifierCollector Qs;
2483 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002485 // If we have a simple case, just return now.
2486 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002487 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002488 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002490 // Otherwise, we have an array and we have qualifiers on it. Push the
2491 // qualifiers into the array element type and return a new array type.
2492 // Get the canonical version of the element with the extra qualifiers on it.
2493 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002494 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002496 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2497 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2498 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002499 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002500 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2501 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2502 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002503 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002504
Mike Stump1eb44332009-09-09 15:08:12 +00002505 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002506 = dyn_cast<DependentSizedArrayType>(ATy))
2507 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002508 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002509 DSAT->getSizeExpr() ?
2510 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002511 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002512 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002513 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002515 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002516 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002517 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002518 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002519 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002520 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002521 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002522}
2523
2524
Chris Lattnere6327742008-04-02 05:18:44 +00002525/// getArrayDecayedType - Return the properly qualified result of decaying the
2526/// specified array type to a pointer. This operation is non-trivial when
2527/// handling typedefs etc. The canonical type of "T" must be an array type,
2528/// this returns a pointer to a properly qualified element of the array.
2529///
2530/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2531QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002532 // Get the element type with 'getAsArrayType' so that we don't lose any
2533 // typedefs in the element type of the array. This also handles propagation
2534 // of type qualifiers from the array type into the element type if present
2535 // (C99 6.7.3p8).
2536 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2537 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002539 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002540
2541 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002542 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002543}
2544
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002545QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002546 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002547 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002548 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002549 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2550 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002551 } else {
John McCall0953e762009-09-24 19:53:00 +00002552 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002553 }
2554 }
2555}
2556
Anders Carlssonfbbce492009-09-25 01:23:32 +00002557QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2558 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Anders Carlssonfbbce492009-09-25 01:23:32 +00002560 if (const ArrayType *AT = getAsArrayType(ElemTy))
2561 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Anders Carlsson6183a992008-12-21 03:44:36 +00002563 return ElemTy;
2564}
2565
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002566/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002567uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002568ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2569 uint64_t ElementCount = 1;
2570 do {
2571 ElementCount *= CA->getSize().getZExtValue();
2572 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2573 } while (CA);
2574 return ElementCount;
2575}
2576
Reid Spencer5f016e22007-07-11 17:01:13 +00002577/// getFloatingRank - Return a relative rank for floating point types.
2578/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002579static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002580 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002582
John McCall183700f2009-09-21 23:43:11 +00002583 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2584 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002585 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 case BuiltinType::Float: return FloatRank;
2587 case BuiltinType::Double: return DoubleRank;
2588 case BuiltinType::LongDouble: return LongDoubleRank;
2589 }
2590}
2591
Mike Stump1eb44332009-09-09 15:08:12 +00002592/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2593/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002594/// 'typeDomain' is a real floating point or complex type.
2595/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002596QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2597 QualType Domain) const {
2598 FloatingRank EltRank = getFloatingRank(Size);
2599 if (Domain->isComplexType()) {
2600 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002601 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002602 case FloatRank: return FloatComplexTy;
2603 case DoubleRank: return DoubleComplexTy;
2604 case LongDoubleRank: return LongDoubleComplexTy;
2605 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 }
Chris Lattner1361b112008-04-06 23:58:54 +00002607
2608 assert(Domain->isRealFloatingType() && "Unknown domain!");
2609 switch (EltRank) {
2610 default: assert(0 && "getFloatingRank(): illegal value for rank");
2611 case FloatRank: return FloatTy;
2612 case DoubleRank: return DoubleTy;
2613 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002614 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002615}
2616
Chris Lattner7cfeb082008-04-06 23:55:33 +00002617/// getFloatingTypeOrder - Compare the rank of the two specified floating
2618/// point types, ignoring the domain of the type (i.e. 'double' ==
2619/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002620/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002621int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2622 FloatingRank LHSR = getFloatingRank(LHS);
2623 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Chris Lattnera75cea32008-04-06 23:38:49 +00002625 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002626 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002627 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002628 return 1;
2629 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002630}
2631
Chris Lattnerf52ab252008-04-06 22:59:24 +00002632/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2633/// routine will assert if passed a built-in type that isn't an integer or enum,
2634/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002635unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002636 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002637 if (EnumType* ET = dyn_cast<EnumType>(T))
2638 T = ET->getDecl()->getIntegerType().getTypePtr();
2639
Eli Friedmana3426752009-07-05 23:44:27 +00002640 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2641 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2642
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002643 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2644 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2645
2646 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2647 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2648
Eli Friedmanf98aba32009-02-13 02:31:07 +00002649 // There are two things which impact the integer rank: the width, and
2650 // the ordering of builtins. The builtin ordering is encoded in the
2651 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002652 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002653 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002654
Chris Lattnerf52ab252008-04-06 22:59:24 +00002655 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002656 default: assert(0 && "getIntegerRank(): not a built-in integer");
2657 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002658 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002659 case BuiltinType::Char_S:
2660 case BuiltinType::Char_U:
2661 case BuiltinType::SChar:
2662 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002663 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002664 case BuiltinType::Short:
2665 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002666 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002667 case BuiltinType::Int:
2668 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002669 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002670 case BuiltinType::Long:
2671 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002672 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002673 case BuiltinType::LongLong:
2674 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002675 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002676 case BuiltinType::Int128:
2677 case BuiltinType::UInt128:
2678 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002679 }
2680}
2681
Eli Friedman04e83572009-08-20 04:21:42 +00002682/// \brief Whether this is a promotable bitfield reference according
2683/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2684///
2685/// \returns the type this bit-field will promote to, or NULL if no
2686/// promotion occurs.
2687QualType ASTContext::isPromotableBitField(Expr *E) {
2688 FieldDecl *Field = E->getBitField();
2689 if (!Field)
2690 return QualType();
2691
2692 QualType FT = Field->getType();
2693
2694 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2695 uint64_t BitWidth = BitWidthAP.getZExtValue();
2696 uint64_t IntSize = getTypeSize(IntTy);
2697 // GCC extension compatibility: if the bit-field size is less than or equal
2698 // to the size of int, it gets promoted no matter what its type is.
2699 // For instance, unsigned long bf : 4 gets promoted to signed int.
2700 if (BitWidth < IntSize)
2701 return IntTy;
2702
2703 if (BitWidth == IntSize)
2704 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2705
2706 // Types bigger than int are not subject to promotions, and therefore act
2707 // like the base type.
2708 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2709 // is ridiculous.
2710 return QualType();
2711}
2712
Eli Friedmana95d7572009-08-19 07:44:53 +00002713/// getPromotedIntegerType - Returns the type that Promotable will
2714/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2715/// integer type.
2716QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2717 assert(!Promotable.isNull());
2718 assert(Promotable->isPromotableIntegerType());
2719 if (Promotable->isSignedIntegerType())
2720 return IntTy;
2721 uint64_t PromotableSize = getTypeSize(Promotable);
2722 uint64_t IntSize = getTypeSize(IntTy);
2723 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2724 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2725}
2726
Mike Stump1eb44332009-09-09 15:08:12 +00002727/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002728/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002729/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002730int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002731 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2732 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002733 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Chris Lattnerf52ab252008-04-06 22:59:24 +00002735 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2736 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Chris Lattner7cfeb082008-04-06 23:55:33 +00002738 unsigned LHSRank = getIntegerRank(LHSC);
2739 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Chris Lattner7cfeb082008-04-06 23:55:33 +00002741 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2742 if (LHSRank == RHSRank) return 0;
2743 return LHSRank > RHSRank ? 1 : -1;
2744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Chris Lattner7cfeb082008-04-06 23:55:33 +00002746 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2747 if (LHSUnsigned) {
2748 // If the unsigned [LHS] type is larger, return it.
2749 if (LHSRank >= RHSRank)
2750 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Chris Lattner7cfeb082008-04-06 23:55:33 +00002752 // If the signed type can represent all values of the unsigned type, it
2753 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002754 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002755 return -1;
2756 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002757
Chris Lattner7cfeb082008-04-06 23:55:33 +00002758 // If the unsigned [RHS] type is larger, return it.
2759 if (RHSRank >= LHSRank)
2760 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Chris Lattner7cfeb082008-04-06 23:55:33 +00002762 // If the signed type can represent all values of the unsigned type, it
2763 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002764 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002765 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002766}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002767
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002768static RecordDecl *
2769CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2770 SourceLocation L, IdentifierInfo *Id) {
2771 if (Ctx.getLangOptions().CPlusPlus)
2772 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2773 else
2774 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2775}
2776
Mike Stump1eb44332009-09-09 15:08:12 +00002777// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002778QualType ASTContext::getCFConstantStringType() {
2779 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002780 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002781 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2782 &Idents.get("NSConstantString"));
2783
Anders Carlssonf06273f2007-11-19 00:25:30 +00002784 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Anders Carlsson71993dd2007-08-17 05:31:46 +00002786 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002787 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002788 // int flags;
2789 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002790 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002791 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002792 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002793 FieldTypes[3] = LongTy;
2794
Anders Carlsson71993dd2007-08-17 05:31:46 +00002795 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002796 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002797 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002798 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002799 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002800 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002801 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002802 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002803 }
2804
2805 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002806 }
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Anders Carlsson71993dd2007-08-17 05:31:46 +00002808 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002809}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002810
Douglas Gregor319ac892009-04-23 22:29:11 +00002811void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002812 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002813 assert(Rec && "Invalid CFConstantStringType");
2814 CFConstantStringTypeDecl = Rec->getDecl();
2815}
2816
Mike Stump1eb44332009-09-09 15:08:12 +00002817QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002818 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002819 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002820 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2821 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002823 QualType FieldTypes[] = {
2824 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002825 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002826 getPointerType(UnsignedLongTy),
2827 getConstantArrayType(UnsignedLongTy,
2828 llvm::APInt(32, 5), ArrayType::Normal, 0)
2829 };
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Douglas Gregor44b43212008-12-11 16:49:14 +00002831 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002832 FieldDecl *Field = FieldDecl::Create(*this,
2833 ObjCFastEnumerationStateTypeDecl,
2834 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002835 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002836 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002837 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002838 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002839 }
Mike Stump1eb44332009-09-09 15:08:12 +00002840
Douglas Gregor44b43212008-12-11 16:49:14 +00002841 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002842 }
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002844 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2845}
2846
Mike Stumpadaaad32009-10-20 02:12:22 +00002847QualType ASTContext::getBlockDescriptorType() {
2848 if (BlockDescriptorType)
2849 return getTagDeclType(BlockDescriptorType);
2850
2851 RecordDecl *T;
2852 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002853 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2854 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002855
2856 QualType FieldTypes[] = {
2857 UnsignedLongTy,
2858 UnsignedLongTy,
2859 };
2860
2861 const char *FieldNames[] = {
2862 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002863 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002864 };
2865
2866 for (size_t i = 0; i < 2; ++i) {
2867 FieldDecl *Field = FieldDecl::Create(*this,
2868 T,
2869 SourceLocation(),
2870 &Idents.get(FieldNames[i]),
2871 FieldTypes[i], /*DInfo=*/0,
2872 /*BitWidth=*/0,
2873 /*Mutable=*/false);
2874 T->addDecl(Field);
2875 }
2876
2877 T->completeDefinition(*this);
2878
2879 BlockDescriptorType = T;
2880
2881 return getTagDeclType(BlockDescriptorType);
2882}
2883
2884void ASTContext::setBlockDescriptorType(QualType T) {
2885 const RecordType *Rec = T->getAs<RecordType>();
2886 assert(Rec && "Invalid BlockDescriptorType");
2887 BlockDescriptorType = Rec->getDecl();
2888}
2889
Mike Stump083c25e2009-10-22 00:49:09 +00002890QualType ASTContext::getBlockDescriptorExtendedType() {
2891 if (BlockDescriptorExtendedType)
2892 return getTagDeclType(BlockDescriptorExtendedType);
2893
2894 RecordDecl *T;
2895 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002896 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2897 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002898
2899 QualType FieldTypes[] = {
2900 UnsignedLongTy,
2901 UnsignedLongTy,
2902 getPointerType(VoidPtrTy),
2903 getPointerType(VoidPtrTy)
2904 };
2905
2906 const char *FieldNames[] = {
2907 "reserved",
2908 "Size",
2909 "CopyFuncPtr",
2910 "DestroyFuncPtr"
2911 };
2912
2913 for (size_t i = 0; i < 4; ++i) {
2914 FieldDecl *Field = FieldDecl::Create(*this,
2915 T,
2916 SourceLocation(),
2917 &Idents.get(FieldNames[i]),
2918 FieldTypes[i], /*DInfo=*/0,
2919 /*BitWidth=*/0,
2920 /*Mutable=*/false);
2921 T->addDecl(Field);
2922 }
2923
2924 T->completeDefinition(*this);
2925
2926 BlockDescriptorExtendedType = T;
2927
2928 return getTagDeclType(BlockDescriptorExtendedType);
2929}
2930
2931void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2932 const RecordType *Rec = T->getAs<RecordType>();
2933 assert(Rec && "Invalid BlockDescriptorType");
2934 BlockDescriptorExtendedType = Rec->getDecl();
2935}
2936
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002937bool ASTContext::BlockRequiresCopying(QualType Ty) {
2938 if (Ty->isBlockPointerType())
2939 return true;
2940 if (isObjCNSObjectType(Ty))
2941 return true;
2942 if (Ty->isObjCObjectPointerType())
2943 return true;
2944 return false;
2945}
2946
2947QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2948 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002949 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002950 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002951 // unsigned int __flags;
2952 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002953 // void *__copy_helper; // as needed
2954 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002955 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002956 // } *
2957
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002958 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2959
2960 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002961 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002962 llvm::SmallString<36> Name;
2963 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2964 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002965 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002966 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2967 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002968 T->startDefinition();
2969 QualType Int32Ty = IntTy;
2970 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2971 QualType FieldTypes[] = {
2972 getPointerType(VoidPtrTy),
2973 getPointerType(getTagDeclType(T)),
2974 Int32Ty,
2975 Int32Ty,
2976 getPointerType(VoidPtrTy),
2977 getPointerType(VoidPtrTy),
2978 Ty
2979 };
2980
2981 const char *FieldNames[] = {
2982 "__isa",
2983 "__forwarding",
2984 "__flags",
2985 "__size",
2986 "__copy_helper",
2987 "__destroy_helper",
2988 DeclName,
2989 };
2990
2991 for (size_t i = 0; i < 7; ++i) {
2992 if (!HasCopyAndDispose && i >=4 && i <= 5)
2993 continue;
2994 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2995 &Idents.get(FieldNames[i]),
2996 FieldTypes[i], /*DInfo=*/0,
2997 /*BitWidth=*/0, /*Mutable=*/false);
2998 T->addDecl(Field);
2999 }
3000
3001 T->completeDefinition(*this);
3002
3003 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003004}
3005
3006
3007QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003008 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003009 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003010 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003011 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003012 llvm::SmallString<36> Name;
3013 llvm::raw_svector_ostream(Name) << "__block_literal_"
3014 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003015 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003016 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3017 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003018 QualType FieldTypes[] = {
3019 getPointerType(VoidPtrTy),
3020 IntTy,
3021 IntTy,
3022 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003023 (BlockHasCopyDispose ?
3024 getPointerType(getBlockDescriptorExtendedType()) :
3025 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003026 };
3027
3028 const char *FieldNames[] = {
3029 "__isa",
3030 "__flags",
3031 "__reserved",
3032 "__FuncPtr",
3033 "__descriptor"
3034 };
3035
3036 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003037 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003038 &Idents.get(FieldNames[i]),
3039 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003040 /*BitWidth=*/0, /*Mutable=*/false);
3041 T->addDecl(Field);
3042 }
3043
3044 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3045 const Expr *E = BlockDeclRefDecls[i];
3046 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3047 clang::IdentifierInfo *Name = 0;
3048 if (BDRE) {
3049 const ValueDecl *D = BDRE->getDecl();
3050 Name = &Idents.get(D->getName());
3051 }
3052 QualType FieldType = E->getType();
3053
3054 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003055 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3056 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003057
3058 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3059 Name, FieldType, /*DInfo=*/0,
3060 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003061 T->addDecl(Field);
3062 }
3063
3064 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003065
3066 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003067}
3068
Douglas Gregor319ac892009-04-23 22:29:11 +00003069void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003070 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003071 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3072 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3073}
3074
Anders Carlssone8c49532007-10-29 06:33:42 +00003075// This returns true if a type has been typedefed to BOOL:
3076// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003077static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003078 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003079 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3080 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003082 return false;
3083}
3084
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003086/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003087int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003088 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003090 // Make all integer and enum types at least as large as an int
3091 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003092 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003093 // Treat arrays as pointers, since that's how they're passed in.
3094 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003095 sz = getTypeSize(VoidPtrTy);
3096 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003097}
3098
David Chisnall5e530af2009-11-17 19:33:30 +00003099/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3100/// declaration.
3101void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3102 std::string& S) {
3103 const BlockDecl *Decl = Expr->getBlockDecl();
3104 QualType BlockTy =
3105 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3106 // Encode result type.
3107 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3108 // Compute size of all parameters.
3109 // Start with computing size of a pointer in number of bytes.
3110 // FIXME: There might(should) be a better way of doing this computation!
3111 SourceLocation Loc;
3112 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3113 int ParmOffset = PtrSize;
3114 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3115 E = Decl->param_end(); PI != E; ++PI) {
3116 QualType PType = (*PI)->getType();
3117 int sz = getObjCEncodingTypeSize(PType);
3118 assert (sz > 0 && "BlockExpr - Incomplete param type");
3119 ParmOffset += sz;
3120 }
3121 // Size of the argument frame
3122 S += llvm::utostr(ParmOffset);
3123 // Block pointer and offset.
3124 S += "@?0";
3125 ParmOffset = PtrSize;
3126
3127 // Argument types.
3128 ParmOffset = PtrSize;
3129 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3130 Decl->param_end(); PI != E; ++PI) {
3131 ParmVarDecl *PVDecl = *PI;
3132 QualType PType = PVDecl->getOriginalType();
3133 if (const ArrayType *AT =
3134 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3135 // Use array's original type only if it has known number of
3136 // elements.
3137 if (!isa<ConstantArrayType>(AT))
3138 PType = PVDecl->getType();
3139 } else if (PType->isFunctionType())
3140 PType = PVDecl->getType();
3141 getObjCEncodingForType(PType, S);
3142 S += llvm::utostr(ParmOffset);
3143 ParmOffset += getObjCEncodingTypeSize(PType);
3144 }
3145}
3146
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003147/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003148/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003149void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003150 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003151 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003152 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003153 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003154 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003155 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003156 // Compute size of all parameters.
3157 // Start with computing size of a pointer in number of bytes.
3158 // FIXME: There might(should) be a better way of doing this computation!
3159 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003160 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003161 // The first two arguments (self and _cmd) are pointers; account for
3162 // their size.
3163 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003164 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3165 E = Decl->param_end(); PI != E; ++PI) {
3166 QualType PType = (*PI)->getType();
3167 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003168 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003169 ParmOffset += sz;
3170 }
3171 S += llvm::utostr(ParmOffset);
3172 S += "@0:";
3173 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003174
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003175 // Argument types.
3176 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003177 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3178 E = Decl->param_end(); PI != E; ++PI) {
3179 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003180 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003181 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003182 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3183 // Use array's original type only if it has known number of
3184 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003185 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003186 PType = PVDecl->getType();
3187 } else if (PType->isFunctionType())
3188 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003189 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003190 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003191 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003192 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003193 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003194 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003195 }
3196}
3197
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003198/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003199/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003200/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3201/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003202/// Property attributes are stored as a comma-delimited C string. The simple
3203/// attributes readonly and bycopy are encoded as single characters. The
3204/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3205/// encoded as single characters, followed by an identifier. Property types
3206/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003207/// these attributes are defined by the following enumeration:
3208/// @code
3209/// enum PropertyAttributes {
3210/// kPropertyReadOnly = 'R', // property is read-only.
3211/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3212/// kPropertyByref = '&', // property is a reference to the value last assigned
3213/// kPropertyDynamic = 'D', // property is dynamic
3214/// kPropertyGetter = 'G', // followed by getter selector name
3215/// kPropertySetter = 'S', // followed by setter selector name
3216/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3217/// kPropertyType = 't' // followed by old-style type encoding.
3218/// kPropertyWeak = 'W' // 'weak' property
3219/// kPropertyStrong = 'P' // property GC'able
3220/// kPropertyNonAtomic = 'N' // property non-atomic
3221/// };
3222/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003223void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003224 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003225 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003226 // Collect information from the property implementation decl(s).
3227 bool Dynamic = false;
3228 ObjCPropertyImplDecl *SynthesizePID = 0;
3229
3230 // FIXME: Duplicated code due to poor abstraction.
3231 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003232 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003233 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3234 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003235 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003236 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003237 ObjCPropertyImplDecl *PID = *i;
3238 if (PID->getPropertyDecl() == PD) {
3239 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3240 Dynamic = true;
3241 } else {
3242 SynthesizePID = PID;
3243 }
3244 }
3245 }
3246 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003247 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003248 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003249 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003250 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003251 ObjCPropertyImplDecl *PID = *i;
3252 if (PID->getPropertyDecl() == PD) {
3253 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3254 Dynamic = true;
3255 } else {
3256 SynthesizePID = PID;
3257 }
3258 }
Mike Stump1eb44332009-09-09 15:08:12 +00003259 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003260 }
3261 }
3262
3263 // FIXME: This is not very efficient.
3264 S = "T";
3265
3266 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003267 // GCC has some special rules regarding encoding of properties which
3268 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003269 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003270 true /* outermost type */,
3271 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003272
3273 if (PD->isReadOnly()) {
3274 S += ",R";
3275 } else {
3276 switch (PD->getSetterKind()) {
3277 case ObjCPropertyDecl::Assign: break;
3278 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003279 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003280 }
3281 }
3282
3283 // It really isn't clear at all what this means, since properties
3284 // are "dynamic by default".
3285 if (Dynamic)
3286 S += ",D";
3287
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003288 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3289 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003291 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3292 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003293 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003294 }
3295
3296 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3297 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003298 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003299 }
3300
3301 if (SynthesizePID) {
3302 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3303 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003304 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003305 }
3306
3307 // FIXME: OBJCGC: weak & strong
3308}
3309
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003310/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003311/// Another legacy compatibility encoding: 32-bit longs are encoded as
3312/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003313/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3314///
3315void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003316 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003317 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003318 if (BT->getKind() == BuiltinType::ULong &&
3319 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003320 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003321 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003322 if (BT->getKind() == BuiltinType::Long &&
3323 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003324 PointeeTy = IntTy;
3325 }
3326 }
3327}
3328
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003329void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003330 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003331 // We follow the behavior of gcc, expanding structures which are
3332 // directly pointed to, and expanding embedded structures. Note that
3333 // these rules are sufficient to prevent recursive encoding of the
3334 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003335 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003336 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003337}
3338
Mike Stump1eb44332009-09-09 15:08:12 +00003339static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003340 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003341 const Expr *E = FD->getBitWidth();
3342 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3343 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003344 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003345 S += 'b';
3346 S += llvm::utostr(N);
3347}
3348
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003349// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003350void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3351 bool ExpandPointedToStructures,
3352 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003353 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003354 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003355 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003356 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003357 if (FD && FD->isBitField())
3358 return EncodeBitField(this, S, FD);
3359 char encoding;
3360 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003361 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003362 case BuiltinType::Void: encoding = 'v'; break;
3363 case BuiltinType::Bool: encoding = 'B'; break;
3364 case BuiltinType::Char_U:
3365 case BuiltinType::UChar: encoding = 'C'; break;
3366 case BuiltinType::UShort: encoding = 'S'; break;
3367 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003368 case BuiltinType::ULong:
3369 encoding =
3370 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003371 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003372 case BuiltinType::UInt128: encoding = 'T'; break;
3373 case BuiltinType::ULongLong: encoding = 'Q'; break;
3374 case BuiltinType::Char_S:
3375 case BuiltinType::SChar: encoding = 'c'; break;
3376 case BuiltinType::Short: encoding = 's'; break;
3377 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003378 case BuiltinType::Long:
3379 encoding =
3380 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003381 break;
3382 case BuiltinType::LongLong: encoding = 'q'; break;
3383 case BuiltinType::Int128: encoding = 't'; break;
3384 case BuiltinType::Float: encoding = 'f'; break;
3385 case BuiltinType::Double: encoding = 'd'; break;
3386 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003389 S += encoding;
3390 return;
3391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
John McCall183700f2009-09-21 23:43:11 +00003393 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003394 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003395 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003396 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003397 return;
3398 }
Mike Stump1eb44332009-09-09 15:08:12 +00003399
Ted Kremenek6217b802009-07-29 21:53:49 +00003400 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003401 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003402 bool isReadOnly = false;
3403 // For historical/compatibility reasons, the read-only qualifier of the
3404 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3405 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003406 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003407 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003408 if (OutermostType && T.isConstQualified()) {
3409 isReadOnly = true;
3410 S += 'r';
3411 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003412 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003413 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003414 while (P->getAs<PointerType>())
3415 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003416 if (P.isConstQualified()) {
3417 isReadOnly = true;
3418 S += 'r';
3419 }
3420 }
3421 if (isReadOnly) {
3422 // Another legacy compatibility encoding. Some ObjC qualifier and type
3423 // combinations need to be rearranged.
3424 // Rewrite "in const" from "nr" to "rn"
3425 const char * s = S.c_str();
3426 int len = S.length();
3427 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3428 std::string replace = "rn";
3429 S.replace(S.end()-2, S.end(), replace);
3430 }
3431 }
Steve Naroff14108da2009-07-10 23:34:53 +00003432 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003433 S += ':';
3434 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003435 }
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003437 if (PointeeTy->isCharType()) {
3438 // char pointer types should be encoded as '*' unless it is a
3439 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003440 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003441 S += '*';
3442 return;
3443 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003444 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003445 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3446 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3447 S += '#';
3448 return;
3449 }
3450 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3451 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3452 S += '@';
3453 return;
3454 }
3455 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003456 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003457 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003458 getLegacyIntegralTypeEncoding(PointeeTy);
3459
Mike Stump1eb44332009-09-09 15:08:12 +00003460 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003461 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003462 return;
3463 }
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003465 if (const ArrayType *AT =
3466 // Ignore type qualifiers etc.
3467 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003468 if (isa<IncompleteArrayType>(AT)) {
3469 // Incomplete arrays are encoded as a pointer to the array element.
3470 S += '^';
3471
Mike Stump1eb44332009-09-09 15:08:12 +00003472 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003473 false, ExpandStructures, FD);
3474 } else {
3475 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003476
Anders Carlsson559a8332009-02-22 01:38:57 +00003477 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3478 S += llvm::utostr(CAT->getSize().getZExtValue());
3479 else {
3480 //Variable length arrays are encoded as a regular array with 0 elements.
3481 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3482 S += '0';
3483 }
Mike Stump1eb44332009-09-09 15:08:12 +00003484
3485 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003486 false, ExpandStructures, FD);
3487 S += ']';
3488 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003489 return;
3490 }
Mike Stump1eb44332009-09-09 15:08:12 +00003491
John McCall183700f2009-09-21 23:43:11 +00003492 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003493 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003494 return;
3495 }
Mike Stump1eb44332009-09-09 15:08:12 +00003496
Ted Kremenek6217b802009-07-29 21:53:49 +00003497 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003498 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003499 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003500 // Anonymous structures print as '?'
3501 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3502 S += II->getName();
3503 } else {
3504 S += '?';
3505 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003506 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003507 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003508 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3509 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003510 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003511 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003512 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003513 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003514 S += '"';
3515 }
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003517 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003518 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003519 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003520 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003521 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003522 QualType qt = Field->getType();
3523 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003524 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003525 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003526 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003527 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003528 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003529 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003530 return;
3531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003533 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003534 if (FD && FD->isBitField())
3535 EncodeBitField(this, S, FD);
3536 else
3537 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003538 return;
3539 }
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003541 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003542 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003543 return;
3544 }
Mike Stump1eb44332009-09-09 15:08:12 +00003545
John McCall0953e762009-09-24 19:53:00 +00003546 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003547 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003548 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003549 S += '{';
3550 const IdentifierInfo *II = OI->getIdentifier();
3551 S += II->getName();
3552 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003553 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003554 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003555 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003556 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003557 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003558 RecFields[i]);
3559 else
Mike Stump1eb44332009-09-09 15:08:12 +00003560 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003561 FD);
3562 }
3563 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003564 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003565 }
Mike Stump1eb44332009-09-09 15:08:12 +00003566
John McCall183700f2009-09-21 23:43:11 +00003567 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003568 if (OPT->isObjCIdType()) {
3569 S += '@';
3570 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Steve Naroff27d20a22009-10-28 22:03:49 +00003573 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3574 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3575 // Since this is a binary compatibility issue, need to consult with runtime
3576 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003577 S += '#';
3578 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003579 }
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003581 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003582 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003583 ExpandPointedToStructures,
3584 ExpandStructures, FD);
3585 if (FD || EncodingProperty) {
3586 // Note that we do extended encoding of protocol qualifer list
3587 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003588 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003589 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3590 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003591 S += '<';
3592 S += (*I)->getNameAsString();
3593 S += '>';
3594 }
3595 S += '"';
3596 }
3597 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 }
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003600 QualType PointeeTy = OPT->getPointeeType();
3601 if (!EncodingProperty &&
3602 isa<TypedefType>(PointeeTy.getTypePtr())) {
3603 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003604 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003605 // {...};
3606 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003607 getObjCEncodingForTypeImpl(PointeeTy, S,
3608 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003609 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003610 return;
3611 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003612
3613 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003614 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003615 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003616 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003617 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3618 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003619 S += '<';
3620 S += (*I)->getNameAsString();
3621 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003622 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003623 S += '"';
3624 }
3625 return;
3626 }
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003628 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003629}
3630
Mike Stump1eb44332009-09-09 15:08:12 +00003631void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003632 std::string& S) const {
3633 if (QT & Decl::OBJC_TQ_In)
3634 S += 'n';
3635 if (QT & Decl::OBJC_TQ_Inout)
3636 S += 'N';
3637 if (QT & Decl::OBJC_TQ_Out)
3638 S += 'o';
3639 if (QT & Decl::OBJC_TQ_Bycopy)
3640 S += 'O';
3641 if (QT & Decl::OBJC_TQ_Byref)
3642 S += 'R';
3643 if (QT & Decl::OBJC_TQ_Oneway)
3644 S += 'V';
3645}
3646
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003647void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003648 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003650 BuiltinVaListType = T;
3651}
3652
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003653void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003654 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003655}
3656
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003657void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003658 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003659}
3660
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003661void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003662 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003663}
3664
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003665void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003666 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003667}
3668
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003669void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003670 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003671 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003673 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003674}
3675
Douglas Gregor7532dc62009-03-30 22:58:21 +00003676/// \brief Retrieve the template name that represents a qualified
3677/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003678TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003679 bool TemplateKeyword,
3680 TemplateDecl *Template) {
3681 llvm::FoldingSetNodeID ID;
3682 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3683
3684 void *InsertPos = 0;
3685 QualifiedTemplateName *QTN =
3686 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3687 if (!QTN) {
3688 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3689 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3690 }
3691
3692 return TemplateName(QTN);
3693}
3694
Douglas Gregord99cbe62009-07-29 18:26:50 +00003695/// \brief Retrieve the template name that represents a qualified
3696/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003697TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003698 bool TemplateKeyword,
3699 OverloadedFunctionDecl *Template) {
3700 llvm::FoldingSetNodeID ID;
3701 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Douglas Gregord99cbe62009-07-29 18:26:50 +00003703 void *InsertPos = 0;
3704 QualifiedTemplateName *QTN =
3705 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3706 if (!QTN) {
3707 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3708 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3709 }
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Douglas Gregord99cbe62009-07-29 18:26:50 +00003711 return TemplateName(QTN);
3712}
3713
Douglas Gregor7532dc62009-03-30 22:58:21 +00003714/// \brief Retrieve the template name that represents a dependent
3715/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003716TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003717 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003718 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003719 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003720
3721 llvm::FoldingSetNodeID ID;
3722 DependentTemplateName::Profile(ID, NNS, Name);
3723
3724 void *InsertPos = 0;
3725 DependentTemplateName *QTN =
3726 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3727
3728 if (QTN)
3729 return TemplateName(QTN);
3730
3731 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3732 if (CanonNNS == NNS) {
3733 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3734 } else {
3735 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3736 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3737 }
3738
3739 DependentTemplateNames.InsertNode(QTN, InsertPos);
3740 return TemplateName(QTN);
3741}
3742
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003743/// \brief Retrieve the template name that represents a dependent
3744/// template name such as \c MetaFun::template operator+.
3745TemplateName
3746ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3747 OverloadedOperatorKind Operator) {
3748 assert((!NNS || NNS->isDependent()) &&
3749 "Nested name specifier must be dependent");
3750
3751 llvm::FoldingSetNodeID ID;
3752 DependentTemplateName::Profile(ID, NNS, Operator);
3753
3754 void *InsertPos = 0;
3755 DependentTemplateName *QTN =
3756 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3757
3758 if (QTN)
3759 return TemplateName(QTN);
3760
3761 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3762 if (CanonNNS == NNS) {
3763 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3764 } else {
3765 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3766 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3767 }
3768
3769 DependentTemplateNames.InsertNode(QTN, InsertPos);
3770 return TemplateName(QTN);
3771}
3772
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003773/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003774/// TargetInfo, produce the corresponding type. The unsigned @p Type
3775/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003776CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003777 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003778 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003779 case TargetInfo::SignedShort: return ShortTy;
3780 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3781 case TargetInfo::SignedInt: return IntTy;
3782 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3783 case TargetInfo::SignedLong: return LongTy;
3784 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3785 case TargetInfo::SignedLongLong: return LongLongTy;
3786 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3787 }
3788
3789 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003790 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003791}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003792
3793//===----------------------------------------------------------------------===//
3794// Type Predicates.
3795//===----------------------------------------------------------------------===//
3796
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003797/// isObjCNSObjectType - Return true if this is an NSObject object using
3798/// NSObject attribute on a c-style pointer type.
3799/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003800/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003801///
3802bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3803 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3804 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003805 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003806 return true;
3807 }
Mike Stump1eb44332009-09-09 15:08:12 +00003808 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003809}
3810
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003811/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3812/// garbage collection attribute.
3813///
John McCall0953e762009-09-24 19:53:00 +00003814Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3815 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003816 if (getLangOptions().ObjC1 &&
3817 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003818 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003819 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003820 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003821 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003822 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003823 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003824 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003825 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003826 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003827 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003828 // Non-pointers have none gc'able attribute regardless of the attribute
3829 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003830 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003831 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003832 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003833 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003834}
3835
Chris Lattner6ac46a42008-04-07 06:51:04 +00003836//===----------------------------------------------------------------------===//
3837// Type Compatibility Testing
3838//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003839
Mike Stump1eb44332009-09-09 15:08:12 +00003840/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003841/// compatible.
3842static bool areCompatVectorTypes(const VectorType *LHS,
3843 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003844 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003845 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003846 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003847}
3848
Steve Naroff4084c302009-07-23 01:01:38 +00003849//===----------------------------------------------------------------------===//
3850// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3851//===----------------------------------------------------------------------===//
3852
3853/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3854/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003855bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3856 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003857 if (lProto == rProto)
3858 return true;
3859 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3860 E = rProto->protocol_end(); PI != E; ++PI)
3861 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3862 return true;
3863 return false;
3864}
3865
Steve Naroff4084c302009-07-23 01:01:38 +00003866/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3867/// return true if lhs's protocols conform to rhs's protocol; false
3868/// otherwise.
3869bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3870 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3871 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3872 return false;
3873}
3874
3875/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3876/// ObjCQualifiedIDType.
3877bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3878 bool compare) {
3879 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003880 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003881 lhs->isObjCIdType() || lhs->isObjCClassType())
3882 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003883 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003884 rhs->isObjCIdType() || rhs->isObjCClassType())
3885 return true;
3886
3887 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003888 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Steve Naroff4084c302009-07-23 01:01:38 +00003890 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Steve Naroff4084c302009-07-23 01:01:38 +00003892 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003893 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003894 // make sure we check the class hierarchy.
3895 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3896 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3897 E = lhsQID->qual_end(); I != E; ++I) {
3898 // when comparing an id<P> on lhs with a static type on rhs,
3899 // see if static class implements all of id's protocols, directly or
3900 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003901 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003902 return false;
3903 }
3904 }
3905 // If there are no qualifiers and no interface, we have an 'id'.
3906 return true;
3907 }
Mike Stump1eb44332009-09-09 15:08:12 +00003908 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003909 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3910 E = lhsQID->qual_end(); I != E; ++I) {
3911 ObjCProtocolDecl *lhsProto = *I;
3912 bool match = false;
3913
3914 // when comparing an id<P> on lhs with a static type on rhs,
3915 // see if static class implements all of id's protocols, directly or
3916 // through its super class and categories.
3917 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3918 E = rhsOPT->qual_end(); J != E; ++J) {
3919 ObjCProtocolDecl *rhsProto = *J;
3920 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3921 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3922 match = true;
3923 break;
3924 }
3925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003927 // make sure we check the class hierarchy.
3928 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3929 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3930 E = lhsQID->qual_end(); I != E; ++I) {
3931 // when comparing an id<P> on lhs with a static type on rhs,
3932 // see if static class implements all of id's protocols, directly or
3933 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003934 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003935 match = true;
3936 break;
3937 }
3938 }
3939 }
3940 if (!match)
3941 return false;
3942 }
Mike Stump1eb44332009-09-09 15:08:12 +00003943
Steve Naroff4084c302009-07-23 01:01:38 +00003944 return true;
3945 }
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Steve Naroff4084c302009-07-23 01:01:38 +00003947 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3948 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3949
Mike Stump1eb44332009-09-09 15:08:12 +00003950 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003951 lhs->getAsObjCInterfacePointerType()) {
3952 if (lhsOPT->qual_empty()) {
3953 bool match = false;
3954 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3955 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3956 E = rhsQID->qual_end(); I != E; ++I) {
3957 // when comparing an id<P> on lhs with a static type on rhs,
3958 // see if static class implements all of id's protocols, directly or
3959 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003960 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003961 match = true;
3962 break;
3963 }
3964 }
3965 if (!match)
3966 return false;
3967 }
3968 return true;
3969 }
Mike Stump1eb44332009-09-09 15:08:12 +00003970 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003971 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3972 E = lhsOPT->qual_end(); I != E; ++I) {
3973 ObjCProtocolDecl *lhsProto = *I;
3974 bool match = false;
3975
3976 // when comparing an id<P> on lhs with a static type on rhs,
3977 // see if static class implements all of id's protocols, directly or
3978 // through its super class and categories.
3979 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3980 E = rhsQID->qual_end(); J != E; ++J) {
3981 ObjCProtocolDecl *rhsProto = *J;
3982 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3983 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3984 match = true;
3985 break;
3986 }
3987 }
3988 if (!match)
3989 return false;
3990 }
3991 return true;
3992 }
3993 return false;
3994}
3995
Eli Friedman3d815e72008-08-22 00:56:42 +00003996/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003997/// compatible for assignment from RHS to LHS. This handles validation of any
3998/// protocol qualifiers on the LHS or RHS.
3999///
Steve Naroff14108da2009-07-10 23:34:53 +00004000bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4001 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004002 // If either type represents the built-in 'id' or 'Class' types, return true.
4003 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004004 return true;
4005
Steve Naroff4084c302009-07-23 01:01:38 +00004006 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004007 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4008 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004009 false);
4010
Steve Naroff14108da2009-07-10 23:34:53 +00004011 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4012 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004013 if (LHS && RHS) // We have 2 user-defined types.
4014 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Steve Naroff4084c302009-07-23 01:01:38 +00004016 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004017}
4018
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004019/// getIntersectionOfProtocols - This routine finds the intersection of set
4020/// of protocols inherited from two distinct objective-c pointer objects.
4021/// It is used to build composite qualifier list of the composite type of
4022/// the conditional expression involving two objective-c pointer objects.
4023static
4024void getIntersectionOfProtocols(ASTContext &Context,
4025 const ObjCObjectPointerType *LHSOPT,
4026 const ObjCObjectPointerType *RHSOPT,
4027 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4028
4029 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4030 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4031
4032 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4033 unsigned LHSNumProtocols = LHS->getNumProtocols();
4034 if (LHSNumProtocols > 0)
4035 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4036 else {
4037 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4038 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4039 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4040 LHSInheritedProtocols.end());
4041 }
4042
4043 unsigned RHSNumProtocols = RHS->getNumProtocols();
4044 if (RHSNumProtocols > 0) {
4045 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4046 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4047 if (InheritedProtocolSet.count(RHSProtocols[i]))
4048 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4049 }
4050 else {
4051 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4052 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4053 // FIXME. This may cause duplication of protocols in the list, but should
4054 // be harmless.
4055 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4056 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4057 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4058 }
4059}
4060
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004061/// areCommonBaseCompatible - Returns common base class of the two classes if
4062/// one found. Note that this is O'2 algorithm. But it will be called as the
4063/// last type comparison in a ?-exp of ObjC pointer types before a
4064/// warning is issued. So, its invokation is extremely rare.
4065QualType ASTContext::areCommonBaseCompatible(
4066 const ObjCObjectPointerType *LHSOPT,
4067 const ObjCObjectPointerType *RHSOPT) {
4068 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4069 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4070 if (!LHS || !RHS)
4071 return QualType();
4072
4073 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4074 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4075 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004076 if (canAssignObjCInterfaces(LHS, RHS)) {
4077 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4078 getIntersectionOfProtocols(*this,
4079 LHSOPT, RHSOPT, IntersectionOfProtocols);
4080 if (IntersectionOfProtocols.empty())
4081 LHSTy = getObjCObjectPointerType(LHSTy);
4082 else
4083 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4084 IntersectionOfProtocols.size());
4085 return LHSTy;
4086 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004087 }
4088
4089 return QualType();
4090}
4091
Eli Friedman3d815e72008-08-22 00:56:42 +00004092bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4093 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004094 // Verify that the base decls are compatible: the RHS must be a subclass of
4095 // the LHS.
4096 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4097 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004098
Chris Lattner6ac46a42008-04-07 06:51:04 +00004099 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4100 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004101 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004102 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004103
Chris Lattner6ac46a42008-04-07 06:51:04 +00004104 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4105 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004106 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004107 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004109 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4110 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004111 LHSPI != LHSPE; LHSPI++) {
4112 bool RHSImplementsProtocol = false;
4113
4114 // If the RHS doesn't implement the protocol on the left, the types
4115 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004116 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004117 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004118 RHSPI != RHSPE; RHSPI++) {
4119 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004120 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004121 break;
4122 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004123 }
4124 // FIXME: For better diagnostics, consider passing back the protocol name.
4125 if (!RHSImplementsProtocol)
4126 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004127 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004128 // The RHS implements all protocols listed on the LHS.
4129 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004130}
4131
Steve Naroff389bf462009-02-12 17:52:19 +00004132bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4133 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004134 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4135 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Steve Naroff14108da2009-07-10 23:34:53 +00004137 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004138 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004139
4140 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4141 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004142}
4143
Mike Stump1eb44332009-09-09 15:08:12 +00004144/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004145/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004146/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004147/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004148bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4149 return !mergeTypes(LHS, RHS).isNull();
4150}
4151
4152QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004153 const FunctionType *lbase = lhs->getAs<FunctionType>();
4154 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004155 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4156 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004157 bool allLTypes = true;
4158 bool allRTypes = true;
4159
4160 // Check return type
4161 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4162 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004163 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4164 allLTypes = false;
4165 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4166 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004167 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004168 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4169 if (NoReturn != lbase->getNoReturnAttr())
4170 allLTypes = false;
4171 if (NoReturn != rbase->getNoReturnAttr())
4172 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004173
Eli Friedman3d815e72008-08-22 00:56:42 +00004174 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004175 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4176 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004177 unsigned lproto_nargs = lproto->getNumArgs();
4178 unsigned rproto_nargs = rproto->getNumArgs();
4179
4180 // Compatible functions must have the same number of arguments
4181 if (lproto_nargs != rproto_nargs)
4182 return QualType();
4183
4184 // Variadic and non-variadic functions aren't compatible
4185 if (lproto->isVariadic() != rproto->isVariadic())
4186 return QualType();
4187
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004188 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4189 return QualType();
4190
Eli Friedman3d815e72008-08-22 00:56:42 +00004191 // Check argument compatibility
4192 llvm::SmallVector<QualType, 10> types;
4193 for (unsigned i = 0; i < lproto_nargs; i++) {
4194 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4195 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4196 QualType argtype = mergeTypes(largtype, rargtype);
4197 if (argtype.isNull()) return QualType();
4198 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004199 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4200 allLTypes = false;
4201 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4202 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004203 }
4204 if (allLTypes) return lhs;
4205 if (allRTypes) return rhs;
4206 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004207 lproto->isVariadic(), lproto->getTypeQuals(),
4208 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004209 }
4210
4211 if (lproto) allRTypes = false;
4212 if (rproto) allLTypes = false;
4213
Douglas Gregor72564e72009-02-26 23:50:07 +00004214 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004215 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004216 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004217 if (proto->isVariadic()) return QualType();
4218 // Check that the types are compatible with the types that
4219 // would result from default argument promotions (C99 6.7.5.3p15).
4220 // The only types actually affected are promotable integer
4221 // types and floats, which would be passed as a different
4222 // type depending on whether the prototype is visible.
4223 unsigned proto_nargs = proto->getNumArgs();
4224 for (unsigned i = 0; i < proto_nargs; ++i) {
4225 QualType argTy = proto->getArgType(i);
4226 if (argTy->isPromotableIntegerType() ||
4227 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4228 return QualType();
4229 }
4230
4231 if (allLTypes) return lhs;
4232 if (allRTypes) return rhs;
4233 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004234 proto->getNumArgs(), proto->isVariadic(),
4235 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004236 }
4237
4238 if (allLTypes) return lhs;
4239 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004240 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004241}
4242
4243QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004244 // C++ [expr]: If an expression initially has the type "reference to T", the
4245 // type is adjusted to "T" prior to any further analysis, the expression
4246 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004247 // expression is an lvalue unless the reference is an rvalue reference and
4248 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004249 // FIXME: C++ shouldn't be going through here! The rules are different
4250 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004251 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4252 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004253 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004254 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004255 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004256 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004257
Eli Friedman3d815e72008-08-22 00:56:42 +00004258 QualType LHSCan = getCanonicalType(LHS),
4259 RHSCan = getCanonicalType(RHS);
4260
4261 // If two types are identical, they are compatible.
4262 if (LHSCan == RHSCan)
4263 return LHS;
4264
John McCall0953e762009-09-24 19:53:00 +00004265 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004266 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4267 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004268 if (LQuals != RQuals) {
4269 // If any of these qualifiers are different, we have a type
4270 // mismatch.
4271 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4272 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4273 return QualType();
4274
4275 // Exactly one GC qualifier difference is allowed: __strong is
4276 // okay if the other type has no GC qualifier but is an Objective
4277 // C object pointer (i.e. implicitly strong by default). We fix
4278 // this by pretending that the unqualified type was actually
4279 // qualified __strong.
4280 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4281 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4282 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4283
4284 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4285 return QualType();
4286
4287 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4288 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4289 }
4290 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4291 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4292 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004293 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004294 }
4295
4296 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004297
Eli Friedman852d63b2009-06-01 01:22:52 +00004298 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4299 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004300
Chris Lattner1adb8832008-01-14 05:45:46 +00004301 // We want to consider the two function types to be the same for these
4302 // comparisons, just force one to the other.
4303 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4304 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004305
4306 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004307 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4308 LHSClass = Type::ConstantArray;
4309 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4310 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Nate Begeman213541a2008-04-18 23:10:10 +00004312 // Canonicalize ExtVector -> Vector.
4313 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4314 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004315
Chris Lattnera36a61f2008-04-07 05:43:21 +00004316 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004317 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004318 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004319 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004320 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004321 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4322 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004323 }
John McCall183700f2009-09-21 23:43:11 +00004324 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004325 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4326 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004327 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004328
Eli Friedman3d815e72008-08-22 00:56:42 +00004329 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004330 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004331
Steve Naroff4a746782008-01-09 22:43:08 +00004332 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004333 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004334#define TYPE(Class, Base)
4335#define ABSTRACT_TYPE(Class, Base)
4336#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4337#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4338#include "clang/AST/TypeNodes.def"
4339 assert(false && "Non-canonical and dependent types shouldn't get here");
4340 return QualType();
4341
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004342 case Type::LValueReference:
4343 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004344 case Type::MemberPointer:
4345 assert(false && "C++ should never be in mergeTypes");
4346 return QualType();
4347
4348 case Type::IncompleteArray:
4349 case Type::VariableArray:
4350 case Type::FunctionProto:
4351 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004352 assert(false && "Types are eliminated above");
4353 return QualType();
4354
Chris Lattner1adb8832008-01-14 05:45:46 +00004355 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004356 {
4357 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004358 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4359 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004360 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4361 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004362 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004363 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004364 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004365 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004366 return getPointerType(ResultType);
4367 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004368 case Type::BlockPointer:
4369 {
4370 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004371 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4372 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004373 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4374 if (ResultType.isNull()) return QualType();
4375 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4376 return LHS;
4377 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4378 return RHS;
4379 return getBlockPointerType(ResultType);
4380 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004381 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004382 {
4383 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4384 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4385 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4386 return QualType();
4387
4388 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4389 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4390 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4391 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004392 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4393 return LHS;
4394 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4395 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004396 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4397 ArrayType::ArraySizeModifier(), 0);
4398 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4399 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004400 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4401 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004402 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4403 return LHS;
4404 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4405 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004406 if (LVAT) {
4407 // FIXME: This isn't correct! But tricky to implement because
4408 // the array's size has to be the size of LHS, but the type
4409 // has to be different.
4410 return LHS;
4411 }
4412 if (RVAT) {
4413 // FIXME: This isn't correct! But tricky to implement because
4414 // the array's size has to be the size of RHS, but the type
4415 // has to be different.
4416 return RHS;
4417 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004418 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4419 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004420 return getIncompleteArrayType(ResultType,
4421 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004422 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004423 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004424 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004425 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004426 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004427 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004428 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004429 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004430 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004431 case Type::Complex:
4432 // Distinct complex types are incompatible.
4433 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004434 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004435 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004436 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004437 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004438 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004439 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004440 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004441 // FIXME: This should be type compatibility, e.g. whether
4442 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004443 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4444 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004445 if (LHSIface && RHSIface &&
4446 canAssignObjCInterfaces(LHSIface, RHSIface))
4447 return LHS;
4448
Eli Friedman3d815e72008-08-22 00:56:42 +00004449 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004450 }
Steve Naroff14108da2009-07-10 23:34:53 +00004451 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004452 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4453 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004454 return LHS;
4455
Steve Naroffbc76dd02008-12-10 22:14:21 +00004456 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004457 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004458 case Type::FixedWidthInt:
4459 // Distinct fixed-width integers are not compatible.
4460 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004461 case Type::TemplateSpecialization:
4462 assert(false && "Dependent types have no size");
4463 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004464 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004465
4466 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004467}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004468
Chris Lattner5426bf62008-04-07 07:01:58 +00004469//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004470// Integer Predicates
4471//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004472
Eli Friedmanad74a752008-06-28 06:23:08 +00004473unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004474 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004475 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004476 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004477 return FWIT->getWidth();
4478 }
4479 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004480 return (unsigned)getTypeSize(T);
4481}
4482
4483QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4484 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004485
4486 // Turn <4 x signed int> -> <4 x unsigned int>
4487 if (const VectorType *VTy = T->getAs<VectorType>())
4488 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4489 VTy->getNumElements());
4490
4491 // For enums, we return the unsigned version of the base type.
4492 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004493 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004494
4495 const BuiltinType *BTy = T->getAs<BuiltinType>();
4496 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004497 switch (BTy->getKind()) {
4498 case BuiltinType::Char_S:
4499 case BuiltinType::SChar:
4500 return UnsignedCharTy;
4501 case BuiltinType::Short:
4502 return UnsignedShortTy;
4503 case BuiltinType::Int:
4504 return UnsignedIntTy;
4505 case BuiltinType::Long:
4506 return UnsignedLongTy;
4507 case BuiltinType::LongLong:
4508 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004509 case BuiltinType::Int128:
4510 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004511 default:
4512 assert(0 && "Unexpected signed integer type");
4513 return QualType();
4514 }
4515}
4516
Douglas Gregor2cf26342009-04-09 22:27:44 +00004517ExternalASTSource::~ExternalASTSource() { }
4518
4519void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004520
4521
4522//===----------------------------------------------------------------------===//
4523// Builtin Type Computation
4524//===----------------------------------------------------------------------===//
4525
4526/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4527/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004528static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004529 ASTContext::GetBuiltinTypeError &Error,
4530 bool AllowTypeModifiers = true) {
4531 // Modifiers.
4532 int HowLong = 0;
4533 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Chris Lattner86df27b2009-06-14 00:45:47 +00004535 // Read the modifiers first.
4536 bool Done = false;
4537 while (!Done) {
4538 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004539 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004540 case 'S':
4541 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4542 assert(!Signed && "Can't use 'S' modifier multiple times!");
4543 Signed = true;
4544 break;
4545 case 'U':
4546 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4547 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4548 Unsigned = true;
4549 break;
4550 case 'L':
4551 assert(HowLong <= 2 && "Can't have LLLL modifier");
4552 ++HowLong;
4553 break;
4554 }
4555 }
4556
4557 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Chris Lattner86df27b2009-06-14 00:45:47 +00004559 // Read the base type.
4560 switch (*Str++) {
4561 default: assert(0 && "Unknown builtin type letter!");
4562 case 'v':
4563 assert(HowLong == 0 && !Signed && !Unsigned &&
4564 "Bad modifiers used with 'v'!");
4565 Type = Context.VoidTy;
4566 break;
4567 case 'f':
4568 assert(HowLong == 0 && !Signed && !Unsigned &&
4569 "Bad modifiers used with 'f'!");
4570 Type = Context.FloatTy;
4571 break;
4572 case 'd':
4573 assert(HowLong < 2 && !Signed && !Unsigned &&
4574 "Bad modifiers used with 'd'!");
4575 if (HowLong)
4576 Type = Context.LongDoubleTy;
4577 else
4578 Type = Context.DoubleTy;
4579 break;
4580 case 's':
4581 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4582 if (Unsigned)
4583 Type = Context.UnsignedShortTy;
4584 else
4585 Type = Context.ShortTy;
4586 break;
4587 case 'i':
4588 if (HowLong == 3)
4589 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4590 else if (HowLong == 2)
4591 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4592 else if (HowLong == 1)
4593 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4594 else
4595 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4596 break;
4597 case 'c':
4598 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4599 if (Signed)
4600 Type = Context.SignedCharTy;
4601 else if (Unsigned)
4602 Type = Context.UnsignedCharTy;
4603 else
4604 Type = Context.CharTy;
4605 break;
4606 case 'b': // boolean
4607 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4608 Type = Context.BoolTy;
4609 break;
4610 case 'z': // size_t.
4611 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4612 Type = Context.getSizeType();
4613 break;
4614 case 'F':
4615 Type = Context.getCFConstantStringType();
4616 break;
4617 case 'a':
4618 Type = Context.getBuiltinVaListType();
4619 assert(!Type.isNull() && "builtin va list type not initialized!");
4620 break;
4621 case 'A':
4622 // This is a "reference" to a va_list; however, what exactly
4623 // this means depends on how va_list is defined. There are two
4624 // different kinds of va_list: ones passed by value, and ones
4625 // passed by reference. An example of a by-value va_list is
4626 // x86, where va_list is a char*. An example of by-ref va_list
4627 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4628 // we want this argument to be a char*&; for x86-64, we want
4629 // it to be a __va_list_tag*.
4630 Type = Context.getBuiltinVaListType();
4631 assert(!Type.isNull() && "builtin va list type not initialized!");
4632 if (Type->isArrayType()) {
4633 Type = Context.getArrayDecayedType(Type);
4634 } else {
4635 Type = Context.getLValueReferenceType(Type);
4636 }
4637 break;
4638 case 'V': {
4639 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004640 unsigned NumElements = strtoul(Str, &End, 10);
4641 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Chris Lattner86df27b2009-06-14 00:45:47 +00004643 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Chris Lattner86df27b2009-06-14 00:45:47 +00004645 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4646 Type = Context.getVectorType(ElementType, NumElements);
4647 break;
4648 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004649 case 'X': {
4650 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4651 Type = Context.getComplexType(ElementType);
4652 break;
4653 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004654 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004655 Type = Context.getFILEType();
4656 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004657 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004658 return QualType();
4659 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004660 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004661 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004662 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004663 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004664 else
4665 Type = Context.getjmp_bufType();
4666
Mike Stumpfd612db2009-07-28 23:47:15 +00004667 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004668 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004669 return QualType();
4670 }
4671 break;
Mike Stump782fa302009-07-28 02:25:19 +00004672 }
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Chris Lattner86df27b2009-06-14 00:45:47 +00004674 if (!AllowTypeModifiers)
4675 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Chris Lattner86df27b2009-06-14 00:45:47 +00004677 Done = false;
4678 while (!Done) {
4679 switch (*Str++) {
4680 default: Done = true; --Str; break;
4681 case '*':
4682 Type = Context.getPointerType(Type);
4683 break;
4684 case '&':
4685 Type = Context.getLValueReferenceType(Type);
4686 break;
4687 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4688 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004689 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004690 break;
4691 }
4692 }
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Chris Lattner86df27b2009-06-14 00:45:47 +00004694 return Type;
4695}
4696
4697/// GetBuiltinType - Return the type for the specified builtin.
4698QualType ASTContext::GetBuiltinType(unsigned id,
4699 GetBuiltinTypeError &Error) {
4700 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Chris Lattner86df27b2009-06-14 00:45:47 +00004702 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Chris Lattner86df27b2009-06-14 00:45:47 +00004704 Error = GE_None;
4705 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4706 if (Error != GE_None)
4707 return QualType();
4708 while (TypeStr[0] && TypeStr[0] != '.') {
4709 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4710 if (Error != GE_None)
4711 return QualType();
4712
4713 // Do array -> pointer decay. The builtin should use the decayed type.
4714 if (Ty->isArrayType())
4715 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004716
Chris Lattner86df27b2009-06-14 00:45:47 +00004717 ArgTypes.push_back(Ty);
4718 }
4719
4720 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4721 "'.' should only occur at end of builtin type list!");
4722
4723 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4724 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4725 return getFunctionNoProtoType(ResType);
4726 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4727 TypeStr[0] == '.', 0);
4728}
Eli Friedmana95d7572009-08-19 07:44:53 +00004729
4730QualType
4731ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4732 // Perform the usual unary conversions. We do this early so that
4733 // integral promotions to "int" can allow us to exit early, in the
4734 // lhs == rhs check. Also, for conversion purposes, we ignore any
4735 // qualifiers. For example, "const float" and "float" are
4736 // equivalent.
4737 if (lhs->isPromotableIntegerType())
4738 lhs = getPromotedIntegerType(lhs);
4739 else
4740 lhs = lhs.getUnqualifiedType();
4741 if (rhs->isPromotableIntegerType())
4742 rhs = getPromotedIntegerType(rhs);
4743 else
4744 rhs = rhs.getUnqualifiedType();
4745
4746 // If both types are identical, no conversion is needed.
4747 if (lhs == rhs)
4748 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004749
Eli Friedmana95d7572009-08-19 07:44:53 +00004750 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4751 // The caller can deal with this (e.g. pointer + int).
4752 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4753 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004754
4755 // At this point, we have two different arithmetic types.
4756
Eli Friedmana95d7572009-08-19 07:44:53 +00004757 // Handle complex types first (C99 6.3.1.8p1).
4758 if (lhs->isComplexType() || rhs->isComplexType()) {
4759 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004760 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004761 // convert the rhs to the lhs complex type.
4762 return lhs;
4763 }
Mike Stump1eb44332009-09-09 15:08:12 +00004764 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004765 // convert the lhs to the rhs complex type.
4766 return rhs;
4767 }
4768 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004769 // When both operands are complex, the shorter operand is converted to the
4770 // type of the longer, and that is the type of the result. This corresponds
4771 // to what is done when combining two real floating-point operands.
4772 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004773 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004774 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004775 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004776 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004777 // "double _Complex" is promoted to "long double _Complex".
4778 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004779
4780 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004781 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004782 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004783 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004784 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004785 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4786 // domains match. This is a requirement for our implementation, C99
4787 // does not require this promotion.
4788 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4789 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4790 return rhs;
4791 } else { // handle "_Complex double, double".
4792 return lhs;
4793 }
4794 }
4795 return lhs; // The domain/size match exactly.
4796 }
4797 // Now handle "real" floating types (i.e. float, double, long double).
4798 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4799 // if we have an integer operand, the result is the real floating type.
4800 if (rhs->isIntegerType()) {
4801 // convert rhs to the lhs floating point type.
4802 return lhs;
4803 }
4804 if (rhs->isComplexIntegerType()) {
4805 // convert rhs to the complex floating point type.
4806 return getComplexType(lhs);
4807 }
4808 if (lhs->isIntegerType()) {
4809 // convert lhs to the rhs floating point type.
4810 return rhs;
4811 }
Mike Stump1eb44332009-09-09 15:08:12 +00004812 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004813 // convert lhs to the complex floating point type.
4814 return getComplexType(rhs);
4815 }
4816 // We have two real floating types, float/complex combos were handled above.
4817 // Convert the smaller operand to the bigger result.
4818 int result = getFloatingTypeOrder(lhs, rhs);
4819 if (result > 0) // convert the rhs
4820 return lhs;
4821 assert(result < 0 && "illegal float comparison");
4822 return rhs; // convert the lhs
4823 }
4824 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4825 // Handle GCC complex int extension.
4826 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4827 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4828
4829 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004830 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004831 rhsComplexInt->getElementType()) >= 0)
4832 return lhs; // convert the rhs
4833 return rhs;
4834 } else if (lhsComplexInt && rhs->isIntegerType()) {
4835 // convert the rhs to the lhs complex type.
4836 return lhs;
4837 } else if (rhsComplexInt && lhs->isIntegerType()) {
4838 // convert the lhs to the rhs complex type.
4839 return rhs;
4840 }
4841 }
4842 // Finally, we have two differing integer types.
4843 // The rules for this case are in C99 6.3.1.8
4844 int compare = getIntegerTypeOrder(lhs, rhs);
4845 bool lhsSigned = lhs->isSignedIntegerType(),
4846 rhsSigned = rhs->isSignedIntegerType();
4847 QualType destType;
4848 if (lhsSigned == rhsSigned) {
4849 // Same signedness; use the higher-ranked type
4850 destType = compare >= 0 ? lhs : rhs;
4851 } else if (compare != (lhsSigned ? 1 : -1)) {
4852 // The unsigned type has greater than or equal rank to the
4853 // signed type, so use the unsigned type
4854 destType = lhsSigned ? rhs : lhs;
4855 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4856 // The two types are different widths; if we are here, that
4857 // means the signed type is larger than the unsigned type, so
4858 // use the signed type.
4859 destType = lhsSigned ? lhs : rhs;
4860 } else {
4861 // The signed type is higher-ranked than the unsigned type,
4862 // but isn't actually any bigger (like unsigned int and long
4863 // on most 32-bit systems). Use the unsigned type corresponding
4864 // to the signed type.
4865 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4866 }
4867 return destType;
4868}