blob: dc92afdd111bb2a2f969126dee7ca3aebf2f05a1 [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.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000523unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000524 unsigned Align = Target.getCharWidth();
525
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000526 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000527 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000528
Chris Lattneraf707ab2009-01-24 21:53:27 +0000529 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
530 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000531 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000532 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000533 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000534 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
535 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000536 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
537 T = cast<ArrayType>(T)->getElementType();
538
539 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
540 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000541 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000542
543 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000544}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000545
Chris Lattnera7674d82007-07-13 22:13:22 +0000546/// getTypeSize - Return the size of the specified type, in bits. This method
547/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000548///
549/// FIXME: Pointers into different addr spaces could have different sizes and
550/// alignment requirements: getPointerInfo should take an AddrSpace, this
551/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000552std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000553ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000554 uint64_t Width=0;
555 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000556 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000557#define TYPE(Class, Base)
558#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000559#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000560#define DEPENDENT_TYPE(Class, Base) case Type::Class:
561#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000562 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000563 break;
564
Chris Lattner692233e2007-07-13 22:27:08 +0000565 case Type::FunctionNoProto:
566 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000567 // GCC extension: alignof(function) = 32 bits
568 Width = 0;
569 Align = 32;
570 break;
571
Douglas Gregor72564e72009-02-26 23:50:07 +0000572 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000573 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000574 Width = 0;
575 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
576 break;
577
Steve Narofffb22d962007-08-30 01:06:46 +0000578 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000579 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Chris Lattner98be4942008-03-05 18:54:05 +0000581 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000582 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000583 Align = EltInfo.second;
584 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000585 }
Nate Begeman213541a2008-04-18 23:10:10 +0000586 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000587 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000588 const VectorType *VT = cast<VectorType>(T);
589 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
590 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000591 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000592 // If the alignment is not a power of 2, round up to the next power of 2.
593 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000594 if (VT->getNumElements() & (VT->getNumElements()-1)) {
595 Align = llvm::NextPowerOf2(Align);
596 Width = llvm::RoundUpToAlignment(Width, Align);
597 }
Chris Lattner030d8842007-07-19 22:06:24 +0000598 break;
599 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000600
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000601 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000602 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000603 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000604 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000605 // GCC extension: alignof(void) = 8 bits.
606 Width = 0;
607 Align = 8;
608 break;
609
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000610 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000611 Width = Target.getBoolWidth();
612 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000613 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000614 case BuiltinType::Char_S:
615 case BuiltinType::Char_U:
616 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000617 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000618 Width = Target.getCharWidth();
619 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000620 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000621 case BuiltinType::WChar:
622 Width = Target.getWCharWidth();
623 Align = Target.getWCharAlign();
624 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000625 case BuiltinType::Char16:
626 Width = Target.getChar16Width();
627 Align = Target.getChar16Align();
628 break;
629 case BuiltinType::Char32:
630 Width = Target.getChar32Width();
631 Align = Target.getChar32Align();
632 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000633 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000635 Width = Target.getShortWidth();
636 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000637 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000638 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = Target.getIntWidth();
641 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000643 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000645 Width = Target.getLongWidth();
646 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000647 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000648 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000649 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000650 Width = Target.getLongLongWidth();
651 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000653 case BuiltinType::Int128:
654 case BuiltinType::UInt128:
655 Width = 128;
656 Align = 128; // int128_t is 128-bit aligned on all targets.
657 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000659 Width = Target.getFloatWidth();
660 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000661 break;
662 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000663 Width = Target.getDoubleWidth();
664 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 break;
666 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000667 Width = Target.getLongDoubleWidth();
668 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000669 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000670 case BuiltinType::NullPtr:
671 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
672 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000673 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000674 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000675 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000676 case Type::FixedWidthInt:
677 // FIXME: This isn't precisely correct; the width/alignment should depend
678 // on the available types for the target
679 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000680 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000681 Align = Width;
682 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000683 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000684 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000685 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000687 case Type::BlockPointer: {
688 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
689 Width = Target.getPointerWidth(AS);
690 Align = Target.getPointerAlign(AS);
691 break;
692 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000693 case Type::Pointer: {
694 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000695 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000696 Align = Target.getPointerAlign(AS);
697 break;
698 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000699 case Type::LValueReference:
700 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000701 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000702 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000703 // FIXME: This is wrong for struct layout: a reference in a struct has
704 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000705 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000706 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000707 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
708 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
709 // If we ever want to support other ABIs this needs to be abstracted.
710
Sebastian Redlf30208a2009-01-24 21:16:55 +0000711 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000712 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000713 getTypeInfo(getPointerDiffType());
714 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000715 if (Pointee->isFunctionType())
716 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000717 Align = PtrDiffInfo.second;
718 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000719 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000720 case Type::Complex: {
721 // Complex types have the same alignment as their elements, but twice the
722 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000723 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000724 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000725 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000726 Align = EltInfo.second;
727 break;
728 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000729 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000730 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000731 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
732 Width = Layout.getSize();
733 Align = Layout.getAlignment();
734 break;
735 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000736 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000737 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000738 const TagType *TT = cast<TagType>(T);
739
740 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000741 Width = 1;
742 Align = 1;
743 break;
744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Daniel Dunbar1d751182008-11-08 05:48:37 +0000746 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000747 return getTypeInfo(ET->getDecl()->getIntegerType());
748
Daniel Dunbar1d751182008-11-08 05:48:37 +0000749 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000750 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
751 Width = Layout.getSize();
752 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000753 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000754 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000755
Chris Lattner9fcfe922009-10-22 05:17:15 +0000756 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000757 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
758 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000759
Chris Lattner9fcfe922009-10-22 05:17:15 +0000760 case Type::Elaborated:
761 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
762 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000763
Douglas Gregor18857642009-04-30 17:32:17 +0000764 case Type::Typedef: {
765 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000766 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000767 Align = std::max(Aligned->getMaxAlignment(),
768 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000769 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
770 } else
771 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000772 break;
Chris Lattner71763312008-04-06 22:05:18 +0000773 }
Douglas Gregor18857642009-04-30 17:32:17 +0000774
775 case Type::TypeOfExpr:
776 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
777 .getTypePtr());
778
779 case Type::TypeOf:
780 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
781
Anders Carlsson395b4752009-06-24 19:06:50 +0000782 case Type::Decltype:
783 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
784 .getTypePtr());
785
Douglas Gregor18857642009-04-30 17:32:17 +0000786 case Type::QualifiedName:
787 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor18857642009-04-30 17:32:17 +0000789 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000790 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000791 "Cannot request the size of a dependent type");
792 // FIXME: this is likely to be wrong once we support template
793 // aliases, since a template alias could refer to a typedef that
794 // has an __aligned__ attribute on it.
795 return getTypeInfo(getCanonicalType(T));
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattner464175b2007-07-18 17:52:12 +0000798 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000799 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000800}
801
Chris Lattner34ebde42009-01-27 18:08:34 +0000802/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
803/// type for the current target in bits. This can be different than the ABI
804/// alignment in cases where it is beneficial for performance to overalign
805/// a data type.
806unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
807 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000808
809 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000810 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000811 T = CT->getElementType().getTypePtr();
812 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
813 T->isSpecificBuiltinType(BuiltinType::LongLong))
814 return std::max(ABIAlign, (unsigned)getTypeSize(T));
815
Chris Lattner34ebde42009-01-27 18:08:34 +0000816 return ABIAlign;
817}
818
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000819static void CollectLocalObjCIvars(ASTContext *Ctx,
820 const ObjCInterfaceDecl *OI,
821 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000822 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
823 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000824 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000825 if (!IVDecl->isInvalidDecl())
826 Fields.push_back(cast<FieldDecl>(IVDecl));
827 }
828}
829
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000830void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
831 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
832 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
833 CollectObjCIvars(SuperClass, Fields);
834 CollectLocalObjCIvars(this, OI, Fields);
835}
836
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000837/// ShallowCollectObjCIvars -
838/// Collect all ivars, including those synthesized, in the current class.
839///
840void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
841 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
842 bool CollectSynthesized) {
843 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
844 E = OI->ivar_end(); I != E; ++I) {
845 Ivars.push_back(*I);
846 }
847 if (CollectSynthesized)
848 CollectSynthesizedIvars(OI, Ivars);
849}
850
Fariborz Jahanian98200742009-05-12 18:14:29 +0000851void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
852 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000853 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
854 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000855 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
856 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Fariborz Jahanian98200742009-05-12 18:14:29 +0000858 // Also look into nested protocols.
859 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
860 E = PD->protocol_end(); P != E; ++P)
861 CollectProtocolSynthesizedIvars(*P, Ivars);
862}
863
864/// CollectSynthesizedIvars -
865/// This routine collect synthesized ivars for the designated class.
866///
867void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
868 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000869 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
870 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000871 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
872 Ivars.push_back(Ivar);
873 }
874 // Also look into interface's protocol list for properties declared
875 // in the protocol and whose ivars are synthesized.
876 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
877 PE = OI->protocol_end(); P != PE; ++P) {
878 ObjCProtocolDecl *PD = (*P);
879 CollectProtocolSynthesizedIvars(PD, Ivars);
880 }
881}
882
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000883/// CollectInheritedProtocols - Collect all protocols in current class and
884/// those inherited by it.
885void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
886 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
887 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
888 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
889 PE = OI->protocol_end(); P != PE; ++P) {
890 ObjCProtocolDecl *Proto = (*P);
891 Protocols.push_back(Proto);
892 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
893 PE = Proto->protocol_end(); P != PE; ++P)
894 CollectInheritedProtocols(*P, Protocols);
895 }
896
897 // Categories of this Interface.
898 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
899 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
900 CollectInheritedProtocols(CDeclChain, Protocols);
901 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
902 while (SD) {
903 CollectInheritedProtocols(SD, Protocols);
904 SD = SD->getSuperClass();
905 }
906 return;
907 }
908 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
909 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
910 PE = OC->protocol_end(); P != PE; ++P) {
911 ObjCProtocolDecl *Proto = (*P);
912 Protocols.push_back(Proto);
913 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
914 PE = Proto->protocol_end(); P != PE; ++P)
915 CollectInheritedProtocols(*P, Protocols);
916 }
917 return;
918 }
919 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
920 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
921 PE = OP->protocol_end(); P != PE; ++P) {
922 ObjCProtocolDecl *Proto = (*P);
923 Protocols.push_back(Proto);
924 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
925 PE = Proto->protocol_end(); P != PE; ++P)
926 CollectInheritedProtocols(*P, Protocols);
927 }
928 return;
929 }
930}
931
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000932unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
933 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000934 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
935 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000936 if ((*I)->getPropertyIvarDecl())
937 ++count;
938
939 // Also look into nested protocols.
940 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
941 E = PD->protocol_end(); P != E; ++P)
942 count += CountProtocolSynthesizedIvars(*P);
943 return count;
944}
945
Mike Stump1eb44332009-09-09 15:08:12 +0000946unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000947 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000948 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
949 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000950 if ((*I)->getPropertyIvarDecl())
951 ++count;
952 }
953 // Also look into interface's protocol list for properties declared
954 // in the protocol and whose ivars are synthesized.
955 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
956 PE = OI->protocol_end(); P != PE; ++P) {
957 ObjCProtocolDecl *PD = (*P);
958 count += CountProtocolSynthesizedIvars(PD);
959 }
960 return count;
961}
962
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000963/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
964ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
965 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
966 I = ObjCImpls.find(D);
967 if (I != ObjCImpls.end())
968 return cast<ObjCImplementationDecl>(I->second);
969 return 0;
970}
971/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
972ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
973 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
974 I = ObjCImpls.find(D);
975 if (I != ObjCImpls.end())
976 return cast<ObjCCategoryImplDecl>(I->second);
977 return 0;
978}
979
980/// \brief Set the implementation of ObjCInterfaceDecl.
981void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
982 ObjCImplementationDecl *ImplD) {
983 assert(IFaceD && ImplD && "Passed null params");
984 ObjCImpls[IFaceD] = ImplD;
985}
986/// \brief Set the implementation of ObjCCategoryDecl.
987void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
988 ObjCCategoryImplDecl *ImplD) {
989 assert(CatD && ImplD && "Passed null params");
990 ObjCImpls[CatD] = ImplD;
991}
992
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000993/// \brief Allocate an uninitialized DeclaratorInfo.
994///
995/// The caller should initialize the memory held by DeclaratorInfo using
996/// the TypeLoc wrappers.
997///
998/// \param T the type that will be the basis for type source info. This type
999/// should refer to how the declarator was written in source code, not to
1000/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +00001001DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
1002 unsigned DataSize) {
1003 if (!DataSize)
1004 DataSize = TypeLoc::getFullDataSizeForType(T);
1005 else
1006 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1007 "incorrect data size provided to CreateDeclaratorInfo!");
1008
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001009 DeclaratorInfo *DInfo =
1010 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1011 new (DInfo) DeclaratorInfo(T);
1012 return DInfo;
1013}
1014
John McCalla4eb74d2009-10-23 21:14:09 +00001015DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1016 SourceLocation L) {
1017 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1018 DI->getTypeLoc().initialize(L);
1019 return DI;
1020}
1021
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001022/// getInterfaceLayoutImpl - Get or compute information about the
1023/// layout of the given interface.
1024///
1025/// \param Impl - If given, also include the layout of the interface's
1026/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001027const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001028ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1029 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001030 assert(!D->isForwardDecl() && "Invalid interface decl!");
1031
Devang Patel44a3dde2008-06-04 21:54:36 +00001032 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001033 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001034 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1035 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1036 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001037
Daniel Dunbar453addb2009-05-03 11:16:44 +00001038 // Add in synthesized ivar count if laying out an implementation.
1039 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001040 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001041 unsigned SynthCount = CountSynthesizedIvars(D);
1042 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001043 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001044 // entry. Note we can't cache this because we simply free all
1045 // entries later; however we shouldn't look up implementations
1046 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001047 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001048 return getObjCLayout(D, 0);
1049 }
1050
Mike Stump1eb44332009-09-09 15:08:12 +00001051 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001052 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1053 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Devang Patel44a3dde2008-06-04 21:54:36 +00001055 return *NewEntry;
1056}
1057
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001058const ASTRecordLayout &
1059ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1060 return getObjCLayout(D, 0);
1061}
1062
1063const ASTRecordLayout &
1064ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1065 return getObjCLayout(D->getClassInterface(), D);
1066}
1067
Devang Patel88a981b2007-11-01 19:11:01 +00001068/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001069/// specified record (struct/union/class), which indicates its size and field
1070/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001071const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001072 D = D->getDefinition(*this);
1073 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001074
Chris Lattner464175b2007-07-18 17:52:12 +00001075 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001076 // Note that we can't save a reference to the entry because this function
1077 // is recursive.
1078 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001079 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001080
Mike Stump1eb44332009-09-09 15:08:12 +00001081 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001082 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001083 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner5d2a6302007-07-18 18:26:58 +00001085 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001086}
1087
Chris Lattnera7674d82007-07-13 22:13:22 +00001088//===----------------------------------------------------------------------===//
1089// Type creation/memoization methods
1090//===----------------------------------------------------------------------===//
1091
John McCall0953e762009-09-24 19:53:00 +00001092QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1093 unsigned Fast = Quals.getFastQualifiers();
1094 Quals.removeFastQualifiers();
1095
1096 // Check if we've already instantiated this type.
1097 llvm::FoldingSetNodeID ID;
1098 ExtQuals::Profile(ID, TypeNode, Quals);
1099 void *InsertPos = 0;
1100 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1101 assert(EQ->getQualifiers() == Quals);
1102 QualType T = QualType(EQ, Fast);
1103 return T;
1104 }
1105
John McCall6b304a02009-09-24 23:30:46 +00001106 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001107 ExtQualNodes.InsertNode(New, InsertPos);
1108 QualType T = QualType(New, Fast);
1109 return T;
1110}
1111
1112QualType ASTContext::getVolatileType(QualType T) {
1113 QualType CanT = getCanonicalType(T);
1114 if (CanT.isVolatileQualified()) return T;
1115
1116 QualifierCollector Quals;
1117 const Type *TypeNode = Quals.strip(T);
1118 Quals.addVolatile();
1119
1120 return getExtQualType(TypeNode, Quals);
1121}
1122
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001123QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001124 QualType CanT = getCanonicalType(T);
1125 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001126 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001127
John McCall0953e762009-09-24 19:53:00 +00001128 // If we are composing extended qualifiers together, merge together
1129 // into one ExtQuals node.
1130 QualifierCollector Quals;
1131 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
John McCall0953e762009-09-24 19:53:00 +00001133 // If this type already has an address space specified, it cannot get
1134 // another one.
1135 assert(!Quals.hasAddressSpace() &&
1136 "Type cannot be in multiple addr spaces!");
1137 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001138
John McCall0953e762009-09-24 19:53:00 +00001139 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001140}
1141
Chris Lattnerb7d25532009-02-18 22:53:11 +00001142QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001143 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001144 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001145 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001146 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001148 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001149 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001150 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001151 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1152 return getPointerType(ResultType);
1153 }
1154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155
John McCall0953e762009-09-24 19:53:00 +00001156 // If we are composing extended qualifiers together, merge together
1157 // into one ExtQuals node.
1158 QualifierCollector Quals;
1159 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCall0953e762009-09-24 19:53:00 +00001161 // If this type already has an ObjCGC specified, it cannot get
1162 // another one.
1163 assert(!Quals.hasObjCGCAttr() &&
1164 "Type cannot have multiple ObjCGCs!");
1165 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001166
John McCall0953e762009-09-24 19:53:00 +00001167 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001168}
Chris Lattnera7674d82007-07-13 22:13:22 +00001169
Mike Stump24556362009-07-25 21:26:53 +00001170QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001171 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001172 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001173 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001174 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001175 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001176 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001177 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001178 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001179 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001180 } else {
1181 assert (T->isFunctionType()
1182 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001184 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1185 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001186 } else {
1187 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1188 ResultType
1189 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1190 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1191 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1192 F->getNumExceptions(), F->exception_begin(), true);
1193 }
Mike Stump24556362009-07-25 21:26:53 +00001194 }
John McCall0953e762009-09-24 19:53:00 +00001195
Douglas Gregora4923eb2009-11-16 21:35:15 +00001196 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001197}
1198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199/// getComplexType - Return the uniqued reference to the type for a complex
1200/// number with the specified element type.
1201QualType ASTContext::getComplexType(QualType T) {
1202 // Unique pointers, to guarantee there is only one pointer of a particular
1203 // structure.
1204 llvm::FoldingSetNodeID ID;
1205 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 void *InsertPos = 0;
1208 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1209 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 // If the pointee type isn't canonical, this won't be a canonical type either,
1212 // so fill in the canonical type field.
1213 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001214 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001215 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 // Get the new insert position for the node we care about.
1218 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001219 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 }
John McCall6b304a02009-09-24 23:30:46 +00001221 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 Types.push_back(New);
1223 ComplexTypes.InsertNode(New, InsertPos);
1224 return QualType(New, 0);
1225}
1226
Eli Friedmanf98aba32009-02-13 02:31:07 +00001227QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1228 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1229 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1230 FixedWidthIntType *&Entry = Map[Width];
1231 if (!Entry)
1232 Entry = new FixedWidthIntType(Width, Signed);
1233 return QualType(Entry, 0);
1234}
Reid Spencer5f016e22007-07-11 17:01:13 +00001235
1236/// getPointerType - Return the uniqued reference to the type for a pointer to
1237/// the specified type.
1238QualType ASTContext::getPointerType(QualType T) {
1239 // Unique pointers, to guarantee there is only one pointer of a particular
1240 // structure.
1241 llvm::FoldingSetNodeID ID;
1242 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 void *InsertPos = 0;
1245 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1246 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 // If the pointee type isn't canonical, this won't be a canonical type either,
1249 // so fill in the canonical type field.
1250 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001251 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001252 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // Get the new insert position for the node we care about.
1255 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001256 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 }
John McCall6b304a02009-09-24 23:30:46 +00001258 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 Types.push_back(New);
1260 PointerTypes.InsertNode(New, InsertPos);
1261 return QualType(New, 0);
1262}
1263
Mike Stump1eb44332009-09-09 15:08:12 +00001264/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001265/// a pointer to the specified block.
1266QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001267 assert(T->isFunctionType() && "block of function types only");
1268 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001269 // structure.
1270 llvm::FoldingSetNodeID ID;
1271 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Steve Naroff5618bd42008-08-27 16:04:49 +00001273 void *InsertPos = 0;
1274 if (BlockPointerType *PT =
1275 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1276 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
1278 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001279 // type either so fill in the canonical type field.
1280 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001281 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001282 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Steve Naroff5618bd42008-08-27 16:04:49 +00001284 // Get the new insert position for the node we care about.
1285 BlockPointerType *NewIP =
1286 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001287 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001288 }
John McCall6b304a02009-09-24 23:30:46 +00001289 BlockPointerType *New
1290 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001291 Types.push_back(New);
1292 BlockPointerTypes.InsertNode(New, InsertPos);
1293 return QualType(New, 0);
1294}
1295
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001296/// getLValueReferenceType - Return the uniqued reference to the type for an
1297/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001298QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 // Unique pointers, to guarantee there is only one pointer of a particular
1300 // structure.
1301 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001302 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001303
1304 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305 if (LValueReferenceType *RT =
1306 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001308
John McCall54e14c42009-10-22 22:37:11 +00001309 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1310
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 // If the referencee type isn't canonical, this won't be a canonical type
1312 // either, so fill in the canonical type field.
1313 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001314 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1315 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1316 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001319 LValueReferenceType *NewIP =
1320 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001321 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 }
1323
John McCall6b304a02009-09-24 23:30:46 +00001324 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001325 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1326 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001328 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001329
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001330 return QualType(New, 0);
1331}
1332
1333/// getRValueReferenceType - Return the uniqued reference to the type for an
1334/// rvalue reference to the specified type.
1335QualType ASTContext::getRValueReferenceType(QualType T) {
1336 // Unique pointers, to guarantee there is only one pointer of a particular
1337 // structure.
1338 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001339 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001340
1341 void *InsertPos = 0;
1342 if (RValueReferenceType *RT =
1343 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1344 return QualType(RT, 0);
1345
John McCall54e14c42009-10-22 22:37:11 +00001346 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1347
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001348 // If the referencee type isn't canonical, this won't be a canonical type
1349 // either, so fill in the canonical type field.
1350 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001351 if (InnerRef || !T.isCanonical()) {
1352 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1353 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001354
1355 // Get the new insert position for the node we care about.
1356 RValueReferenceType *NewIP =
1357 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1358 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1359 }
1360
John McCall6b304a02009-09-24 23:30:46 +00001361 RValueReferenceType *New
1362 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001363 Types.push_back(New);
1364 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 return QualType(New, 0);
1366}
1367
Sebastian Redlf30208a2009-01-24 21:16:55 +00001368/// getMemberPointerType - Return the uniqued reference to the type for a
1369/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001370QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001371 // Unique pointers, to guarantee there is only one pointer of a particular
1372 // structure.
1373 llvm::FoldingSetNodeID ID;
1374 MemberPointerType::Profile(ID, T, Cls);
1375
1376 void *InsertPos = 0;
1377 if (MemberPointerType *PT =
1378 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1379 return QualType(PT, 0);
1380
1381 // If the pointee or class type isn't canonical, this won't be a canonical
1382 // type either, so fill in the canonical type field.
1383 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001384 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001385 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1386
1387 // Get the new insert position for the node we care about.
1388 MemberPointerType *NewIP =
1389 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1390 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1391 }
John McCall6b304a02009-09-24 23:30:46 +00001392 MemberPointerType *New
1393 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001394 Types.push_back(New);
1395 MemberPointerTypes.InsertNode(New, InsertPos);
1396 return QualType(New, 0);
1397}
1398
Mike Stump1eb44332009-09-09 15:08:12 +00001399/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001400/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001401QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001402 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001403 ArrayType::ArraySizeModifier ASM,
1404 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001405 assert((EltTy->isDependentType() ||
1406 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001407 "Constant array of VLAs is illegal!");
1408
Chris Lattner38aeec72009-05-13 04:12:56 +00001409 // Convert the array size into a canonical width matching the pointer size for
1410 // the target.
1411 llvm::APInt ArySize(ArySizeIn);
1412 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001415 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001418 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001419 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 // If the element type isn't canonical, this won't be a canonical type either,
1423 // so fill in the canonical type field.
1424 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001425 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001426 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001427 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001429 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001430 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001431 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
John McCall6b304a02009-09-24 23:30:46 +00001434 ConstantArrayType *New = new(*this,TypeAlignment)
1435 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001436 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 Types.push_back(New);
1438 return QualType(New, 0);
1439}
1440
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001441/// getVariableArrayType - Returns a non-unique reference to the type for a
1442/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001443QualType ASTContext::getVariableArrayType(QualType EltTy,
1444 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001445 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001446 unsigned EltTypeQuals,
1447 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001448 // Since we don't unique expressions, it isn't possible to unique VLA's
1449 // that have an expression provided for their size.
1450
John McCall6b304a02009-09-24 23:30:46 +00001451 VariableArrayType *New = new(*this, TypeAlignment)
1452 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001453
1454 VariableArrayTypes.push_back(New);
1455 Types.push_back(New);
1456 return QualType(New, 0);
1457}
1458
Douglas Gregor898574e2008-12-05 23:32:09 +00001459/// getDependentSizedArrayType - Returns a non-unique reference to
1460/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001461/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001462QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1463 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001464 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001465 unsigned EltTypeQuals,
1466 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001467 assert((!NumElts || NumElts->isTypeDependent() ||
1468 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001469 "Size must be type- or value-dependent!");
1470
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001471 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001472 DependentSizedArrayType *Canon = 0;
1473
1474 if (NumElts) {
1475 // Dependently-sized array types that do not have a specified
1476 // number of elements will have their sizes deduced from an
1477 // initializer.
1478 llvm::FoldingSetNodeID ID;
1479 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1480 EltTypeQuals, NumElts);
1481
1482 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1483 }
1484
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001485 DependentSizedArrayType *New;
1486 if (Canon) {
1487 // We already have a canonical version of this array type; use it as
1488 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001489 New = new (*this, TypeAlignment)
1490 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1491 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001492 } else {
1493 QualType CanonEltTy = getCanonicalType(EltTy);
1494 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001495 New = new (*this, TypeAlignment)
1496 DependentSizedArrayType(*this, EltTy, QualType(),
1497 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001498
1499 if (NumElts)
1500 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001501 } else {
1502 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1503 ASM, EltTypeQuals,
1504 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001505 New = new (*this, TypeAlignment)
1506 DependentSizedArrayType(*this, EltTy, Canon,
1507 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001508 }
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Douglas Gregor898574e2008-12-05 23:32:09 +00001511 Types.push_back(New);
1512 return QualType(New, 0);
1513}
1514
Eli Friedmanc5773c42008-02-15 18:16:39 +00001515QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1516 ArrayType::ArraySizeModifier ASM,
1517 unsigned EltTypeQuals) {
1518 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001519 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001520
1521 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001522 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001523 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1524 return QualType(ATP, 0);
1525
1526 // If the element type isn't canonical, this won't be a canonical type
1527 // either, so fill in the canonical type field.
1528 QualType Canonical;
1529
John McCall467b27b2009-10-22 20:10:53 +00001530 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001531 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001532 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001533
1534 // Get the new insert position for the node we care about.
1535 IncompleteArrayType *NewIP =
1536 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001537 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001538 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001539
John McCall6b304a02009-09-24 23:30:46 +00001540 IncompleteArrayType *New = new (*this, TypeAlignment)
1541 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001542
1543 IncompleteArrayTypes.InsertNode(New, InsertPos);
1544 Types.push_back(New);
1545 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001546}
1547
Steve Naroff73322922007-07-18 18:00:27 +00001548/// getVectorType - Return the unique reference to a vector type of
1549/// the specified element type and size. VectorType must be a built-in type.
1550QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattnerf52ab252008-04-06 22:59:24 +00001553 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001554 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // Check if we've already instantiated a vector of this type.
1557 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001558 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 void *InsertPos = 0;
1560 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1561 return QualType(VTP, 0);
1562
1563 // If the element type isn't canonical, this won't be a canonical type either,
1564 // so fill in the canonical type field.
1565 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001566 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001567 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // Get the new insert position for the node we care about.
1570 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001571 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 }
John McCall6b304a02009-09-24 23:30:46 +00001573 VectorType *New = new (*this, TypeAlignment)
1574 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 VectorTypes.InsertNode(New, InsertPos);
1576 Types.push_back(New);
1577 return QualType(New, 0);
1578}
1579
Nate Begeman213541a2008-04-18 23:10:10 +00001580/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001581/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001582QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001583 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Chris Lattnerf52ab252008-04-06 22:59:24 +00001585 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001586 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Steve Naroff73322922007-07-18 18:00:27 +00001588 // Check if we've already instantiated a vector of this type.
1589 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001590 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001591 void *InsertPos = 0;
1592 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1593 return QualType(VTP, 0);
1594
1595 // If the element type isn't canonical, this won't be a canonical type either,
1596 // so fill in the canonical type field.
1597 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001598 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001599 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Steve Naroff73322922007-07-18 18:00:27 +00001601 // Get the new insert position for the node we care about.
1602 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001603 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001604 }
John McCall6b304a02009-09-24 23:30:46 +00001605 ExtVectorType *New = new (*this, TypeAlignment)
1606 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001607 VectorTypes.InsertNode(New, InsertPos);
1608 Types.push_back(New);
1609 return QualType(New, 0);
1610}
1611
Mike Stump1eb44332009-09-09 15:08:12 +00001612QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001613 Expr *SizeExpr,
1614 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001615 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001616 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001617 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001619 void *InsertPos = 0;
1620 DependentSizedExtVectorType *Canon
1621 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1622 DependentSizedExtVectorType *New;
1623 if (Canon) {
1624 // We already have a canonical version of this array type; use it as
1625 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001626 New = new (*this, TypeAlignment)
1627 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1628 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001629 } else {
1630 QualType CanonVecTy = getCanonicalType(vecType);
1631 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001632 New = new (*this, TypeAlignment)
1633 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1634 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001635 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1636 } else {
1637 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1638 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001639 New = new (*this, TypeAlignment)
1640 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001641 }
1642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001644 Types.push_back(New);
1645 return QualType(New, 0);
1646}
1647
Douglas Gregor72564e72009-02-26 23:50:07 +00001648/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001649///
Mike Stump24556362009-07-25 21:26:53 +00001650QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 // Unique functions, to guarantee there is only one function of a particular
1652 // structure.
1653 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001654 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001657 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001658 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001662 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001663 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001666 FunctionNoProtoType *NewIP =
1667 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001668 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670
John McCall6b304a02009-09-24 23:30:46 +00001671 FunctionNoProtoType *New = new (*this, TypeAlignment)
1672 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001674 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 return QualType(New, 0);
1676}
1677
1678/// getFunctionType - Return a normal function type with a typed argument
1679/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001680QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001681 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001682 unsigned TypeQuals, bool hasExceptionSpec,
1683 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001684 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // Unique functions, to guarantee there is only one function of a particular
1686 // structure.
1687 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001688 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001689 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001690 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001691
1692 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001693 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001694 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001696
1697 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001698 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001700 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 isCanonical = false;
1702
1703 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001704 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 QualType Canonical;
1706 if (!isCanonical) {
1707 llvm::SmallVector<QualType, 16> CanonicalArgs;
1708 CanonicalArgs.reserve(NumArgs);
1709 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001710 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001711
Chris Lattnerf52ab252008-04-06 22:59:24 +00001712 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001713 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001714 isVariadic, TypeQuals, false,
1715 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001718 FunctionProtoType *NewIP =
1719 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001720 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001722
Douglas Gregor72564e72009-02-26 23:50:07 +00001723 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001724 // for two variable size arrays (for parameter and exception types) at the
1725 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001726 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001727 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1728 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001729 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001730 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001731 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001732 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001734 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 return QualType(FTP, 0);
1736}
1737
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001738/// getTypeDeclType - Return the unique reference to the type for the
1739/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001740QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001741 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001742 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001744 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001745 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001746 else if (isa<TemplateTypeParmDecl>(Decl)) {
1747 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001748 } else if (ObjCInterfaceDecl *ObjCInterface
1749 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001750 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001751
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001752 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001753 if (PrevDecl)
1754 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001755 else
John McCall6b304a02009-09-24 23:30:46 +00001756 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001757 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001758 if (PrevDecl)
1759 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001760 else
John McCall6b304a02009-09-24 23:30:46 +00001761 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001762 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001763 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001764
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001765 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001766 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001767}
1768
Reid Spencer5f016e22007-07-11 17:01:13 +00001769/// getTypedefType - Return the unique reference to the type for the
1770/// specified typename decl.
1771QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1772 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Chris Lattnerf52ab252008-04-06 22:59:24 +00001774 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001775 Decl->TypeForDecl = new(*this, TypeAlignment)
1776 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 Types.push_back(Decl->TypeForDecl);
1778 return QualType(Decl->TypeForDecl, 0);
1779}
1780
John McCall49a832b2009-10-18 09:09:24 +00001781/// \brief Retrieve a substitution-result type.
1782QualType
1783ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1784 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001785 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001786 && "replacement types must always be canonical");
1787
1788 llvm::FoldingSetNodeID ID;
1789 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1790 void *InsertPos = 0;
1791 SubstTemplateTypeParmType *SubstParm
1792 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1793
1794 if (!SubstParm) {
1795 SubstParm = new (*this, TypeAlignment)
1796 SubstTemplateTypeParmType(Parm, Replacement);
1797 Types.push_back(SubstParm);
1798 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1799 }
1800
1801 return QualType(SubstParm, 0);
1802}
1803
Douglas Gregorfab9d672009-02-05 23:33:38 +00001804/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001805/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001806/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001807QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001808 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001809 IdentifierInfo *Name) {
1810 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001811 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001812 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001813 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001814 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1815
1816 if (TypeParm)
1817 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001819 if (Name) {
1820 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001821 TypeParm = new (*this, TypeAlignment)
1822 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001823 } else
John McCall6b304a02009-09-24 23:30:46 +00001824 TypeParm = new (*this, TypeAlignment)
1825 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001826
1827 Types.push_back(TypeParm);
1828 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1829
1830 return QualType(TypeParm, 0);
1831}
1832
Mike Stump1eb44332009-09-09 15:08:12 +00001833QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001834ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001835 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001836 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001837 unsigned NumArgs = Args.size();
1838
John McCall833ca992009-10-29 08:12:44 +00001839 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1840 ArgVec.reserve(NumArgs);
1841 for (unsigned i = 0; i != NumArgs; ++i)
1842 ArgVec.push_back(Args[i].getArgument());
1843
1844 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1845}
1846
1847QualType
1848ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001849 const TemplateArgument *Args,
1850 unsigned NumArgs,
1851 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001852 if (!Canon.isNull())
1853 Canon = getCanonicalType(Canon);
1854 else {
1855 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001856 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1857 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1858 CanonArgs.reserve(NumArgs);
1859 for (unsigned I = 0; I != NumArgs; ++I)
1860 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1861
1862 // Determine whether this canonical template specialization type already
1863 // exists.
1864 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001865 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001866 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001867
1868 void *InsertPos = 0;
1869 TemplateSpecializationType *Spec
1870 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Douglas Gregor1275ae02009-07-28 23:00:59 +00001872 if (!Spec) {
1873 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001874 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001875 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001876 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001877 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001878 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001879 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001880 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001881 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001882 }
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Douglas Gregorb88e8882009-07-30 17:40:51 +00001884 if (Canon.isNull())
1885 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001886 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001887 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001888 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001889
Douglas Gregor1275ae02009-07-28 23:00:59 +00001890 // Allocate the (non-canonical) template specialization type, but don't
1891 // try to unique it: these types typically have location information that
1892 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001893 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001894 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001895 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001896 TemplateSpecializationType *Spec
1897 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001898 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregor55f6b142009-02-09 18:46:07 +00001900 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001901 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001902}
1903
Mike Stump1eb44332009-09-09 15:08:12 +00001904QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001905ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001906 QualType NamedType) {
1907 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001908 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001909
1910 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001912 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1913 if (T)
1914 return QualType(T, 0);
1915
Mike Stump1eb44332009-09-09 15:08:12 +00001916 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001917 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001918 Types.push_back(T);
1919 QualifiedNameTypes.InsertNode(T, InsertPos);
1920 return QualType(T, 0);
1921}
1922
Mike Stump1eb44332009-09-09 15:08:12 +00001923QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001924 const IdentifierInfo *Name,
1925 QualType Canon) {
1926 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1927
1928 if (Canon.isNull()) {
1929 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1930 if (CanonNNS != NNS)
1931 Canon = getTypenameType(CanonNNS, Name);
1932 }
1933
1934 llvm::FoldingSetNodeID ID;
1935 TypenameType::Profile(ID, NNS, Name);
1936
1937 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001938 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001939 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1940 if (T)
1941 return QualType(T, 0);
1942
1943 T = new (*this) TypenameType(NNS, Name, Canon);
1944 Types.push_back(T);
1945 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001946 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001947}
1948
Mike Stump1eb44332009-09-09 15:08:12 +00001949QualType
1950ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001951 const TemplateSpecializationType *TemplateId,
1952 QualType Canon) {
1953 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1954
1955 if (Canon.isNull()) {
1956 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1957 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1958 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1959 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001960 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001961 assert(CanonTemplateId &&
1962 "Canonical type must also be a template specialization type");
1963 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1964 }
1965 }
1966
1967 llvm::FoldingSetNodeID ID;
1968 TypenameType::Profile(ID, NNS, TemplateId);
1969
1970 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001971 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001972 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1973 if (T)
1974 return QualType(T, 0);
1975
1976 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1977 Types.push_back(T);
1978 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001979 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001980}
1981
John McCall7da24312009-09-05 00:15:47 +00001982QualType
1983ASTContext::getElaboratedType(QualType UnderlyingType,
1984 ElaboratedType::TagKind Tag) {
1985 llvm::FoldingSetNodeID ID;
1986 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
John McCall7da24312009-09-05 00:15:47 +00001988 void *InsertPos = 0;
1989 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1990 if (T)
1991 return QualType(T, 0);
1992
1993 QualType Canon = getCanonicalType(UnderlyingType);
1994
1995 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1996 Types.push_back(T);
1997 ElaboratedTypes.InsertNode(T, InsertPos);
1998 return QualType(T, 0);
1999}
2000
Chris Lattner88cb27a2008-04-07 04:56:42 +00002001/// CmpProtocolNames - Comparison predicate for sorting protocols
2002/// alphabetically.
2003static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2004 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002005 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002006}
2007
John McCall54e14c42009-10-22 22:37:11 +00002008static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2009 unsigned NumProtocols) {
2010 if (NumProtocols == 0) return true;
2011
2012 for (unsigned i = 1; i != NumProtocols; ++i)
2013 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2014 return false;
2015 return true;
2016}
2017
2018static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002019 unsigned &NumProtocols) {
2020 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Chris Lattner88cb27a2008-04-07 04:56:42 +00002022 // Sort protocols, keyed by name.
2023 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2024
2025 // Remove duplicates.
2026 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2027 NumProtocols = ProtocolsEnd-Protocols;
2028}
2029
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002030/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2031/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002032QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002033 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002034 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002035 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002036 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002037
2038 void *InsertPos = 0;
2039 if (ObjCObjectPointerType *QT =
2040 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2041 return QualType(QT, 0);
2042
John McCall54e14c42009-10-22 22:37:11 +00002043 // Sort the protocol list alphabetically to canonicalize it.
2044 QualType Canonical;
2045 if (!InterfaceT.isCanonical() ||
2046 !areSortedAndUniqued(Protocols, NumProtocols)) {
2047 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2048 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2049 unsigned UniqueCount = NumProtocols;
2050
2051 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2052 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2053
2054 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2055 &Sorted[0], UniqueCount);
2056 } else {
2057 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2058 Protocols, NumProtocols);
2059 }
2060
2061 // Regenerate InsertPos.
2062 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2063 }
2064
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002065 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002066 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002067 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002069 Types.push_back(QType);
2070 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2071 return QualType(QType, 0);
2072}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002073
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002074/// getObjCInterfaceType - Return the unique reference to the type for the
2075/// specified ObjC interface decl. The list of protocols is optional.
2076QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002077 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002078 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002079 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002081 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002082 if (ObjCInterfaceType *QT =
2083 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002084 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002085
John McCall54e14c42009-10-22 22:37:11 +00002086 // Sort the protocol list alphabetically to canonicalize it.
2087 QualType Canonical;
2088 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2089 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2090 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2091
2092 unsigned UniqueCount = NumProtocols;
2093 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2094
2095 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2096
2097 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2098 }
2099
John McCall6b304a02009-09-24 23:30:46 +00002100 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002101 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002102 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002103
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002104 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002105 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002106 return QualType(QType, 0);
2107}
2108
Douglas Gregor72564e72009-02-26 23:50:07 +00002109/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2110/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002111/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002112/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002113/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002114QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002115 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002116 if (tofExpr->isTypeDependent()) {
2117 llvm::FoldingSetNodeID ID;
2118 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregorb1975722009-07-30 23:18:24 +00002120 void *InsertPos = 0;
2121 DependentTypeOfExprType *Canon
2122 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2123 if (Canon) {
2124 // We already have a "canonical" version of an identical, dependent
2125 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002126 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002127 QualType((TypeOfExprType*)Canon, 0));
2128 }
2129 else {
2130 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002131 Canon
2132 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002133 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2134 toe = Canon;
2135 }
2136 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002137 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002138 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002139 }
Steve Naroff9752f252007-08-01 18:02:17 +00002140 Types.push_back(toe);
2141 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002142}
2143
Steve Naroff9752f252007-08-01 18:02:17 +00002144/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2145/// TypeOfType AST's. The only motivation to unique these nodes would be
2146/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002147/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002148/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002149QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002150 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002151 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002152 Types.push_back(tot);
2153 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002154}
2155
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002156/// getDecltypeForExpr - Given an expr, will return the decltype for that
2157/// expression, according to the rules in C++0x [dcl.type.simple]p4
2158static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002159 if (e->isTypeDependent())
2160 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002162 // If e is an id expression or a class member access, decltype(e) is defined
2163 // as the type of the entity named by e.
2164 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2165 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2166 return VD->getType();
2167 }
2168 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2169 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2170 return FD->getType();
2171 }
2172 // If e is a function call or an invocation of an overloaded operator,
2173 // (parentheses around e are ignored), decltype(e) is defined as the
2174 // return type of that function.
2175 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2176 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002178 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002179
2180 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002181 // defined as T&, otherwise decltype(e) is defined as T.
2182 if (e->isLvalue(Context) == Expr::LV_Valid)
2183 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002185 return T;
2186}
2187
Anders Carlsson395b4752009-06-24 19:06:50 +00002188/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2189/// DecltypeType AST's. The only motivation to unique these nodes would be
2190/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002191/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002192/// on canonical type's (which are always unique).
2193QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002194 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002195 if (e->isTypeDependent()) {
2196 llvm::FoldingSetNodeID ID;
2197 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002199 void *InsertPos = 0;
2200 DependentDecltypeType *Canon
2201 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2202 if (Canon) {
2203 // We already have a "canonical" version of an equivalent, dependent
2204 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002205 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002206 QualType((DecltypeType*)Canon, 0));
2207 }
2208 else {
2209 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002210 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002211 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2212 dt = Canon;
2213 }
2214 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002215 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002216 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002217 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002218 Types.push_back(dt);
2219 return QualType(dt, 0);
2220}
2221
Reid Spencer5f016e22007-07-11 17:01:13 +00002222/// getTagDeclType - Return the unique reference to the type for the
2223/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002224QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002225 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002226 // FIXME: What is the design on getTagDeclType when it requires casting
2227 // away const? mutable?
2228 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002229}
2230
Mike Stump1eb44332009-09-09 15:08:12 +00002231/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2232/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2233/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002234QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002235 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002236}
2237
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002238/// getSignedWCharType - Return the type of "signed wchar_t".
2239/// Used when in C++, as a GCC extension.
2240QualType ASTContext::getSignedWCharType() const {
2241 // FIXME: derive from "Target" ?
2242 return WCharTy;
2243}
2244
2245/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2246/// Used when in C++, as a GCC extension.
2247QualType ASTContext::getUnsignedWCharType() const {
2248 // FIXME: derive from "Target" ?
2249 return UnsignedIntTy;
2250}
2251
Chris Lattner8b9023b2007-07-13 03:05:23 +00002252/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2253/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2254QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002255 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002256}
2257
Chris Lattnere6327742008-04-02 05:18:44 +00002258//===----------------------------------------------------------------------===//
2259// Type Operators
2260//===----------------------------------------------------------------------===//
2261
John McCall54e14c42009-10-22 22:37:11 +00002262CanQualType ASTContext::getCanonicalParamType(QualType T) {
2263 // Push qualifiers into arrays, and then discard any remaining
2264 // qualifiers.
2265 T = getCanonicalType(T);
2266 const Type *Ty = T.getTypePtr();
2267
2268 QualType Result;
2269 if (isa<ArrayType>(Ty)) {
2270 Result = getArrayDecayedType(QualType(Ty,0));
2271 } else if (isa<FunctionType>(Ty)) {
2272 Result = getPointerType(QualType(Ty, 0));
2273 } else {
2274 Result = QualType(Ty, 0);
2275 }
2276
2277 return CanQualType::CreateUnsafe(Result);
2278}
2279
Chris Lattner77c96472008-04-06 22:41:35 +00002280/// getCanonicalType - Return the canonical (structural) type corresponding to
2281/// the specified potentially non-canonical type. The non-canonical version
2282/// of a type may have many "decorated" versions of types. Decorators can
2283/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2284/// to be free of any of these, allowing two canonical types to be compared
2285/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002286CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002287 QualifierCollector Quals;
2288 const Type *Ptr = Quals.strip(T);
2289 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002290
John McCall0953e762009-09-24 19:53:00 +00002291 // The canonical internal type will be the canonical type *except*
2292 // that we push type qualifiers down through array types.
2293
2294 // If there are no new qualifiers to push down, stop here.
2295 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002296 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002297
John McCall0953e762009-09-24 19:53:00 +00002298 // If the type qualifiers are on an array type, get the canonical
2299 // type of the array with the qualifiers applied to the element
2300 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002301 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2302 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002303 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002305 // Get the canonical version of the element with the extra qualifiers on it.
2306 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002307 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002308 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002310 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002311 return CanQualType::CreateUnsafe(
2312 getConstantArrayType(NewEltTy, CAT->getSize(),
2313 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002314 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002315 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002316 return CanQualType::CreateUnsafe(
2317 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002318 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Douglas Gregor898574e2008-12-05 23:32:09 +00002320 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002321 return CanQualType::CreateUnsafe(
2322 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002323 DSAT->getSizeExpr() ?
2324 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002325 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002326 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002327 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002328
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002329 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002330 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002331 VAT->getSizeExpr() ?
2332 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002333 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002334 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002335 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002336}
2337
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002338TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2339 // If this template name refers to a template, the canonical
2340 // template name merely stores the template itself.
2341 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002342 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002343
Mike Stump1eb44332009-09-09 15:08:12 +00002344 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002345 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002346 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2347 OverloadedFunctionDecl *CanonOvl = 0;
2348 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2349 FEnd = Ovl->function_end();
2350 F != FEnd; ++F) {
2351 Decl *Canon = F->get()->getCanonicalDecl();
2352 if (CanonOvl || Canon != F->get()) {
2353 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002354 CanonOvl = OverloadedFunctionDecl::Create(*this,
2355 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002356 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002358 CanonOvl->addOverload(
2359 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2360 }
2361 }
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002363 return TemplateName(CanonOvl? CanonOvl : Ovl);
2364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002366 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2367 assert(DTN && "Non-dependent template names must refer to template decls.");
2368 return DTN->CanonicalTemplateName;
2369}
2370
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002371bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2372 X = getCanonicalTemplateName(X);
2373 Y = getCanonicalTemplateName(Y);
2374 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2375}
2376
Mike Stump1eb44332009-09-09 15:08:12 +00002377TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002378ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2379 switch (Arg.getKind()) {
2380 case TemplateArgument::Null:
2381 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Douglas Gregor1275ae02009-07-28 23:00:59 +00002383 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002384 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Douglas Gregor1275ae02009-07-28 23:00:59 +00002386 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002387 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Douglas Gregor788cd062009-11-11 01:00:40 +00002389 case TemplateArgument::Template:
2390 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2391
Douglas Gregor1275ae02009-07-28 23:00:59 +00002392 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002393 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002394 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregor1275ae02009-07-28 23:00:59 +00002396 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002397 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Douglas Gregor1275ae02009-07-28 23:00:59 +00002399 case TemplateArgument::Pack: {
2400 // FIXME: Allocate in ASTContext
2401 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2402 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002403 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002404 AEnd = Arg.pack_end();
2405 A != AEnd; (void)++A, ++Idx)
2406 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Douglas Gregor1275ae02009-07-28 23:00:59 +00002408 TemplateArgument Result;
2409 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2410 return Result;
2411 }
2412 }
2413
2414 // Silence GCC warning
2415 assert(false && "Unhandled template argument kind");
2416 return TemplateArgument();
2417}
2418
Douglas Gregord57959a2009-03-27 23:10:48 +00002419NestedNameSpecifier *
2420ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002421 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002422 return 0;
2423
2424 switch (NNS->getKind()) {
2425 case NestedNameSpecifier::Identifier:
2426 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002427 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002428 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2429 NNS->getAsIdentifier());
2430
2431 case NestedNameSpecifier::Namespace:
2432 // A namespace is canonical; build a nested-name-specifier with
2433 // this namespace and no prefix.
2434 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2435
2436 case NestedNameSpecifier::TypeSpec:
2437 case NestedNameSpecifier::TypeSpecWithTemplate: {
2438 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002439 return NestedNameSpecifier::Create(*this, 0,
2440 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002441 T.getTypePtr());
2442 }
2443
2444 case NestedNameSpecifier::Global:
2445 // The global specifier is canonical and unique.
2446 return NNS;
2447 }
2448
2449 // Required to silence a GCC warning
2450 return 0;
2451}
2452
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002453
2454const ArrayType *ASTContext::getAsArrayType(QualType T) {
2455 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002456 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002457 // Handle the common positive case fast.
2458 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2459 return AT;
2460 }
Mike Stump1eb44332009-09-09 15:08:12 +00002461
John McCall0953e762009-09-24 19:53:00 +00002462 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002463 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002464 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002465 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002466
John McCall0953e762009-09-24 19:53:00 +00002467 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002468 // implements C99 6.7.3p8: "If the specification of an array type includes
2469 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002471 // If we get here, we either have type qualifiers on the type, or we have
2472 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002473 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002474
John McCall0953e762009-09-24 19:53:00 +00002475 QualifierCollector Qs;
2476 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002478 // If we have a simple case, just return now.
2479 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002480 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002481 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002483 // Otherwise, we have an array and we have qualifiers on it. Push the
2484 // qualifiers into the array element type and return a new array type.
2485 // Get the canonical version of the element with the extra qualifiers on it.
2486 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002487 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002489 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2490 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2491 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002492 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002493 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2494 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2495 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002496 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002497
Mike Stump1eb44332009-09-09 15:08:12 +00002498 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002499 = dyn_cast<DependentSizedArrayType>(ATy))
2500 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002501 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002502 DSAT->getSizeExpr() ?
2503 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002504 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002505 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002506 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002507
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002508 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002509 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002510 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002511 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002512 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002513 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002514 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002515}
2516
2517
Chris Lattnere6327742008-04-02 05:18:44 +00002518/// getArrayDecayedType - Return the properly qualified result of decaying the
2519/// specified array type to a pointer. This operation is non-trivial when
2520/// handling typedefs etc. The canonical type of "T" must be an array type,
2521/// this returns a pointer to a properly qualified element of the array.
2522///
2523/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2524QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002525 // Get the element type with 'getAsArrayType' so that we don't lose any
2526 // typedefs in the element type of the array. This also handles propagation
2527 // of type qualifiers from the array type into the element type if present
2528 // (C99 6.7.3p8).
2529 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2530 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002532 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002533
2534 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002535 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002536}
2537
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002538QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002539 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002540 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002541 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002542 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2543 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002544 } else {
John McCall0953e762009-09-24 19:53:00 +00002545 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002546 }
2547 }
2548}
2549
Anders Carlssonfbbce492009-09-25 01:23:32 +00002550QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2551 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Anders Carlssonfbbce492009-09-25 01:23:32 +00002553 if (const ArrayType *AT = getAsArrayType(ElemTy))
2554 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Anders Carlsson6183a992008-12-21 03:44:36 +00002556 return ElemTy;
2557}
2558
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002559/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002560uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002561ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2562 uint64_t ElementCount = 1;
2563 do {
2564 ElementCount *= CA->getSize().getZExtValue();
2565 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2566 } while (CA);
2567 return ElementCount;
2568}
2569
Reid Spencer5f016e22007-07-11 17:01:13 +00002570/// getFloatingRank - Return a relative rank for floating point types.
2571/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002572static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002573 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002575
John McCall183700f2009-09-21 23:43:11 +00002576 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2577 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002578 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 case BuiltinType::Float: return FloatRank;
2580 case BuiltinType::Double: return DoubleRank;
2581 case BuiltinType::LongDouble: return LongDoubleRank;
2582 }
2583}
2584
Mike Stump1eb44332009-09-09 15:08:12 +00002585/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2586/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002587/// 'typeDomain' is a real floating point or complex type.
2588/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002589QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2590 QualType Domain) const {
2591 FloatingRank EltRank = getFloatingRank(Size);
2592 if (Domain->isComplexType()) {
2593 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002594 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002595 case FloatRank: return FloatComplexTy;
2596 case DoubleRank: return DoubleComplexTy;
2597 case LongDoubleRank: return LongDoubleComplexTy;
2598 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002599 }
Chris Lattner1361b112008-04-06 23:58:54 +00002600
2601 assert(Domain->isRealFloatingType() && "Unknown domain!");
2602 switch (EltRank) {
2603 default: assert(0 && "getFloatingRank(): illegal value for rank");
2604 case FloatRank: return FloatTy;
2605 case DoubleRank: return DoubleTy;
2606 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002607 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002608}
2609
Chris Lattner7cfeb082008-04-06 23:55:33 +00002610/// getFloatingTypeOrder - Compare the rank of the two specified floating
2611/// point types, ignoring the domain of the type (i.e. 'double' ==
2612/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002613/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002614int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2615 FloatingRank LHSR = getFloatingRank(LHS);
2616 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Chris Lattnera75cea32008-04-06 23:38:49 +00002618 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002619 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002620 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002621 return 1;
2622 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002623}
2624
Chris Lattnerf52ab252008-04-06 22:59:24 +00002625/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2626/// routine will assert if passed a built-in type that isn't an integer or enum,
2627/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002628unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002629 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002630 if (EnumType* ET = dyn_cast<EnumType>(T))
2631 T = ET->getDecl()->getIntegerType().getTypePtr();
2632
Eli Friedmana3426752009-07-05 23:44:27 +00002633 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2634 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2635
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002636 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2637 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2638
2639 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2640 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2641
Eli Friedmanf98aba32009-02-13 02:31:07 +00002642 // There are two things which impact the integer rank: the width, and
2643 // the ordering of builtins. The builtin ordering is encoded in the
2644 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002645 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002646 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002647
Chris Lattnerf52ab252008-04-06 22:59:24 +00002648 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002649 default: assert(0 && "getIntegerRank(): not a built-in integer");
2650 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002651 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002652 case BuiltinType::Char_S:
2653 case BuiltinType::Char_U:
2654 case BuiltinType::SChar:
2655 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002656 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002657 case BuiltinType::Short:
2658 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002659 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002660 case BuiltinType::Int:
2661 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002662 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002663 case BuiltinType::Long:
2664 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002665 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002666 case BuiltinType::LongLong:
2667 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002668 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002669 case BuiltinType::Int128:
2670 case BuiltinType::UInt128:
2671 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002672 }
2673}
2674
Eli Friedman04e83572009-08-20 04:21:42 +00002675/// \brief Whether this is a promotable bitfield reference according
2676/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2677///
2678/// \returns the type this bit-field will promote to, or NULL if no
2679/// promotion occurs.
2680QualType ASTContext::isPromotableBitField(Expr *E) {
2681 FieldDecl *Field = E->getBitField();
2682 if (!Field)
2683 return QualType();
2684
2685 QualType FT = Field->getType();
2686
2687 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2688 uint64_t BitWidth = BitWidthAP.getZExtValue();
2689 uint64_t IntSize = getTypeSize(IntTy);
2690 // GCC extension compatibility: if the bit-field size is less than or equal
2691 // to the size of int, it gets promoted no matter what its type is.
2692 // For instance, unsigned long bf : 4 gets promoted to signed int.
2693 if (BitWidth < IntSize)
2694 return IntTy;
2695
2696 if (BitWidth == IntSize)
2697 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2698
2699 // Types bigger than int are not subject to promotions, and therefore act
2700 // like the base type.
2701 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2702 // is ridiculous.
2703 return QualType();
2704}
2705
Eli Friedmana95d7572009-08-19 07:44:53 +00002706/// getPromotedIntegerType - Returns the type that Promotable will
2707/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2708/// integer type.
2709QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2710 assert(!Promotable.isNull());
2711 assert(Promotable->isPromotableIntegerType());
2712 if (Promotable->isSignedIntegerType())
2713 return IntTy;
2714 uint64_t PromotableSize = getTypeSize(Promotable);
2715 uint64_t IntSize = getTypeSize(IntTy);
2716 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2717 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2718}
2719
Mike Stump1eb44332009-09-09 15:08:12 +00002720/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002721/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002722/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002723int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002724 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2725 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002726 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Chris Lattnerf52ab252008-04-06 22:59:24 +00002728 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2729 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Chris Lattner7cfeb082008-04-06 23:55:33 +00002731 unsigned LHSRank = getIntegerRank(LHSC);
2732 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Chris Lattner7cfeb082008-04-06 23:55:33 +00002734 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2735 if (LHSRank == RHSRank) return 0;
2736 return LHSRank > RHSRank ? 1 : -1;
2737 }
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Chris Lattner7cfeb082008-04-06 23:55:33 +00002739 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2740 if (LHSUnsigned) {
2741 // If the unsigned [LHS] type is larger, return it.
2742 if (LHSRank >= RHSRank)
2743 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Chris Lattner7cfeb082008-04-06 23:55:33 +00002745 // If the signed type can represent all values of the unsigned type, it
2746 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002747 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002748 return -1;
2749 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002750
Chris Lattner7cfeb082008-04-06 23:55:33 +00002751 // If the unsigned [RHS] type is larger, return it.
2752 if (RHSRank >= LHSRank)
2753 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Chris Lattner7cfeb082008-04-06 23:55:33 +00002755 // If the signed type can represent all values of the unsigned type, it
2756 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002757 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002758 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002759}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002760
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002761static RecordDecl *
2762CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2763 SourceLocation L, IdentifierInfo *Id) {
2764 if (Ctx.getLangOptions().CPlusPlus)
2765 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2766 else
2767 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2768}
2769
Mike Stump1eb44332009-09-09 15:08:12 +00002770// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002771QualType ASTContext::getCFConstantStringType() {
2772 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002773 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002774 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2775 &Idents.get("NSConstantString"));
2776
Anders Carlssonf06273f2007-11-19 00:25:30 +00002777 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Anders Carlsson71993dd2007-08-17 05:31:46 +00002779 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002780 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002781 // int flags;
2782 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002783 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002784 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002785 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002786 FieldTypes[3] = LongTy;
2787
Anders Carlsson71993dd2007-08-17 05:31:46 +00002788 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002789 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002790 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002791 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002792 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002793 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002794 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002795 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002796 }
2797
2798 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002799 }
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Anders Carlsson71993dd2007-08-17 05:31:46 +00002801 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002802}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002803
Douglas Gregor319ac892009-04-23 22:29:11 +00002804void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002805 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002806 assert(Rec && "Invalid CFConstantStringType");
2807 CFConstantStringTypeDecl = Rec->getDecl();
2808}
2809
Mike Stump1eb44332009-09-09 15:08:12 +00002810QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002811 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002812 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002813 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2814 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002816 QualType FieldTypes[] = {
2817 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002818 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002819 getPointerType(UnsignedLongTy),
2820 getConstantArrayType(UnsignedLongTy,
2821 llvm::APInt(32, 5), ArrayType::Normal, 0)
2822 };
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Douglas Gregor44b43212008-12-11 16:49:14 +00002824 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002825 FieldDecl *Field = FieldDecl::Create(*this,
2826 ObjCFastEnumerationStateTypeDecl,
2827 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002828 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002829 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002830 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002831 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002832 }
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Douglas Gregor44b43212008-12-11 16:49:14 +00002834 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002835 }
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002837 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2838}
2839
Mike Stumpadaaad32009-10-20 02:12:22 +00002840QualType ASTContext::getBlockDescriptorType() {
2841 if (BlockDescriptorType)
2842 return getTagDeclType(BlockDescriptorType);
2843
2844 RecordDecl *T;
2845 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002846 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2847 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002848
2849 QualType FieldTypes[] = {
2850 UnsignedLongTy,
2851 UnsignedLongTy,
2852 };
2853
2854 const char *FieldNames[] = {
2855 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002856 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002857 };
2858
2859 for (size_t i = 0; i < 2; ++i) {
2860 FieldDecl *Field = FieldDecl::Create(*this,
2861 T,
2862 SourceLocation(),
2863 &Idents.get(FieldNames[i]),
2864 FieldTypes[i], /*DInfo=*/0,
2865 /*BitWidth=*/0,
2866 /*Mutable=*/false);
2867 T->addDecl(Field);
2868 }
2869
2870 T->completeDefinition(*this);
2871
2872 BlockDescriptorType = T;
2873
2874 return getTagDeclType(BlockDescriptorType);
2875}
2876
2877void ASTContext::setBlockDescriptorType(QualType T) {
2878 const RecordType *Rec = T->getAs<RecordType>();
2879 assert(Rec && "Invalid BlockDescriptorType");
2880 BlockDescriptorType = Rec->getDecl();
2881}
2882
Mike Stump083c25e2009-10-22 00:49:09 +00002883QualType ASTContext::getBlockDescriptorExtendedType() {
2884 if (BlockDescriptorExtendedType)
2885 return getTagDeclType(BlockDescriptorExtendedType);
2886
2887 RecordDecl *T;
2888 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002889 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2890 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002891
2892 QualType FieldTypes[] = {
2893 UnsignedLongTy,
2894 UnsignedLongTy,
2895 getPointerType(VoidPtrTy),
2896 getPointerType(VoidPtrTy)
2897 };
2898
2899 const char *FieldNames[] = {
2900 "reserved",
2901 "Size",
2902 "CopyFuncPtr",
2903 "DestroyFuncPtr"
2904 };
2905
2906 for (size_t i = 0; i < 4; ++i) {
2907 FieldDecl *Field = FieldDecl::Create(*this,
2908 T,
2909 SourceLocation(),
2910 &Idents.get(FieldNames[i]),
2911 FieldTypes[i], /*DInfo=*/0,
2912 /*BitWidth=*/0,
2913 /*Mutable=*/false);
2914 T->addDecl(Field);
2915 }
2916
2917 T->completeDefinition(*this);
2918
2919 BlockDescriptorExtendedType = T;
2920
2921 return getTagDeclType(BlockDescriptorExtendedType);
2922}
2923
2924void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2925 const RecordType *Rec = T->getAs<RecordType>();
2926 assert(Rec && "Invalid BlockDescriptorType");
2927 BlockDescriptorExtendedType = Rec->getDecl();
2928}
2929
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002930bool ASTContext::BlockRequiresCopying(QualType Ty) {
2931 if (Ty->isBlockPointerType())
2932 return true;
2933 if (isObjCNSObjectType(Ty))
2934 return true;
2935 if (Ty->isObjCObjectPointerType())
2936 return true;
2937 return false;
2938}
2939
2940QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2941 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002942 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002943 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002944 // unsigned int __flags;
2945 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002946 // void *__copy_helper; // as needed
2947 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002948 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002949 // } *
2950
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002951 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2952
2953 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002954 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002955 llvm::SmallString<36> Name;
2956 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2957 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002958 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002959 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2960 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002961 T->startDefinition();
2962 QualType Int32Ty = IntTy;
2963 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2964 QualType FieldTypes[] = {
2965 getPointerType(VoidPtrTy),
2966 getPointerType(getTagDeclType(T)),
2967 Int32Ty,
2968 Int32Ty,
2969 getPointerType(VoidPtrTy),
2970 getPointerType(VoidPtrTy),
2971 Ty
2972 };
2973
2974 const char *FieldNames[] = {
2975 "__isa",
2976 "__forwarding",
2977 "__flags",
2978 "__size",
2979 "__copy_helper",
2980 "__destroy_helper",
2981 DeclName,
2982 };
2983
2984 for (size_t i = 0; i < 7; ++i) {
2985 if (!HasCopyAndDispose && i >=4 && i <= 5)
2986 continue;
2987 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2988 &Idents.get(FieldNames[i]),
2989 FieldTypes[i], /*DInfo=*/0,
2990 /*BitWidth=*/0, /*Mutable=*/false);
2991 T->addDecl(Field);
2992 }
2993
2994 T->completeDefinition(*this);
2995
2996 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002997}
2998
2999
3000QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003001 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003002 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003003 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003004 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003005 llvm::SmallString<36> Name;
3006 llvm::raw_svector_ostream(Name) << "__block_literal_"
3007 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003008 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003009 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3010 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003011 QualType FieldTypes[] = {
3012 getPointerType(VoidPtrTy),
3013 IntTy,
3014 IntTy,
3015 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003016 (BlockHasCopyDispose ?
3017 getPointerType(getBlockDescriptorExtendedType()) :
3018 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003019 };
3020
3021 const char *FieldNames[] = {
3022 "__isa",
3023 "__flags",
3024 "__reserved",
3025 "__FuncPtr",
3026 "__descriptor"
3027 };
3028
3029 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003030 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003031 &Idents.get(FieldNames[i]),
3032 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003033 /*BitWidth=*/0, /*Mutable=*/false);
3034 T->addDecl(Field);
3035 }
3036
3037 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3038 const Expr *E = BlockDeclRefDecls[i];
3039 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3040 clang::IdentifierInfo *Name = 0;
3041 if (BDRE) {
3042 const ValueDecl *D = BDRE->getDecl();
3043 Name = &Idents.get(D->getName());
3044 }
3045 QualType FieldType = E->getType();
3046
3047 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003048 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3049 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003050
3051 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3052 Name, FieldType, /*DInfo=*/0,
3053 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003054 T->addDecl(Field);
3055 }
3056
3057 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003058
3059 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003060}
3061
Douglas Gregor319ac892009-04-23 22:29:11 +00003062void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003063 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003064 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3065 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3066}
3067
Anders Carlssone8c49532007-10-29 06:33:42 +00003068// This returns true if a type has been typedefed to BOOL:
3069// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003070static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003071 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003072 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3073 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003075 return false;
3076}
3077
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003078/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003079/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003080int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003081 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003083 // Make all integer and enum types at least as large as an int
3084 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003085 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003086 // Treat arrays as pointers, since that's how they're passed in.
3087 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003088 sz = getTypeSize(VoidPtrTy);
3089 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003090}
3091
David Chisnall5e530af2009-11-17 19:33:30 +00003092/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3093/// declaration.
3094void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3095 std::string& S) {
3096 const BlockDecl *Decl = Expr->getBlockDecl();
3097 QualType BlockTy =
3098 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3099 // Encode result type.
3100 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3101 // Compute size of all parameters.
3102 // Start with computing size of a pointer in number of bytes.
3103 // FIXME: There might(should) be a better way of doing this computation!
3104 SourceLocation Loc;
3105 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3106 int ParmOffset = PtrSize;
3107 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3108 E = Decl->param_end(); PI != E; ++PI) {
3109 QualType PType = (*PI)->getType();
3110 int sz = getObjCEncodingTypeSize(PType);
3111 assert (sz > 0 && "BlockExpr - Incomplete param type");
3112 ParmOffset += sz;
3113 }
3114 // Size of the argument frame
3115 S += llvm::utostr(ParmOffset);
3116 // Block pointer and offset.
3117 S += "@?0";
3118 ParmOffset = PtrSize;
3119
3120 // Argument types.
3121 ParmOffset = PtrSize;
3122 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3123 Decl->param_end(); PI != E; ++PI) {
3124 ParmVarDecl *PVDecl = *PI;
3125 QualType PType = PVDecl->getOriginalType();
3126 if (const ArrayType *AT =
3127 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3128 // Use array's original type only if it has known number of
3129 // elements.
3130 if (!isa<ConstantArrayType>(AT))
3131 PType = PVDecl->getType();
3132 } else if (PType->isFunctionType())
3133 PType = PVDecl->getType();
3134 getObjCEncodingForType(PType, S);
3135 S += llvm::utostr(ParmOffset);
3136 ParmOffset += getObjCEncodingTypeSize(PType);
3137 }
3138}
3139
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003140/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003141/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003142void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003143 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003144 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003145 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003146 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003147 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003148 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003149 // Compute size of all parameters.
3150 // Start with computing size of a pointer in number of bytes.
3151 // FIXME: There might(should) be a better way of doing this computation!
3152 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003153 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003154 // The first two arguments (self and _cmd) are pointers; account for
3155 // their size.
3156 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003157 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3158 E = Decl->param_end(); PI != E; ++PI) {
3159 QualType PType = (*PI)->getType();
3160 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003161 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003162 ParmOffset += sz;
3163 }
3164 S += llvm::utostr(ParmOffset);
3165 S += "@0:";
3166 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003168 // Argument types.
3169 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003170 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3171 E = Decl->param_end(); PI != E; ++PI) {
3172 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003173 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003174 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003175 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3176 // Use array's original type only if it has known number of
3177 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003178 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003179 PType = PVDecl->getType();
3180 } else if (PType->isFunctionType())
3181 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003182 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003183 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003184 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003185 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003186 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003187 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003188 }
3189}
3190
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003191/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003192/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003193/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3194/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003195/// Property attributes are stored as a comma-delimited C string. The simple
3196/// attributes readonly and bycopy are encoded as single characters. The
3197/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3198/// encoded as single characters, followed by an identifier. Property types
3199/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003200/// these attributes are defined by the following enumeration:
3201/// @code
3202/// enum PropertyAttributes {
3203/// kPropertyReadOnly = 'R', // property is read-only.
3204/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3205/// kPropertyByref = '&', // property is a reference to the value last assigned
3206/// kPropertyDynamic = 'D', // property is dynamic
3207/// kPropertyGetter = 'G', // followed by getter selector name
3208/// kPropertySetter = 'S', // followed by setter selector name
3209/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3210/// kPropertyType = 't' // followed by old-style type encoding.
3211/// kPropertyWeak = 'W' // 'weak' property
3212/// kPropertyStrong = 'P' // property GC'able
3213/// kPropertyNonAtomic = 'N' // property non-atomic
3214/// };
3215/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003216void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003217 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003218 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003219 // Collect information from the property implementation decl(s).
3220 bool Dynamic = false;
3221 ObjCPropertyImplDecl *SynthesizePID = 0;
3222
3223 // FIXME: Duplicated code due to poor abstraction.
3224 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003225 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003226 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3227 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003228 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003229 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003230 ObjCPropertyImplDecl *PID = *i;
3231 if (PID->getPropertyDecl() == PD) {
3232 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3233 Dynamic = true;
3234 } else {
3235 SynthesizePID = PID;
3236 }
3237 }
3238 }
3239 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003240 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003241 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003242 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003243 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003244 ObjCPropertyImplDecl *PID = *i;
3245 if (PID->getPropertyDecl() == PD) {
3246 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3247 Dynamic = true;
3248 } else {
3249 SynthesizePID = PID;
3250 }
3251 }
Mike Stump1eb44332009-09-09 15:08:12 +00003252 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003253 }
3254 }
3255
3256 // FIXME: This is not very efficient.
3257 S = "T";
3258
3259 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003260 // GCC has some special rules regarding encoding of properties which
3261 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003262 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003263 true /* outermost type */,
3264 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003265
3266 if (PD->isReadOnly()) {
3267 S += ",R";
3268 } else {
3269 switch (PD->getSetterKind()) {
3270 case ObjCPropertyDecl::Assign: break;
3271 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003272 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003273 }
3274 }
3275
3276 // It really isn't clear at all what this means, since properties
3277 // are "dynamic by default".
3278 if (Dynamic)
3279 S += ",D";
3280
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003281 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3282 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003284 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3285 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003286 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003287 }
3288
3289 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3290 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003291 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003292 }
3293
3294 if (SynthesizePID) {
3295 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3296 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003297 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003298 }
3299
3300 // FIXME: OBJCGC: weak & strong
3301}
3302
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003303/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003304/// Another legacy compatibility encoding: 32-bit longs are encoded as
3305/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003306/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3307///
3308void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003309 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003310 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003311 if (BT->getKind() == BuiltinType::ULong &&
3312 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003313 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003314 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003315 if (BT->getKind() == BuiltinType::Long &&
3316 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003317 PointeeTy = IntTy;
3318 }
3319 }
3320}
3321
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003322void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003323 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003324 // We follow the behavior of gcc, expanding structures which are
3325 // directly pointed to, and expanding embedded structures. Note that
3326 // these rules are sufficient to prevent recursive encoding of the
3327 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003328 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003329 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003330}
3331
Mike Stump1eb44332009-09-09 15:08:12 +00003332static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003333 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003334 const Expr *E = FD->getBitWidth();
3335 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3336 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003337 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003338 S += 'b';
3339 S += llvm::utostr(N);
3340}
3341
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003342// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003343void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3344 bool ExpandPointedToStructures,
3345 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003346 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003347 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003348 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003349 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003350 if (FD && FD->isBitField())
3351 return EncodeBitField(this, S, FD);
3352 char encoding;
3353 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003354 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003355 case BuiltinType::Void: encoding = 'v'; break;
3356 case BuiltinType::Bool: encoding = 'B'; break;
3357 case BuiltinType::Char_U:
3358 case BuiltinType::UChar: encoding = 'C'; break;
3359 case BuiltinType::UShort: encoding = 'S'; break;
3360 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003361 case BuiltinType::ULong:
3362 encoding =
3363 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003364 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003365 case BuiltinType::UInt128: encoding = 'T'; break;
3366 case BuiltinType::ULongLong: encoding = 'Q'; break;
3367 case BuiltinType::Char_S:
3368 case BuiltinType::SChar: encoding = 'c'; break;
3369 case BuiltinType::Short: encoding = 's'; break;
3370 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003371 case BuiltinType::Long:
3372 encoding =
3373 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003374 break;
3375 case BuiltinType::LongLong: encoding = 'q'; break;
3376 case BuiltinType::Int128: encoding = 't'; break;
3377 case BuiltinType::Float: encoding = 'f'; break;
3378 case BuiltinType::Double: encoding = 'd'; break;
3379 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003380 }
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003382 S += encoding;
3383 return;
3384 }
Mike Stump1eb44332009-09-09 15:08:12 +00003385
John McCall183700f2009-09-21 23:43:11 +00003386 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003387 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003388 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003389 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003390 return;
3391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Ted Kremenek6217b802009-07-29 21:53:49 +00003393 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003394 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003395 bool isReadOnly = false;
3396 // For historical/compatibility reasons, the read-only qualifier of the
3397 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3398 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003399 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003400 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003401 if (OutermostType && T.isConstQualified()) {
3402 isReadOnly = true;
3403 S += 'r';
3404 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003405 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003406 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003407 while (P->getAs<PointerType>())
3408 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003409 if (P.isConstQualified()) {
3410 isReadOnly = true;
3411 S += 'r';
3412 }
3413 }
3414 if (isReadOnly) {
3415 // Another legacy compatibility encoding. Some ObjC qualifier and type
3416 // combinations need to be rearranged.
3417 // Rewrite "in const" from "nr" to "rn"
3418 const char * s = S.c_str();
3419 int len = S.length();
3420 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3421 std::string replace = "rn";
3422 S.replace(S.end()-2, S.end(), replace);
3423 }
3424 }
Steve Naroff14108da2009-07-10 23:34:53 +00003425 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003426 S += ':';
3427 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003428 }
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003430 if (PointeeTy->isCharType()) {
3431 // char pointer types should be encoded as '*' unless it is a
3432 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003433 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003434 S += '*';
3435 return;
3436 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003437 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003438 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3439 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3440 S += '#';
3441 return;
3442 }
3443 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3444 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3445 S += '@';
3446 return;
3447 }
3448 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003449 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003450 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003451 getLegacyIntegralTypeEncoding(PointeeTy);
3452
Mike Stump1eb44332009-09-09 15:08:12 +00003453 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003454 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003455 return;
3456 }
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003458 if (const ArrayType *AT =
3459 // Ignore type qualifiers etc.
3460 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003461 if (isa<IncompleteArrayType>(AT)) {
3462 // Incomplete arrays are encoded as a pointer to the array element.
3463 S += '^';
3464
Mike Stump1eb44332009-09-09 15:08:12 +00003465 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003466 false, ExpandStructures, FD);
3467 } else {
3468 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Anders Carlsson559a8332009-02-22 01:38:57 +00003470 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3471 S += llvm::utostr(CAT->getSize().getZExtValue());
3472 else {
3473 //Variable length arrays are encoded as a regular array with 0 elements.
3474 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3475 S += '0';
3476 }
Mike Stump1eb44332009-09-09 15:08:12 +00003477
3478 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003479 false, ExpandStructures, FD);
3480 S += ']';
3481 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003482 return;
3483 }
Mike Stump1eb44332009-09-09 15:08:12 +00003484
John McCall183700f2009-09-21 23:43:11 +00003485 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003486 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003487 return;
3488 }
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Ted Kremenek6217b802009-07-29 21:53:49 +00003490 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003491 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003492 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003493 // Anonymous structures print as '?'
3494 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3495 S += II->getName();
3496 } else {
3497 S += '?';
3498 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003499 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003500 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003501 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3502 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003503 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003504 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003505 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003506 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003507 S += '"';
3508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003510 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003511 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003512 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003513 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003514 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003515 QualType qt = Field->getType();
3516 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003517 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003518 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003519 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003520 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003521 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003522 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003523 return;
3524 }
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003526 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003527 if (FD && FD->isBitField())
3528 EncodeBitField(this, S, FD);
3529 else
3530 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003531 return;
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003534 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003535 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 return;
3537 }
Mike Stump1eb44332009-09-09 15:08:12 +00003538
John McCall0953e762009-09-24 19:53:00 +00003539 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003540 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003541 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003542 S += '{';
3543 const IdentifierInfo *II = OI->getIdentifier();
3544 S += II->getName();
3545 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003546 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003547 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003548 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003549 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003550 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003551 RecFields[i]);
3552 else
Mike Stump1eb44332009-09-09 15:08:12 +00003553 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003554 FD);
3555 }
3556 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003557 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003558 }
Mike Stump1eb44332009-09-09 15:08:12 +00003559
John McCall183700f2009-09-21 23:43:11 +00003560 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003561 if (OPT->isObjCIdType()) {
3562 S += '@';
3563 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003564 }
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Steve Naroff27d20a22009-10-28 22:03:49 +00003566 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3567 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3568 // Since this is a binary compatibility issue, need to consult with runtime
3569 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003570 S += '#';
3571 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003572 }
Mike Stump1eb44332009-09-09 15:08:12 +00003573
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003574 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003575 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003576 ExpandPointedToStructures,
3577 ExpandStructures, FD);
3578 if (FD || EncodingProperty) {
3579 // Note that we do extended encoding of protocol qualifer list
3580 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003581 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003582 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3583 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003584 S += '<';
3585 S += (*I)->getNameAsString();
3586 S += '>';
3587 }
3588 S += '"';
3589 }
3590 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003591 }
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003593 QualType PointeeTy = OPT->getPointeeType();
3594 if (!EncodingProperty &&
3595 isa<TypedefType>(PointeeTy.getTypePtr())) {
3596 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003597 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 // {...};
3599 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003600 getObjCEncodingForTypeImpl(PointeeTy, S,
3601 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003602 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003603 return;
3604 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003605
3606 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003607 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003608 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003609 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003610 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3611 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003612 S += '<';
3613 S += (*I)->getNameAsString();
3614 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003615 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003616 S += '"';
3617 }
3618 return;
3619 }
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003621 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003622}
3623
Mike Stump1eb44332009-09-09 15:08:12 +00003624void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003625 std::string& S) const {
3626 if (QT & Decl::OBJC_TQ_In)
3627 S += 'n';
3628 if (QT & Decl::OBJC_TQ_Inout)
3629 S += 'N';
3630 if (QT & Decl::OBJC_TQ_Out)
3631 S += 'o';
3632 if (QT & Decl::OBJC_TQ_Bycopy)
3633 S += 'O';
3634 if (QT & Decl::OBJC_TQ_Byref)
3635 S += 'R';
3636 if (QT & Decl::OBJC_TQ_Oneway)
3637 S += 'V';
3638}
3639
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003640void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003641 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003643 BuiltinVaListType = T;
3644}
3645
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003646void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003647 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003648}
3649
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003650void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003651 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003652}
3653
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003654void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003655 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003656}
3657
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003658void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003659 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003660}
3661
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003662void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003663 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003664 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003666 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003667}
3668
Douglas Gregor7532dc62009-03-30 22:58:21 +00003669/// \brief Retrieve the template name that represents a qualified
3670/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003671TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003672 bool TemplateKeyword,
3673 TemplateDecl *Template) {
3674 llvm::FoldingSetNodeID ID;
3675 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3676
3677 void *InsertPos = 0;
3678 QualifiedTemplateName *QTN =
3679 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3680 if (!QTN) {
3681 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3682 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3683 }
3684
3685 return TemplateName(QTN);
3686}
3687
Douglas Gregord99cbe62009-07-29 18:26:50 +00003688/// \brief Retrieve the template name that represents a qualified
3689/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003690TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003691 bool TemplateKeyword,
3692 OverloadedFunctionDecl *Template) {
3693 llvm::FoldingSetNodeID ID;
3694 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Douglas Gregord99cbe62009-07-29 18:26:50 +00003696 void *InsertPos = 0;
3697 QualifiedTemplateName *QTN =
3698 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3699 if (!QTN) {
3700 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3701 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3702 }
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Douglas Gregord99cbe62009-07-29 18:26:50 +00003704 return TemplateName(QTN);
3705}
3706
Douglas Gregor7532dc62009-03-30 22:58:21 +00003707/// \brief Retrieve the template name that represents a dependent
3708/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003709TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003710 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003711 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003712 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003713
3714 llvm::FoldingSetNodeID ID;
3715 DependentTemplateName::Profile(ID, NNS, Name);
3716
3717 void *InsertPos = 0;
3718 DependentTemplateName *QTN =
3719 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3720
3721 if (QTN)
3722 return TemplateName(QTN);
3723
3724 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3725 if (CanonNNS == NNS) {
3726 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3727 } else {
3728 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3729 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3730 }
3731
3732 DependentTemplateNames.InsertNode(QTN, InsertPos);
3733 return TemplateName(QTN);
3734}
3735
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003736/// \brief Retrieve the template name that represents a dependent
3737/// template name such as \c MetaFun::template operator+.
3738TemplateName
3739ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3740 OverloadedOperatorKind Operator) {
3741 assert((!NNS || NNS->isDependent()) &&
3742 "Nested name specifier must be dependent");
3743
3744 llvm::FoldingSetNodeID ID;
3745 DependentTemplateName::Profile(ID, NNS, Operator);
3746
3747 void *InsertPos = 0;
3748 DependentTemplateName *QTN =
3749 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3750
3751 if (QTN)
3752 return TemplateName(QTN);
3753
3754 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3755 if (CanonNNS == NNS) {
3756 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3757 } else {
3758 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3759 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3760 }
3761
3762 DependentTemplateNames.InsertNode(QTN, InsertPos);
3763 return TemplateName(QTN);
3764}
3765
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003766/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003767/// TargetInfo, produce the corresponding type. The unsigned @p Type
3768/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003769CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003770 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003771 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003772 case TargetInfo::SignedShort: return ShortTy;
3773 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3774 case TargetInfo::SignedInt: return IntTy;
3775 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3776 case TargetInfo::SignedLong: return LongTy;
3777 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3778 case TargetInfo::SignedLongLong: return LongLongTy;
3779 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3780 }
3781
3782 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003783 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003784}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003785
3786//===----------------------------------------------------------------------===//
3787// Type Predicates.
3788//===----------------------------------------------------------------------===//
3789
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003790/// isObjCNSObjectType - Return true if this is an NSObject object using
3791/// NSObject attribute on a c-style pointer type.
3792/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003793/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003794///
3795bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3796 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3797 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003798 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003799 return true;
3800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003802}
3803
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003804/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3805/// garbage collection attribute.
3806///
John McCall0953e762009-09-24 19:53:00 +00003807Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3808 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003809 if (getLangOptions().ObjC1 &&
3810 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003811 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003812 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003813 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003814 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003815 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003816 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003817 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003818 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003819 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003820 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003821 // Non-pointers have none gc'able attribute regardless of the attribute
3822 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003823 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003824 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003825 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003826 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003827}
3828
Chris Lattner6ac46a42008-04-07 06:51:04 +00003829//===----------------------------------------------------------------------===//
3830// Type Compatibility Testing
3831//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003832
Mike Stump1eb44332009-09-09 15:08:12 +00003833/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003834/// compatible.
3835static bool areCompatVectorTypes(const VectorType *LHS,
3836 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003837 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003838 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003839 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003840}
3841
Steve Naroff4084c302009-07-23 01:01:38 +00003842//===----------------------------------------------------------------------===//
3843// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3844//===----------------------------------------------------------------------===//
3845
3846/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3847/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003848bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3849 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003850 if (lProto == rProto)
3851 return true;
3852 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3853 E = rProto->protocol_end(); PI != E; ++PI)
3854 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3855 return true;
3856 return false;
3857}
3858
Steve Naroff4084c302009-07-23 01:01:38 +00003859/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3860/// return true if lhs's protocols conform to rhs's protocol; false
3861/// otherwise.
3862bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3863 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3864 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3865 return false;
3866}
3867
3868/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3869/// ObjCQualifiedIDType.
3870bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3871 bool compare) {
3872 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003873 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003874 lhs->isObjCIdType() || lhs->isObjCClassType())
3875 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003876 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003877 rhs->isObjCIdType() || rhs->isObjCClassType())
3878 return true;
3879
3880 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003881 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Steve Naroff4084c302009-07-23 01:01:38 +00003883 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Steve Naroff4084c302009-07-23 01:01:38 +00003885 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003886 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003887 // make sure we check the class hierarchy.
3888 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3889 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3890 E = lhsQID->qual_end(); I != E; ++I) {
3891 // when comparing an id<P> on lhs with a static type on rhs,
3892 // see if static class implements all of id's protocols, directly or
3893 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003894 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003895 return false;
3896 }
3897 }
3898 // If there are no qualifiers and no interface, we have an 'id'.
3899 return true;
3900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003902 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3903 E = lhsQID->qual_end(); I != E; ++I) {
3904 ObjCProtocolDecl *lhsProto = *I;
3905 bool match = false;
3906
3907 // when comparing an id<P> on lhs with a static type on rhs,
3908 // see if static class implements all of id's protocols, directly or
3909 // through its super class and categories.
3910 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3911 E = rhsOPT->qual_end(); J != E; ++J) {
3912 ObjCProtocolDecl *rhsProto = *J;
3913 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3914 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3915 match = true;
3916 break;
3917 }
3918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003920 // make sure we check the class hierarchy.
3921 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3922 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3923 E = lhsQID->qual_end(); I != E; ++I) {
3924 // when comparing an id<P> on lhs with a static type on rhs,
3925 // see if static class implements all of id's protocols, directly or
3926 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003927 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003928 match = true;
3929 break;
3930 }
3931 }
3932 }
3933 if (!match)
3934 return false;
3935 }
Mike Stump1eb44332009-09-09 15:08:12 +00003936
Steve Naroff4084c302009-07-23 01:01:38 +00003937 return true;
3938 }
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Steve Naroff4084c302009-07-23 01:01:38 +00003940 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3941 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3942
Mike Stump1eb44332009-09-09 15:08:12 +00003943 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003944 lhs->getAsObjCInterfacePointerType()) {
3945 if (lhsOPT->qual_empty()) {
3946 bool match = false;
3947 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3948 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3949 E = rhsQID->qual_end(); I != E; ++I) {
3950 // when comparing an id<P> on lhs with a static type on rhs,
3951 // see if static class implements all of id's protocols, directly or
3952 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003953 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003954 match = true;
3955 break;
3956 }
3957 }
3958 if (!match)
3959 return false;
3960 }
3961 return true;
3962 }
Mike Stump1eb44332009-09-09 15:08:12 +00003963 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003964 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3965 E = lhsOPT->qual_end(); I != E; ++I) {
3966 ObjCProtocolDecl *lhsProto = *I;
3967 bool match = false;
3968
3969 // when comparing an id<P> on lhs with a static type on rhs,
3970 // see if static class implements all of id's protocols, directly or
3971 // through its super class and categories.
3972 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3973 E = rhsQID->qual_end(); J != E; ++J) {
3974 ObjCProtocolDecl *rhsProto = *J;
3975 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3976 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3977 match = true;
3978 break;
3979 }
3980 }
3981 if (!match)
3982 return false;
3983 }
3984 return true;
3985 }
3986 return false;
3987}
3988
Eli Friedman3d815e72008-08-22 00:56:42 +00003989/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003990/// compatible for assignment from RHS to LHS. This handles validation of any
3991/// protocol qualifiers on the LHS or RHS.
3992///
Steve Naroff14108da2009-07-10 23:34:53 +00003993bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3994 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003995 // If either type represents the built-in 'id' or 'Class' types, return true.
3996 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003997 return true;
3998
Steve Naroff4084c302009-07-23 01:01:38 +00003999 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004000 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4001 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004002 false);
4003
Steve Naroff14108da2009-07-10 23:34:53 +00004004 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4005 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004006 if (LHS && RHS) // We have 2 user-defined types.
4007 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Steve Naroff4084c302009-07-23 01:01:38 +00004009 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004010}
4011
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004012/// getIntersectionOfProtocols - This routine finds the intersection of set
4013/// of protocols inherited from two distinct objective-c pointer objects.
4014/// It is used to build composite qualifier list of the composite type of
4015/// the conditional expression involving two objective-c pointer objects.
4016static
4017void getIntersectionOfProtocols(ASTContext &Context,
4018 const ObjCObjectPointerType *LHSOPT,
4019 const ObjCObjectPointerType *RHSOPT,
4020 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4021
4022 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4023 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4024
4025 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4026 unsigned LHSNumProtocols = LHS->getNumProtocols();
4027 if (LHSNumProtocols > 0)
4028 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4029 else {
4030 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4031 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4032 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4033 LHSInheritedProtocols.end());
4034 }
4035
4036 unsigned RHSNumProtocols = RHS->getNumProtocols();
4037 if (RHSNumProtocols > 0) {
4038 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4039 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4040 if (InheritedProtocolSet.count(RHSProtocols[i]))
4041 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4042 }
4043 else {
4044 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4045 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4046 // FIXME. This may cause duplication of protocols in the list, but should
4047 // be harmless.
4048 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4049 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4050 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4051 }
4052}
4053
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004054/// areCommonBaseCompatible - Returns common base class of the two classes if
4055/// one found. Note that this is O'2 algorithm. But it will be called as the
4056/// last type comparison in a ?-exp of ObjC pointer types before a
4057/// warning is issued. So, its invokation is extremely rare.
4058QualType ASTContext::areCommonBaseCompatible(
4059 const ObjCObjectPointerType *LHSOPT,
4060 const ObjCObjectPointerType *RHSOPT) {
4061 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4062 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4063 if (!LHS || !RHS)
4064 return QualType();
4065
4066 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4067 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4068 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004069 if (canAssignObjCInterfaces(LHS, RHS)) {
4070 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4071 getIntersectionOfProtocols(*this,
4072 LHSOPT, RHSOPT, IntersectionOfProtocols);
4073 if (IntersectionOfProtocols.empty())
4074 LHSTy = getObjCObjectPointerType(LHSTy);
4075 else
4076 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4077 IntersectionOfProtocols.size());
4078 return LHSTy;
4079 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004080 }
4081
4082 return QualType();
4083}
4084
Eli Friedman3d815e72008-08-22 00:56:42 +00004085bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4086 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004087 // Verify that the base decls are compatible: the RHS must be a subclass of
4088 // the LHS.
4089 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4090 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Chris Lattner6ac46a42008-04-07 06:51:04 +00004092 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4093 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004094 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004095 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Chris Lattner6ac46a42008-04-07 06:51:04 +00004097 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4098 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004099 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004100 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004101
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004102 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4103 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004104 LHSPI != LHSPE; LHSPI++) {
4105 bool RHSImplementsProtocol = false;
4106
4107 // If the RHS doesn't implement the protocol on the left, the types
4108 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004109 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004110 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004111 RHSPI != RHSPE; RHSPI++) {
4112 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004113 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004114 break;
4115 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004116 }
4117 // FIXME: For better diagnostics, consider passing back the protocol name.
4118 if (!RHSImplementsProtocol)
4119 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004120 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004121 // The RHS implements all protocols listed on the LHS.
4122 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004123}
4124
Steve Naroff389bf462009-02-12 17:52:19 +00004125bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4126 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004127 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4128 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Steve Naroff14108da2009-07-10 23:34:53 +00004130 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004131 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004132
4133 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4134 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004135}
4136
Mike Stump1eb44332009-09-09 15:08:12 +00004137/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004138/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004139/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004140/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004141bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4142 return !mergeTypes(LHS, RHS).isNull();
4143}
4144
4145QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004146 const FunctionType *lbase = lhs->getAs<FunctionType>();
4147 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004148 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4149 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004150 bool allLTypes = true;
4151 bool allRTypes = true;
4152
4153 // Check return type
4154 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4155 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004156 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4157 allLTypes = false;
4158 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4159 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004160 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004161 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4162 if (NoReturn != lbase->getNoReturnAttr())
4163 allLTypes = false;
4164 if (NoReturn != rbase->getNoReturnAttr())
4165 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Eli Friedman3d815e72008-08-22 00:56:42 +00004167 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004168 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4169 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004170 unsigned lproto_nargs = lproto->getNumArgs();
4171 unsigned rproto_nargs = rproto->getNumArgs();
4172
4173 // Compatible functions must have the same number of arguments
4174 if (lproto_nargs != rproto_nargs)
4175 return QualType();
4176
4177 // Variadic and non-variadic functions aren't compatible
4178 if (lproto->isVariadic() != rproto->isVariadic())
4179 return QualType();
4180
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004181 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4182 return QualType();
4183
Eli Friedman3d815e72008-08-22 00:56:42 +00004184 // Check argument compatibility
4185 llvm::SmallVector<QualType, 10> types;
4186 for (unsigned i = 0; i < lproto_nargs; i++) {
4187 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4188 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4189 QualType argtype = mergeTypes(largtype, rargtype);
4190 if (argtype.isNull()) return QualType();
4191 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004192 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4193 allLTypes = false;
4194 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4195 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004196 }
4197 if (allLTypes) return lhs;
4198 if (allRTypes) return rhs;
4199 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004200 lproto->isVariadic(), lproto->getTypeQuals(),
4201 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004202 }
4203
4204 if (lproto) allRTypes = false;
4205 if (rproto) allLTypes = false;
4206
Douglas Gregor72564e72009-02-26 23:50:07 +00004207 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004208 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004209 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004210 if (proto->isVariadic()) return QualType();
4211 // Check that the types are compatible with the types that
4212 // would result from default argument promotions (C99 6.7.5.3p15).
4213 // The only types actually affected are promotable integer
4214 // types and floats, which would be passed as a different
4215 // type depending on whether the prototype is visible.
4216 unsigned proto_nargs = proto->getNumArgs();
4217 for (unsigned i = 0; i < proto_nargs; ++i) {
4218 QualType argTy = proto->getArgType(i);
4219 if (argTy->isPromotableIntegerType() ||
4220 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4221 return QualType();
4222 }
4223
4224 if (allLTypes) return lhs;
4225 if (allRTypes) return rhs;
4226 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004227 proto->getNumArgs(), proto->isVariadic(),
4228 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004229 }
4230
4231 if (allLTypes) return lhs;
4232 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004233 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004234}
4235
4236QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004237 // C++ [expr]: If an expression initially has the type "reference to T", the
4238 // type is adjusted to "T" prior to any further analysis, the expression
4239 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004240 // expression is an lvalue unless the reference is an rvalue reference and
4241 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004242 // FIXME: C++ shouldn't be going through here! The rules are different
4243 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004244 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4245 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004246 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004247 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004248 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004249 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004250
Eli Friedman3d815e72008-08-22 00:56:42 +00004251 QualType LHSCan = getCanonicalType(LHS),
4252 RHSCan = getCanonicalType(RHS);
4253
4254 // If two types are identical, they are compatible.
4255 if (LHSCan == RHSCan)
4256 return LHS;
4257
John McCall0953e762009-09-24 19:53:00 +00004258 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004259 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4260 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004261 if (LQuals != RQuals) {
4262 // If any of these qualifiers are different, we have a type
4263 // mismatch.
4264 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4265 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4266 return QualType();
4267
4268 // Exactly one GC qualifier difference is allowed: __strong is
4269 // okay if the other type has no GC qualifier but is an Objective
4270 // C object pointer (i.e. implicitly strong by default). We fix
4271 // this by pretending that the unqualified type was actually
4272 // qualified __strong.
4273 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4274 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4275 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4276
4277 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4278 return QualType();
4279
4280 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4281 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4282 }
4283 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4284 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4285 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004286 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004287 }
4288
4289 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004290
Eli Friedman852d63b2009-06-01 01:22:52 +00004291 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4292 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004293
Chris Lattner1adb8832008-01-14 05:45:46 +00004294 // We want to consider the two function types to be the same for these
4295 // comparisons, just force one to the other.
4296 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4297 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004298
4299 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004300 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4301 LHSClass = Type::ConstantArray;
4302 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4303 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Nate Begeman213541a2008-04-18 23:10:10 +00004305 // Canonicalize ExtVector -> Vector.
4306 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4307 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Chris Lattnera36a61f2008-04-07 05:43:21 +00004309 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004310 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004311 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004312 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004313 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004314 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4315 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004316 }
John McCall183700f2009-09-21 23:43:11 +00004317 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004318 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4319 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004320 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004321
Eli Friedman3d815e72008-08-22 00:56:42 +00004322 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004323 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004324
Steve Naroff4a746782008-01-09 22:43:08 +00004325 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004326 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004327#define TYPE(Class, Base)
4328#define ABSTRACT_TYPE(Class, Base)
4329#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4330#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4331#include "clang/AST/TypeNodes.def"
4332 assert(false && "Non-canonical and dependent types shouldn't get here");
4333 return QualType();
4334
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004335 case Type::LValueReference:
4336 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004337 case Type::MemberPointer:
4338 assert(false && "C++ should never be in mergeTypes");
4339 return QualType();
4340
4341 case Type::IncompleteArray:
4342 case Type::VariableArray:
4343 case Type::FunctionProto:
4344 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004345 assert(false && "Types are eliminated above");
4346 return QualType();
4347
Chris Lattner1adb8832008-01-14 05:45:46 +00004348 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004349 {
4350 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004351 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4352 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004353 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4354 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004355 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004356 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004357 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004358 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004359 return getPointerType(ResultType);
4360 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004361 case Type::BlockPointer:
4362 {
4363 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004364 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4365 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004366 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4367 if (ResultType.isNull()) return QualType();
4368 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4369 return LHS;
4370 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4371 return RHS;
4372 return getBlockPointerType(ResultType);
4373 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004374 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004375 {
4376 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4377 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4378 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4379 return QualType();
4380
4381 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4382 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4383 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4384 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004385 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4386 return LHS;
4387 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4388 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004389 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4390 ArrayType::ArraySizeModifier(), 0);
4391 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4392 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004393 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4394 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004395 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4396 return LHS;
4397 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4398 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004399 if (LVAT) {
4400 // FIXME: This isn't correct! But tricky to implement because
4401 // the array's size has to be the size of LHS, but the type
4402 // has to be different.
4403 return LHS;
4404 }
4405 if (RVAT) {
4406 // FIXME: This isn't correct! But tricky to implement because
4407 // the array's size has to be the size of RHS, but the type
4408 // has to be different.
4409 return RHS;
4410 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004411 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4412 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004413 return getIncompleteArrayType(ResultType,
4414 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004415 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004416 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004417 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004418 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004419 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004420 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004421 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004422 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004423 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004424 case Type::Complex:
4425 // Distinct complex types are incompatible.
4426 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004427 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004428 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004429 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004430 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004431 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004432 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004433 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004434 // FIXME: This should be type compatibility, e.g. whether
4435 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004436 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4437 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004438 if (LHSIface && RHSIface &&
4439 canAssignObjCInterfaces(LHSIface, RHSIface))
4440 return LHS;
4441
Eli Friedman3d815e72008-08-22 00:56:42 +00004442 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004443 }
Steve Naroff14108da2009-07-10 23:34:53 +00004444 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004445 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4446 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004447 return LHS;
4448
Steve Naroffbc76dd02008-12-10 22:14:21 +00004449 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004450 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004451 case Type::FixedWidthInt:
4452 // Distinct fixed-width integers are not compatible.
4453 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004454 case Type::TemplateSpecialization:
4455 assert(false && "Dependent types have no size");
4456 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004457 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004458
4459 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004460}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004461
Chris Lattner5426bf62008-04-07 07:01:58 +00004462//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004463// Integer Predicates
4464//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004465
Eli Friedmanad74a752008-06-28 06:23:08 +00004466unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004467 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004468 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004469 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004470 return FWIT->getWidth();
4471 }
4472 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004473 return (unsigned)getTypeSize(T);
4474}
4475
4476QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4477 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004478
4479 // Turn <4 x signed int> -> <4 x unsigned int>
4480 if (const VectorType *VTy = T->getAs<VectorType>())
4481 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4482 VTy->getNumElements());
4483
4484 // For enums, we return the unsigned version of the base type.
4485 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004486 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004487
4488 const BuiltinType *BTy = T->getAs<BuiltinType>();
4489 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004490 switch (BTy->getKind()) {
4491 case BuiltinType::Char_S:
4492 case BuiltinType::SChar:
4493 return UnsignedCharTy;
4494 case BuiltinType::Short:
4495 return UnsignedShortTy;
4496 case BuiltinType::Int:
4497 return UnsignedIntTy;
4498 case BuiltinType::Long:
4499 return UnsignedLongTy;
4500 case BuiltinType::LongLong:
4501 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004502 case BuiltinType::Int128:
4503 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004504 default:
4505 assert(0 && "Unexpected signed integer type");
4506 return QualType();
4507 }
4508}
4509
Douglas Gregor2cf26342009-04-09 22:27:44 +00004510ExternalASTSource::~ExternalASTSource() { }
4511
4512void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004513
4514
4515//===----------------------------------------------------------------------===//
4516// Builtin Type Computation
4517//===----------------------------------------------------------------------===//
4518
4519/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4520/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004521static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004522 ASTContext::GetBuiltinTypeError &Error,
4523 bool AllowTypeModifiers = true) {
4524 // Modifiers.
4525 int HowLong = 0;
4526 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004527
Chris Lattner86df27b2009-06-14 00:45:47 +00004528 // Read the modifiers first.
4529 bool Done = false;
4530 while (!Done) {
4531 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004532 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004533 case 'S':
4534 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4535 assert(!Signed && "Can't use 'S' modifier multiple times!");
4536 Signed = true;
4537 break;
4538 case 'U':
4539 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4540 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4541 Unsigned = true;
4542 break;
4543 case 'L':
4544 assert(HowLong <= 2 && "Can't have LLLL modifier");
4545 ++HowLong;
4546 break;
4547 }
4548 }
4549
4550 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Chris Lattner86df27b2009-06-14 00:45:47 +00004552 // Read the base type.
4553 switch (*Str++) {
4554 default: assert(0 && "Unknown builtin type letter!");
4555 case 'v':
4556 assert(HowLong == 0 && !Signed && !Unsigned &&
4557 "Bad modifiers used with 'v'!");
4558 Type = Context.VoidTy;
4559 break;
4560 case 'f':
4561 assert(HowLong == 0 && !Signed && !Unsigned &&
4562 "Bad modifiers used with 'f'!");
4563 Type = Context.FloatTy;
4564 break;
4565 case 'd':
4566 assert(HowLong < 2 && !Signed && !Unsigned &&
4567 "Bad modifiers used with 'd'!");
4568 if (HowLong)
4569 Type = Context.LongDoubleTy;
4570 else
4571 Type = Context.DoubleTy;
4572 break;
4573 case 's':
4574 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4575 if (Unsigned)
4576 Type = Context.UnsignedShortTy;
4577 else
4578 Type = Context.ShortTy;
4579 break;
4580 case 'i':
4581 if (HowLong == 3)
4582 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4583 else if (HowLong == 2)
4584 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4585 else if (HowLong == 1)
4586 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4587 else
4588 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4589 break;
4590 case 'c':
4591 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4592 if (Signed)
4593 Type = Context.SignedCharTy;
4594 else if (Unsigned)
4595 Type = Context.UnsignedCharTy;
4596 else
4597 Type = Context.CharTy;
4598 break;
4599 case 'b': // boolean
4600 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4601 Type = Context.BoolTy;
4602 break;
4603 case 'z': // size_t.
4604 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4605 Type = Context.getSizeType();
4606 break;
4607 case 'F':
4608 Type = Context.getCFConstantStringType();
4609 break;
4610 case 'a':
4611 Type = Context.getBuiltinVaListType();
4612 assert(!Type.isNull() && "builtin va list type not initialized!");
4613 break;
4614 case 'A':
4615 // This is a "reference" to a va_list; however, what exactly
4616 // this means depends on how va_list is defined. There are two
4617 // different kinds of va_list: ones passed by value, and ones
4618 // passed by reference. An example of a by-value va_list is
4619 // x86, where va_list is a char*. An example of by-ref va_list
4620 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4621 // we want this argument to be a char*&; for x86-64, we want
4622 // it to be a __va_list_tag*.
4623 Type = Context.getBuiltinVaListType();
4624 assert(!Type.isNull() && "builtin va list type not initialized!");
4625 if (Type->isArrayType()) {
4626 Type = Context.getArrayDecayedType(Type);
4627 } else {
4628 Type = Context.getLValueReferenceType(Type);
4629 }
4630 break;
4631 case 'V': {
4632 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004633 unsigned NumElements = strtoul(Str, &End, 10);
4634 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Chris Lattner86df27b2009-06-14 00:45:47 +00004636 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Chris Lattner86df27b2009-06-14 00:45:47 +00004638 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4639 Type = Context.getVectorType(ElementType, NumElements);
4640 break;
4641 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004642 case 'X': {
4643 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4644 Type = Context.getComplexType(ElementType);
4645 break;
4646 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004647 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004648 Type = Context.getFILEType();
4649 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004650 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004651 return QualType();
4652 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004653 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004654 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004655 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004656 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004657 else
4658 Type = Context.getjmp_bufType();
4659
Mike Stumpfd612db2009-07-28 23:47:15 +00004660 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004661 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004662 return QualType();
4663 }
4664 break;
Mike Stump782fa302009-07-28 02:25:19 +00004665 }
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Chris Lattner86df27b2009-06-14 00:45:47 +00004667 if (!AllowTypeModifiers)
4668 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Chris Lattner86df27b2009-06-14 00:45:47 +00004670 Done = false;
4671 while (!Done) {
4672 switch (*Str++) {
4673 default: Done = true; --Str; break;
4674 case '*':
4675 Type = Context.getPointerType(Type);
4676 break;
4677 case '&':
4678 Type = Context.getLValueReferenceType(Type);
4679 break;
4680 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4681 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004682 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004683 break;
4684 }
4685 }
Mike Stump1eb44332009-09-09 15:08:12 +00004686
Chris Lattner86df27b2009-06-14 00:45:47 +00004687 return Type;
4688}
4689
4690/// GetBuiltinType - Return the type for the specified builtin.
4691QualType ASTContext::GetBuiltinType(unsigned id,
4692 GetBuiltinTypeError &Error) {
4693 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Chris Lattner86df27b2009-06-14 00:45:47 +00004695 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Chris Lattner86df27b2009-06-14 00:45:47 +00004697 Error = GE_None;
4698 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4699 if (Error != GE_None)
4700 return QualType();
4701 while (TypeStr[0] && TypeStr[0] != '.') {
4702 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4703 if (Error != GE_None)
4704 return QualType();
4705
4706 // Do array -> pointer decay. The builtin should use the decayed type.
4707 if (Ty->isArrayType())
4708 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Chris Lattner86df27b2009-06-14 00:45:47 +00004710 ArgTypes.push_back(Ty);
4711 }
4712
4713 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4714 "'.' should only occur at end of builtin type list!");
4715
4716 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4717 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4718 return getFunctionNoProtoType(ResType);
4719 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4720 TypeStr[0] == '.', 0);
4721}
Eli Friedmana95d7572009-08-19 07:44:53 +00004722
4723QualType
4724ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4725 // Perform the usual unary conversions. We do this early so that
4726 // integral promotions to "int" can allow us to exit early, in the
4727 // lhs == rhs check. Also, for conversion purposes, we ignore any
4728 // qualifiers. For example, "const float" and "float" are
4729 // equivalent.
4730 if (lhs->isPromotableIntegerType())
4731 lhs = getPromotedIntegerType(lhs);
4732 else
4733 lhs = lhs.getUnqualifiedType();
4734 if (rhs->isPromotableIntegerType())
4735 rhs = getPromotedIntegerType(rhs);
4736 else
4737 rhs = rhs.getUnqualifiedType();
4738
4739 // If both types are identical, no conversion is needed.
4740 if (lhs == rhs)
4741 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Eli Friedmana95d7572009-08-19 07:44:53 +00004743 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4744 // The caller can deal with this (e.g. pointer + int).
4745 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4746 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004747
4748 // At this point, we have two different arithmetic types.
4749
Eli Friedmana95d7572009-08-19 07:44:53 +00004750 // Handle complex types first (C99 6.3.1.8p1).
4751 if (lhs->isComplexType() || rhs->isComplexType()) {
4752 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004753 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004754 // convert the rhs to the lhs complex type.
4755 return lhs;
4756 }
Mike Stump1eb44332009-09-09 15:08:12 +00004757 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004758 // convert the lhs to the rhs complex type.
4759 return rhs;
4760 }
4761 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004762 // When both operands are complex, the shorter operand is converted to the
4763 // type of the longer, and that is the type of the result. This corresponds
4764 // to what is done when combining two real floating-point operands.
4765 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004766 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004767 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004768 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004769 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004770 // "double _Complex" is promoted to "long double _Complex".
4771 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004772
4773 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004774 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004775 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004776 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004777 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004778 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4779 // domains match. This is a requirement for our implementation, C99
4780 // does not require this promotion.
4781 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4782 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4783 return rhs;
4784 } else { // handle "_Complex double, double".
4785 return lhs;
4786 }
4787 }
4788 return lhs; // The domain/size match exactly.
4789 }
4790 // Now handle "real" floating types (i.e. float, double, long double).
4791 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4792 // if we have an integer operand, the result is the real floating type.
4793 if (rhs->isIntegerType()) {
4794 // convert rhs to the lhs floating point type.
4795 return lhs;
4796 }
4797 if (rhs->isComplexIntegerType()) {
4798 // convert rhs to the complex floating point type.
4799 return getComplexType(lhs);
4800 }
4801 if (lhs->isIntegerType()) {
4802 // convert lhs to the rhs floating point type.
4803 return rhs;
4804 }
Mike Stump1eb44332009-09-09 15:08:12 +00004805 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004806 // convert lhs to the complex floating point type.
4807 return getComplexType(rhs);
4808 }
4809 // We have two real floating types, float/complex combos were handled above.
4810 // Convert the smaller operand to the bigger result.
4811 int result = getFloatingTypeOrder(lhs, rhs);
4812 if (result > 0) // convert the rhs
4813 return lhs;
4814 assert(result < 0 && "illegal float comparison");
4815 return rhs; // convert the lhs
4816 }
4817 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4818 // Handle GCC complex int extension.
4819 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4820 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4821
4822 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004823 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004824 rhsComplexInt->getElementType()) >= 0)
4825 return lhs; // convert the rhs
4826 return rhs;
4827 } else if (lhsComplexInt && rhs->isIntegerType()) {
4828 // convert the rhs to the lhs complex type.
4829 return lhs;
4830 } else if (rhsComplexInt && lhs->isIntegerType()) {
4831 // convert the lhs to the rhs complex type.
4832 return rhs;
4833 }
4834 }
4835 // Finally, we have two differing integer types.
4836 // The rules for this case are in C99 6.3.1.8
4837 int compare = getIntegerTypeOrder(lhs, rhs);
4838 bool lhsSigned = lhs->isSignedIntegerType(),
4839 rhsSigned = rhs->isSignedIntegerType();
4840 QualType destType;
4841 if (lhsSigned == rhsSigned) {
4842 // Same signedness; use the higher-ranked type
4843 destType = compare >= 0 ? lhs : rhs;
4844 } else if (compare != (lhsSigned ? 1 : -1)) {
4845 // The unsigned type has greater than or equal rank to the
4846 // signed type, so use the unsigned type
4847 destType = lhsSigned ? rhs : lhs;
4848 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4849 // The two types are different widths; if we are here, that
4850 // means the signed type is larger than the unsigned type, so
4851 // use the signed type.
4852 destType = lhsSigned ? lhs : rhs;
4853 } else {
4854 // The signed type is higher-ranked than the unsigned type,
4855 // but isn't actually any bigger (like unsigned int and long
4856 // on most 32-bit systems). Use the unsigned type corresponding
4857 // to the signed type.
4858 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4859 }
4860 return destType;
4861}