blob: 13da4b8b130260b41ee04ecd6e710a59b2fde084 [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"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000059 if (FreeMemory) {
60 // Deallocate all the types.
61 while (!Types.empty()) {
62 Types.back()->Destroy(*this);
63 Types.pop_back();
64 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000065
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000066 for (llvm::FoldingSet<ExtQuals>::iterator
67 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
68 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000069 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 }
71 }
72
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000073 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
74 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
75 // Increment in loop to prevent using deallocated memory.
76 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
77 delete R;
78 }
79
80 for (llvm::DenseMap<const ObjCContainerDecl*,
81 const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
83 // Increment in loop to prevent using deallocated memory.
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
Nuno Lopesb74668e2008-12-17 22:30:25 +000086 }
87
Douglas Gregorab452ba2009-03-26 23:50:42 +000088 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000089 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000091 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000092 NNS != NNSEnd; ) {
93 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000095 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000263ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000265 = InstantiatedFromUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
John McCalled976492009-12-04 22:46:56 +0000273ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
274 assert((isa<UsingDecl>(Pattern) ||
275 isa<UnresolvedUsingValueDecl>(Pattern) ||
276 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277 "pattern decl is not a using decl");
278 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279 InstantiatedFromUsingDecl[Inst] = Pattern;
280}
281
282UsingShadowDecl *
283ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
284 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
285 = InstantiatedFromUsingShadowDecl.find(Inst);
286 if (Pos == InstantiatedFromUsingShadowDecl.end())
287 return 0;
288
289 return Pos->second;
290}
291
292void
293ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294 UsingShadowDecl *Pattern) {
295 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
296 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000297}
298
Anders Carlssond8b285f2009-09-01 04:26:58 +0000299FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301 = InstantiatedFromUnnamedFieldDecl.find(Field);
302 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Anders Carlssond8b285f2009-09-01 04:26:58 +0000305 return Pos->second;
306}
307
308void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309 FieldDecl *Tmpl) {
310 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
311 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316}
317
Douglas Gregor2e222532009-07-02 17:08:52 +0000318namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 : std::binary_function<SourceRange, SourceRange, bool> {
321 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Douglas Gregor2e222532009-07-02 17:08:52 +0000323 public:
324 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 bool operator()(SourceRange X, SourceRange Y) {
327 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328 }
329 };
330}
331
332/// \brief Determine whether the given comment is a Doxygen-style comment.
333///
334/// \param Start the start of the comment text.
335///
336/// \param End the end of the comment text.
337///
338/// \param Member whether we want to check whether this is a member comment
339/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
340/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000341static bool
342isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000343 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000345 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
346 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
347 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 if (End - Start < 4)
350 return false;
351
352 assert(Start[0] == '/' && "Not a comment?");
353 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
354 return false;
355 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
356 return false;
357
358 return (Start[3] == '<') == Member;
359}
360
361/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000362/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000363const char *ASTContext::getCommentForDecl(const Decl *D) {
364 if (!D)
365 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Douglas Gregor2e222532009-07-02 17:08:52 +0000367 // Check whether we have cached a comment string for this declaration
368 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000369 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000370 = DeclComments.find(D);
371 if (Pos != DeclComments.end())
372 return Pos->second.c_str();
373
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000375 // that source, do so now.
376 if (ExternalSource && !LoadedExternalComments) {
377 std::vector<SourceRange> LoadedComments;
378 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 if (!LoadedComments.empty())
381 Comments.insert(Comments.begin(), LoadedComments.begin(),
382 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 LoadedExternalComments = true;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
387 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 if (Comments.empty())
389 return 0;
390
391 // If the declaration doesn't map directly to a location in a file, we
392 // can't find the comment.
393 SourceLocation DeclStartLoc = D->getLocStart();
394 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
395 return 0;
396
397 // Find the comment that occurs just before this declaration.
398 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000399 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000400 SourceRange(DeclStartLoc),
401 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 // Decompose the location for the start of the declaration and find the
404 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000406 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000407 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 // First check whether we have a comment for a member.
411 if (LastComment != Comments.end() &&
412 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
413 isDoxygenComment(SourceMgr, *LastComment, true)) {
414 std::pair<FileID, unsigned> LastCommentEndDecomp
415 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
416 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000418 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000419 LastCommentEndDecomp.second)) {
420 // The Doxygen member comment comes after the declaration starts and
421 // is on the same line and in the same file as the declaration. This
422 // is the comment we want.
423 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000424 Result.append(FileBufferStart +
425 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000426 FileBufferStart + LastCommentEndDecomp.second + 1);
427 return Result.c_str();
428 }
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Douglas Gregor2e222532009-07-02 17:08:52 +0000431 if (LastComment == Comments.begin())
432 return 0;
433 --LastComment;
434
435 // Decompose the end of the comment.
436 std::pair<FileID, unsigned> LastCommentEndDecomp
437 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor2e222532009-07-02 17:08:52 +0000439 // If the comment and the declaration aren't in the same file, then they
440 // aren't related.
441 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
442 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor2e222532009-07-02 17:08:52 +0000444 // Check that we actually have a Doxygen comment.
445 if (!isDoxygenComment(SourceMgr, *LastComment))
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-07-02 17:08:52 +0000448 // Compute the starting line for the declaration and for the end of the
449 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000450 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000453 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-07-02 17:08:52 +0000456 // If the comment does not end on the line prior to the declaration, then
457 // the comment is not associated with the declaration at all.
458 if (CommentEndLine + 1 != DeclStartLine)
459 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Douglas Gregor2e222532009-07-02 17:08:52 +0000461 // We have a comment, but there may be more comments on the previous lines.
462 // Keep looking so long as the comments are still Doxygen comments and are
463 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000464 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000465 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
466 std::vector<SourceRange>::iterator FirstComment = LastComment;
467 while (FirstComment != Comments.begin()) {
468 // Look at the previous comment
469 --FirstComment;
470 std::pair<FileID, unsigned> Decomp
471 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor2e222532009-07-02 17:08:52 +0000473 // If this previous comment is in a different file, we're done.
474 if (Decomp.first != DeclStartDecomp.first) {
475 ++FirstComment;
476 break;
477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregor2e222532009-07-02 17:08:52 +0000479 // If this comment is not a Doxygen comment, we're done.
480 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
481 ++FirstComment;
482 break;
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor2e222532009-07-02 17:08:52 +0000485 // If the line number is not what we expected, we're done.
486 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
487 if (Line != ExpectedLine) {
488 ++FirstComment;
489 break;
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000493 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Douglas Gregor2e222532009-07-02 17:08:52 +0000497 // The iterator range [FirstComment, LastComment] contains all of the
498 // BCPL comments that, together, are associated with this declaration.
499 // Form a single comment block string for this declaration that concatenates
500 // all of these comments.
501 std::string &Result = DeclComments[D];
502 while (FirstComment != LastComment) {
503 std::pair<FileID, unsigned> DecompStart
504 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
505 std::pair<FileID, unsigned> DecompEnd
506 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
507 Result.append(FileBufferStart + DecompStart.second,
508 FileBufferStart + DecompEnd.second + 1);
509 ++FirstComment;
510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor2e222532009-07-02 17:08:52 +0000512 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 Result.append(FileBufferStart +
514 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 FileBufferStart + LastCommentEndDecomp.second + 1);
516 return Result.c_str();
517}
518
Chris Lattner464175b2007-07-18 17:52:12 +0000519//===----------------------------------------------------------------------===//
520// Type Sizing and Analysis
521//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000522
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000523/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
524/// scalar floating point type.
525const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000526 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527 assert(BT && "Not a floating point type!");
528 switch (BT->getKind()) {
529 default: assert(0 && "Not a floating point type!");
530 case BuiltinType::Float: return Target.getFloatFormat();
531 case BuiltinType::Double: return Target.getDoubleFormat();
532 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
533 }
534}
535
Mike Stump196efbf2009-09-22 02:43:44 +0000536/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537/// specified decl. Note that bitfields do not have a valid alignment, so
538/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000539/// If @p RefAsPointee, references are treated like their underlying type
540/// (for alignof), else they're treated like pointers (for CodeGen).
541unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000542 unsigned Align = Target.getCharWidth();
543
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000544 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000545 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546
Chris Lattneraf707ab2009-01-24 21:53:27 +0000547 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000549 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000550 if (RefAsPointee)
551 T = RT->getPointeeType();
552 else
553 T = getPointerType(RT->getPointeeType());
554 }
555 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000557 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558 T = cast<ArrayType>(T)->getElementType();
559
560 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000562 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000563
564 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000565}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000566
Chris Lattnera7674d82007-07-13 22:13:22 +0000567/// getTypeSize - Return the size of the specified type, in bits. This method
568/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000569///
570/// FIXME: Pointers into different addr spaces could have different sizes and
571/// alignment requirements: getPointerInfo should take an AddrSpace, this
572/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000573std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000574ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000575 uint64_t Width=0;
576 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000577 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000578#define TYPE(Class, Base)
579#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000580#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000583 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000584 break;
585
Chris Lattner692233e2007-07-13 22:27:08 +0000586 case Type::FunctionNoProto:
587 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000588 // GCC extension: alignof(function) = 32 bits
589 Width = 0;
590 Align = 32;
591 break;
592
Douglas Gregor72564e72009-02-26 23:50:07 +0000593 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000594 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000595 Width = 0;
596 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597 break;
598
Steve Narofffb22d962007-08-30 01:06:46 +0000599 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000600 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner98be4942008-03-05 18:54:05 +0000602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000603 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000604 Align = EltInfo.second;
605 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000606 }
Nate Begeman213541a2008-04-18 23:10:10 +0000607 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000608 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000609 const VectorType *VT = cast<VectorType>(T);
610 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
611 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000612 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000613 // If the alignment is not a power of 2, round up to the next power of 2.
614 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000615 if (VT->getNumElements() & (VT->getNumElements()-1)) {
616 Align = llvm::NextPowerOf2(Align);
617 Width = llvm::RoundUpToAlignment(Width, Align);
618 }
Chris Lattner030d8842007-07-19 22:06:24 +0000619 break;
620 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000621
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000623 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000624 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000625 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000626 // GCC extension: alignof(void) = 8 bits.
627 Width = 0;
628 Align = 8;
629 break;
630
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getBoolWidth();
633 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::Char_S:
636 case BuiltinType::Char_U:
637 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getCharWidth();
640 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000642 case BuiltinType::WChar:
643 Width = Target.getWCharWidth();
644 Align = Target.getWCharAlign();
645 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000646 case BuiltinType::Char16:
647 Width = Target.getChar16Width();
648 Align = Target.getChar16Align();
649 break;
650 case BuiltinType::Char32:
651 Width = Target.getChar32Width();
652 Align = Target.getChar32Align();
653 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000654 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getShortWidth();
657 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000659 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000660 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000661 Width = Target.getIntWidth();
662 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000664 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000666 Width = Target.getLongWidth();
667 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000669 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000671 Width = Target.getLongLongWidth();
672 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000674 case BuiltinType::Int128:
675 case BuiltinType::UInt128:
676 Width = 128;
677 Align = 128; // int128_t is 128-bit aligned on all targets.
678 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000680 Width = Target.getFloatWidth();
681 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 break;
683 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000684 Width = Target.getDoubleWidth();
685 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 Width = Target.getLongDoubleWidth();
689 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000691 case BuiltinType::NullPtr:
692 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
693 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000694 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000695 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000696 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000697 case Type::FixedWidthInt:
698 // FIXME: This isn't precisely correct; the width/alignment should depend
699 // on the available types for the target
700 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000701 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000702 Align = Width;
703 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000704 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000705 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000706 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000708 case Type::BlockPointer: {
709 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
710 Width = Target.getPointerWidth(AS);
711 Align = Target.getPointerAlign(AS);
712 break;
713 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000714 case Type::LValueReference:
715 case Type::RValueReference: {
716 // alignof and sizeof should never enter this code path here, so we go
717 // the pointer route.
718 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
719 Width = Target.getPointerWidth(AS);
720 Align = Target.getPointerAlign(AS);
721 break;
722 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 case Type::Pointer: {
724 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000725 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000726 Align = Target.getPointerAlign(AS);
727 break;
728 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000729 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000730 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000731 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000732 getTypeInfo(getPointerDiffType());
733 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000734 if (Pointee->isFunctionType())
735 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000736 Align = PtrDiffInfo.second;
737 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000738 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000739 case Type::Complex: {
740 // Complex types have the same alignment as their elements, but twice the
741 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000742 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000743 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000744 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000745 Align = EltInfo.second;
746 break;
747 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000748 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000749 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000750 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
751 Width = Layout.getSize();
752 Align = Layout.getAlignment();
753 break;
754 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000755 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000756 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000757 const TagType *TT = cast<TagType>(T);
758
759 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000760 Width = 1;
761 Align = 1;
762 break;
763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Daniel Dunbar1d751182008-11-08 05:48:37 +0000765 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000766 return getTypeInfo(ET->getDecl()->getIntegerType());
767
Daniel Dunbar1d751182008-11-08 05:48:37 +0000768 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000769 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
770 Width = Layout.getSize();
771 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000772 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000773 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000774
Chris Lattner9fcfe922009-10-22 05:17:15 +0000775 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000776 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
777 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000778
Chris Lattner9fcfe922009-10-22 05:17:15 +0000779 case Type::Elaborated:
780 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
781 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000782
Douglas Gregor18857642009-04-30 17:32:17 +0000783 case Type::Typedef: {
784 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000785 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000786 Align = std::max(Aligned->getMaxAlignment(),
787 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000788 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
789 } else
790 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000791 break;
Chris Lattner71763312008-04-06 22:05:18 +0000792 }
Douglas Gregor18857642009-04-30 17:32:17 +0000793
794 case Type::TypeOfExpr:
795 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
796 .getTypePtr());
797
798 case Type::TypeOf:
799 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
800
Anders Carlsson395b4752009-06-24 19:06:50 +0000801 case Type::Decltype:
802 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
803 .getTypePtr());
804
Douglas Gregor18857642009-04-30 17:32:17 +0000805 case Type::QualifiedName:
806 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Douglas Gregor18857642009-04-30 17:32:17 +0000808 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000809 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000810 "Cannot request the size of a dependent type");
811 // FIXME: this is likely to be wrong once we support template
812 // aliases, since a template alias could refer to a typedef that
813 // has an __aligned__ attribute on it.
814 return getTypeInfo(getCanonicalType(T));
815 }
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Chris Lattner464175b2007-07-18 17:52:12 +0000817 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000818 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000819}
820
Ken Dyckbdc601b2009-12-22 14:23:30 +0000821/// getTypeSizeInChars - Return the size of the specified type, in characters.
822/// This method does not work on incomplete types.
823CharUnits ASTContext::getTypeSizeInChars(QualType T) {
824 return CharUnits::fromRaw(getTypeSize(T) / getCharWidth());
825}
826CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
827 return CharUnits::fromRaw(getTypeSize(T) / getCharWidth());
828}
829
Chris Lattner34ebde42009-01-27 18:08:34 +0000830/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
831/// type for the current target in bits. This can be different than the ABI
832/// alignment in cases where it is beneficial for performance to overalign
833/// a data type.
834unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
835 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000836
837 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000838 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000839 T = CT->getElementType().getTypePtr();
840 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
841 T->isSpecificBuiltinType(BuiltinType::LongLong))
842 return std::max(ABIAlign, (unsigned)getTypeSize(T));
843
Chris Lattner34ebde42009-01-27 18:08:34 +0000844 return ABIAlign;
845}
846
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000847static void CollectLocalObjCIvars(ASTContext *Ctx,
848 const ObjCInterfaceDecl *OI,
849 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000850 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
851 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000852 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000853 if (!IVDecl->isInvalidDecl())
854 Fields.push_back(cast<FieldDecl>(IVDecl));
855 }
856}
857
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000858void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
859 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
860 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
861 CollectObjCIvars(SuperClass, Fields);
862 CollectLocalObjCIvars(this, OI, Fields);
863}
864
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000865/// ShallowCollectObjCIvars -
866/// Collect all ivars, including those synthesized, in the current class.
867///
868void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
869 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
870 bool CollectSynthesized) {
871 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
872 E = OI->ivar_end(); I != E; ++I) {
873 Ivars.push_back(*I);
874 }
875 if (CollectSynthesized)
876 CollectSynthesizedIvars(OI, Ivars);
877}
878
Fariborz Jahanian98200742009-05-12 18:14:29 +0000879void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
880 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000881 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
882 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000883 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
884 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Fariborz Jahanian98200742009-05-12 18:14:29 +0000886 // Also look into nested protocols.
887 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
888 E = PD->protocol_end(); P != E; ++P)
889 CollectProtocolSynthesizedIvars(*P, Ivars);
890}
891
892/// CollectSynthesizedIvars -
893/// This routine collect synthesized ivars for the designated class.
894///
895void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
896 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000897 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
898 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000899 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
900 Ivars.push_back(Ivar);
901 }
902 // Also look into interface's protocol list for properties declared
903 // in the protocol and whose ivars are synthesized.
904 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
905 PE = OI->protocol_end(); P != PE; ++P) {
906 ObjCProtocolDecl *PD = (*P);
907 CollectProtocolSynthesizedIvars(PD, Ivars);
908 }
909}
910
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000911/// CollectInheritedProtocols - Collect all protocols in current class and
912/// those inherited by it.
913void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
914 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
915 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
916 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
917 PE = OI->protocol_end(); P != PE; ++P) {
918 ObjCProtocolDecl *Proto = (*P);
919 Protocols.push_back(Proto);
920 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
921 PE = Proto->protocol_end(); P != PE; ++P)
922 CollectInheritedProtocols(*P, Protocols);
923 }
924
925 // Categories of this Interface.
926 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
927 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
928 CollectInheritedProtocols(CDeclChain, Protocols);
929 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
930 while (SD) {
931 CollectInheritedProtocols(SD, Protocols);
932 SD = SD->getSuperClass();
933 }
934 return;
935 }
936 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
937 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
938 PE = OC->protocol_end(); P != PE; ++P) {
939 ObjCProtocolDecl *Proto = (*P);
940 Protocols.push_back(Proto);
941 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
942 PE = Proto->protocol_end(); P != PE; ++P)
943 CollectInheritedProtocols(*P, Protocols);
944 }
945 return;
946 }
947 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
948 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
949 PE = OP->protocol_end(); P != PE; ++P) {
950 ObjCProtocolDecl *Proto = (*P);
951 Protocols.push_back(Proto);
952 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
953 PE = Proto->protocol_end(); P != PE; ++P)
954 CollectInheritedProtocols(*P, Protocols);
955 }
956 return;
957 }
958}
959
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000960unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
961 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000962 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
963 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000964 if ((*I)->getPropertyIvarDecl())
965 ++count;
966
967 // Also look into nested protocols.
968 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
969 E = PD->protocol_end(); P != E; ++P)
970 count += CountProtocolSynthesizedIvars(*P);
971 return count;
972}
973
Mike Stump1eb44332009-09-09 15:08:12 +0000974unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000975 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000976 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
977 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000978 if ((*I)->getPropertyIvarDecl())
979 ++count;
980 }
981 // Also look into interface's protocol list for properties declared
982 // in the protocol and whose ivars are synthesized.
983 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
984 PE = OI->protocol_end(); P != PE; ++P) {
985 ObjCProtocolDecl *PD = (*P);
986 count += CountProtocolSynthesizedIvars(PD);
987 }
988 return count;
989}
990
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000991/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
992ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
993 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
994 I = ObjCImpls.find(D);
995 if (I != ObjCImpls.end())
996 return cast<ObjCImplementationDecl>(I->second);
997 return 0;
998}
999/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1000ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1001 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1002 I = ObjCImpls.find(D);
1003 if (I != ObjCImpls.end())
1004 return cast<ObjCCategoryImplDecl>(I->second);
1005 return 0;
1006}
1007
1008/// \brief Set the implementation of ObjCInterfaceDecl.
1009void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1010 ObjCImplementationDecl *ImplD) {
1011 assert(IFaceD && ImplD && "Passed null params");
1012 ObjCImpls[IFaceD] = ImplD;
1013}
1014/// \brief Set the implementation of ObjCCategoryDecl.
1015void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1016 ObjCCategoryImplDecl *ImplD) {
1017 assert(CatD && ImplD && "Passed null params");
1018 ObjCImpls[CatD] = ImplD;
1019}
1020
John McCalla93c9342009-12-07 02:54:59 +00001021/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001022///
John McCalla93c9342009-12-07 02:54:59 +00001023/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001024/// the TypeLoc wrappers.
1025///
1026/// \param T the type that will be the basis for type source info. This type
1027/// should refer to how the declarator was written in source code, not to
1028/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001029TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001030 unsigned DataSize) {
1031 if (!DataSize)
1032 DataSize = TypeLoc::getFullDataSizeForType(T);
1033 else
1034 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001035 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001036
John McCalla93c9342009-12-07 02:54:59 +00001037 TypeSourceInfo *TInfo =
1038 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1039 new (TInfo) TypeSourceInfo(T);
1040 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001041}
1042
John McCalla93c9342009-12-07 02:54:59 +00001043TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001044 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001045 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001046 DI->getTypeLoc().initialize(L);
1047 return DI;
1048}
1049
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001050/// getInterfaceLayoutImpl - Get or compute information about the
1051/// layout of the given interface.
1052///
1053/// \param Impl - If given, also include the layout of the interface's
1054/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001055const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001056ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1057 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001058 assert(!D->isForwardDecl() && "Invalid interface decl!");
1059
Devang Patel44a3dde2008-06-04 21:54:36 +00001060 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001061 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001062 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1063 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1064 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001065
Daniel Dunbar453addb2009-05-03 11:16:44 +00001066 // Add in synthesized ivar count if laying out an implementation.
1067 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001068 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001069 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001070 // entry. Note we can't cache this because we simply free all
1071 // entries later; however we shouldn't look up implementations
1072 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001073 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001074 return getObjCLayout(D, 0);
1075 }
1076
Mike Stump1eb44332009-09-09 15:08:12 +00001077 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001078 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1079 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Devang Patel44a3dde2008-06-04 21:54:36 +00001081 return *NewEntry;
1082}
1083
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001084const ASTRecordLayout &
1085ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1086 return getObjCLayout(D, 0);
1087}
1088
1089const ASTRecordLayout &
1090ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1091 return getObjCLayout(D->getClassInterface(), D);
1092}
1093
Devang Patel88a981b2007-11-01 19:11:01 +00001094/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001095/// specified record (struct/union/class), which indicates its size and field
1096/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001097const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001098 D = D->getDefinition(*this);
1099 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001100
Chris Lattner464175b2007-07-18 17:52:12 +00001101 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001102 // Note that we can't save a reference to the entry because this function
1103 // is recursive.
1104 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001105 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001106
Mike Stump1eb44332009-09-09 15:08:12 +00001107 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001108 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001109 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner5d2a6302007-07-18 18:26:58 +00001111 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001112}
1113
Anders Carlssonf53df232009-12-07 04:35:11 +00001114const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1115 RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1116 assert(RD && "Cannot get key function for forward declarations!");
1117
1118 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1119 if (!Entry)
1120 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1121 else
1122 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1123 "Key function changed!");
1124
1125 return Entry;
1126}
1127
Chris Lattnera7674d82007-07-13 22:13:22 +00001128//===----------------------------------------------------------------------===//
1129// Type creation/memoization methods
1130//===----------------------------------------------------------------------===//
1131
John McCall0953e762009-09-24 19:53:00 +00001132QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1133 unsigned Fast = Quals.getFastQualifiers();
1134 Quals.removeFastQualifiers();
1135
1136 // Check if we've already instantiated this type.
1137 llvm::FoldingSetNodeID ID;
1138 ExtQuals::Profile(ID, TypeNode, Quals);
1139 void *InsertPos = 0;
1140 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1141 assert(EQ->getQualifiers() == Quals);
1142 QualType T = QualType(EQ, Fast);
1143 return T;
1144 }
1145
John McCall6b304a02009-09-24 23:30:46 +00001146 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001147 ExtQualNodes.InsertNode(New, InsertPos);
1148 QualType T = QualType(New, Fast);
1149 return T;
1150}
1151
1152QualType ASTContext::getVolatileType(QualType T) {
1153 QualType CanT = getCanonicalType(T);
1154 if (CanT.isVolatileQualified()) return T;
1155
1156 QualifierCollector Quals;
1157 const Type *TypeNode = Quals.strip(T);
1158 Quals.addVolatile();
1159
1160 return getExtQualType(TypeNode, Quals);
1161}
1162
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001163QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001164 QualType CanT = getCanonicalType(T);
1165 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001166 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001167
John McCall0953e762009-09-24 19:53:00 +00001168 // If we are composing extended qualifiers together, merge together
1169 // into one ExtQuals node.
1170 QualifierCollector Quals;
1171 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
John McCall0953e762009-09-24 19:53:00 +00001173 // If this type already has an address space specified, it cannot get
1174 // another one.
1175 assert(!Quals.hasAddressSpace() &&
1176 "Type cannot be in multiple addr spaces!");
1177 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001178
John McCall0953e762009-09-24 19:53:00 +00001179 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001180}
1181
Chris Lattnerb7d25532009-02-18 22:53:11 +00001182QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001183 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001184 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001185 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001186 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001188 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001189 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001190 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001191 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1192 return getPointerType(ResultType);
1193 }
1194 }
Mike Stump1eb44332009-09-09 15:08:12 +00001195
John McCall0953e762009-09-24 19:53:00 +00001196 // If we are composing extended qualifiers together, merge together
1197 // into one ExtQuals node.
1198 QualifierCollector Quals;
1199 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
John McCall0953e762009-09-24 19:53:00 +00001201 // If this type already has an ObjCGC specified, it cannot get
1202 // another one.
1203 assert(!Quals.hasObjCGCAttr() &&
1204 "Type cannot have multiple ObjCGCs!");
1205 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
John McCall0953e762009-09-24 19:53:00 +00001207 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001208}
Chris Lattnera7674d82007-07-13 22:13:22 +00001209
Douglas Gregor43c79c22009-12-09 00:47:37 +00001210QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
John McCall0953e762009-09-24 19:53:00 +00001211 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001212 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1213 QualType Pointee = Pointer->getPointeeType();
1214 ResultType = getNoReturnType(Pointee, AddNoReturn);
1215 if (ResultType == Pointee)
1216 return T;
1217
Mike Stump6dcbc292009-07-25 23:24:03 +00001218 ResultType = getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001219 } else if (const BlockPointerType *BlockPointer
1220 = T->getAs<BlockPointerType>()) {
1221 QualType Pointee = BlockPointer->getPointeeType();
1222 ResultType = getNoReturnType(Pointee, AddNoReturn);
1223 if (ResultType == Pointee)
1224 return T;
1225
Mike Stump6dcbc292009-07-25 23:24:03 +00001226 ResultType = getBlockPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001227 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1228 if (F->getNoReturnAttr() == AddNoReturn)
1229 return T;
1230
1231 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1232 ResultType = getFunctionNoProtoType(FNPT->getResultType(), AddNoReturn);
John McCall0953e762009-09-24 19:53:00 +00001233 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001234 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001235 ResultType
Douglas Gregor43c79c22009-12-09 00:47:37 +00001236 = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1237 FPT->getNumArgs(), FPT->isVariadic(),
1238 FPT->getTypeQuals(),
1239 FPT->hasExceptionSpec(), FPT->hasAnyExceptionSpec(),
1240 FPT->getNumExceptions(), FPT->exception_begin(),
1241 AddNoReturn);
John McCall0953e762009-09-24 19:53:00 +00001242 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001243 } else
1244 return T;
1245
Douglas Gregora4923eb2009-11-16 21:35:15 +00001246 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001247}
1248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249/// getComplexType - Return the uniqued reference to the type for a complex
1250/// number with the specified element type.
1251QualType ASTContext::getComplexType(QualType T) {
1252 // Unique pointers, to guarantee there is only one pointer of a particular
1253 // structure.
1254 llvm::FoldingSetNodeID ID;
1255 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 void *InsertPos = 0;
1258 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1259 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // If the pointee type isn't canonical, this won't be a canonical type either,
1262 // so fill in the canonical type field.
1263 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001264 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001265 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 // Get the new insert position for the node we care about.
1268 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001269 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 }
John McCall6b304a02009-09-24 23:30:46 +00001271 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 Types.push_back(New);
1273 ComplexTypes.InsertNode(New, InsertPos);
1274 return QualType(New, 0);
1275}
1276
Eli Friedmanf98aba32009-02-13 02:31:07 +00001277QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1278 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1279 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1280 FixedWidthIntType *&Entry = Map[Width];
1281 if (!Entry)
1282 Entry = new FixedWidthIntType(Width, Signed);
1283 return QualType(Entry, 0);
1284}
Reid Spencer5f016e22007-07-11 17:01:13 +00001285
1286/// getPointerType - Return the uniqued reference to the type for a pointer to
1287/// the specified type.
1288QualType ASTContext::getPointerType(QualType T) {
1289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
1292 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 void *InsertPos = 0;
1295 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1296 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // If the pointee type isn't canonical, this won't be a canonical type either,
1299 // so fill in the canonical type field.
1300 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001301 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001302 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // Get the new insert position for the node we care about.
1305 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001306 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 }
John McCall6b304a02009-09-24 23:30:46 +00001308 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 Types.push_back(New);
1310 PointerTypes.InsertNode(New, InsertPos);
1311 return QualType(New, 0);
1312}
1313
Mike Stump1eb44332009-09-09 15:08:12 +00001314/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001315/// a pointer to the specified block.
1316QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001317 assert(T->isFunctionType() && "block of function types only");
1318 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001319 // structure.
1320 llvm::FoldingSetNodeID ID;
1321 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Steve Naroff5618bd42008-08-27 16:04:49 +00001323 void *InsertPos = 0;
1324 if (BlockPointerType *PT =
1325 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1326 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001327
1328 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001329 // type either so fill in the canonical type field.
1330 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001331 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001332 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Steve Naroff5618bd42008-08-27 16:04:49 +00001334 // Get the new insert position for the node we care about.
1335 BlockPointerType *NewIP =
1336 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001337 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001338 }
John McCall6b304a02009-09-24 23:30:46 +00001339 BlockPointerType *New
1340 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001341 Types.push_back(New);
1342 BlockPointerTypes.InsertNode(New, InsertPos);
1343 return QualType(New, 0);
1344}
1345
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001346/// getLValueReferenceType - Return the uniqued reference to the type for an
1347/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001348QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // Unique pointers, to guarantee there is only one pointer of a particular
1350 // structure.
1351 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001352 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001353
1354 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001355 if (LValueReferenceType *RT =
1356 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001358
John McCall54e14c42009-10-22 22:37:11 +00001359 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // If the referencee type isn't canonical, this won't be a canonical type
1362 // either, so fill in the canonical type field.
1363 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001364 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1365 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1366 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001369 LValueReferenceType *NewIP =
1370 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001371 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 }
1373
John McCall6b304a02009-09-24 23:30:46 +00001374 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001375 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1376 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001378 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001379
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001380 return QualType(New, 0);
1381}
1382
1383/// getRValueReferenceType - Return the uniqued reference to the type for an
1384/// rvalue reference to the specified type.
1385QualType ASTContext::getRValueReferenceType(QualType T) {
1386 // Unique pointers, to guarantee there is only one pointer of a particular
1387 // structure.
1388 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001389 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001390
1391 void *InsertPos = 0;
1392 if (RValueReferenceType *RT =
1393 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1394 return QualType(RT, 0);
1395
John McCall54e14c42009-10-22 22:37:11 +00001396 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1397
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001398 // If the referencee type isn't canonical, this won't be a canonical type
1399 // either, so fill in the canonical type field.
1400 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001401 if (InnerRef || !T.isCanonical()) {
1402 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1403 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001404
1405 // Get the new insert position for the node we care about.
1406 RValueReferenceType *NewIP =
1407 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1408 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1409 }
1410
John McCall6b304a02009-09-24 23:30:46 +00001411 RValueReferenceType *New
1412 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001413 Types.push_back(New);
1414 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 return QualType(New, 0);
1416}
1417
Sebastian Redlf30208a2009-01-24 21:16:55 +00001418/// getMemberPointerType - Return the uniqued reference to the type for a
1419/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001420QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001421 // Unique pointers, to guarantee there is only one pointer of a particular
1422 // structure.
1423 llvm::FoldingSetNodeID ID;
1424 MemberPointerType::Profile(ID, T, Cls);
1425
1426 void *InsertPos = 0;
1427 if (MemberPointerType *PT =
1428 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1429 return QualType(PT, 0);
1430
1431 // If the pointee or class type isn't canonical, this won't be a canonical
1432 // type either, so fill in the canonical type field.
1433 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001434 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001435 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1436
1437 // Get the new insert position for the node we care about.
1438 MemberPointerType *NewIP =
1439 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1440 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1441 }
John McCall6b304a02009-09-24 23:30:46 +00001442 MemberPointerType *New
1443 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001444 Types.push_back(New);
1445 MemberPointerTypes.InsertNode(New, InsertPos);
1446 return QualType(New, 0);
1447}
1448
Mike Stump1eb44332009-09-09 15:08:12 +00001449/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001450/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001451QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001452 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001453 ArrayType::ArraySizeModifier ASM,
1454 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001455 assert((EltTy->isDependentType() ||
1456 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001457 "Constant array of VLAs is illegal!");
1458
Chris Lattner38aeec72009-05-13 04:12:56 +00001459 // Convert the array size into a canonical width matching the pointer size for
1460 // the target.
1461 llvm::APInt ArySize(ArySizeIn);
1462 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001465 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001468 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001469 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // If the element type isn't canonical, this won't be a canonical type either,
1473 // so fill in the canonical type field.
1474 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001475 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001476 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001477 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001479 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001480 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001481 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483
John McCall6b304a02009-09-24 23:30:46 +00001484 ConstantArrayType *New = new(*this,TypeAlignment)
1485 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001486 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 Types.push_back(New);
1488 return QualType(New, 0);
1489}
1490
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001491/// getVariableArrayType - Returns a non-unique reference to the type for a
1492/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001493QualType ASTContext::getVariableArrayType(QualType EltTy,
1494 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001495 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001496 unsigned EltTypeQuals,
1497 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001498 // Since we don't unique expressions, it isn't possible to unique VLA's
1499 // that have an expression provided for their size.
1500
John McCall6b304a02009-09-24 23:30:46 +00001501 VariableArrayType *New = new(*this, TypeAlignment)
1502 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001503
1504 VariableArrayTypes.push_back(New);
1505 Types.push_back(New);
1506 return QualType(New, 0);
1507}
1508
Douglas Gregor898574e2008-12-05 23:32:09 +00001509/// getDependentSizedArrayType - Returns a non-unique reference to
1510/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001511/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001512QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1513 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001514 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001515 unsigned EltTypeQuals,
1516 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001517 assert((!NumElts || NumElts->isTypeDependent() ||
1518 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001519 "Size must be type- or value-dependent!");
1520
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001521 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001522 DependentSizedArrayType *Canon = 0;
1523
1524 if (NumElts) {
1525 // Dependently-sized array types that do not have a specified
1526 // number of elements will have their sizes deduced from an
1527 // initializer.
1528 llvm::FoldingSetNodeID ID;
1529 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1530 EltTypeQuals, NumElts);
1531
1532 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1533 }
1534
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001535 DependentSizedArrayType *New;
1536 if (Canon) {
1537 // We already have a canonical version of this array type; use it as
1538 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001539 New = new (*this, TypeAlignment)
1540 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1541 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001542 } else {
1543 QualType CanonEltTy = getCanonicalType(EltTy);
1544 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001545 New = new (*this, TypeAlignment)
1546 DependentSizedArrayType(*this, EltTy, QualType(),
1547 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001548
1549 if (NumElts)
1550 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001551 } else {
1552 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1553 ASM, EltTypeQuals,
1554 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001555 New = new (*this, TypeAlignment)
1556 DependentSizedArrayType(*this, EltTy, Canon,
1557 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001558 }
1559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Douglas Gregor898574e2008-12-05 23:32:09 +00001561 Types.push_back(New);
1562 return QualType(New, 0);
1563}
1564
Eli Friedmanc5773c42008-02-15 18:16:39 +00001565QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1566 ArrayType::ArraySizeModifier ASM,
1567 unsigned EltTypeQuals) {
1568 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001569 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001570
1571 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001572 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001573 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1574 return QualType(ATP, 0);
1575
1576 // If the element type isn't canonical, this won't be a canonical type
1577 // either, so fill in the canonical type field.
1578 QualType Canonical;
1579
John McCall467b27b2009-10-22 20:10:53 +00001580 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001581 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001582 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001583
1584 // Get the new insert position for the node we care about.
1585 IncompleteArrayType *NewIP =
1586 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001587 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001588 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001589
John McCall6b304a02009-09-24 23:30:46 +00001590 IncompleteArrayType *New = new (*this, TypeAlignment)
1591 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001592
1593 IncompleteArrayTypes.InsertNode(New, InsertPos);
1594 Types.push_back(New);
1595 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001596}
1597
Steve Naroff73322922007-07-18 18:00:27 +00001598/// getVectorType - Return the unique reference to a vector type of
1599/// the specified element type and size. VectorType must be a built-in type.
1600QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattnerf52ab252008-04-06 22:59:24 +00001603 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001604 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 // Check if we've already instantiated a vector of this type.
1607 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001608 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 void *InsertPos = 0;
1610 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1611 return QualType(VTP, 0);
1612
1613 // If the element type isn't canonical, this won't be a canonical type either,
1614 // so fill in the canonical type field.
1615 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001616 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001617 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 // Get the new insert position for the node we care about.
1620 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001621 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 }
John McCall6b304a02009-09-24 23:30:46 +00001623 VectorType *New = new (*this, TypeAlignment)
1624 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 VectorTypes.InsertNode(New, InsertPos);
1626 Types.push_back(New);
1627 return QualType(New, 0);
1628}
1629
Nate Begeman213541a2008-04-18 23:10:10 +00001630/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001631/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001632QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001633 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Chris Lattnerf52ab252008-04-06 22:59:24 +00001635 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001636 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Steve Naroff73322922007-07-18 18:00:27 +00001638 // Check if we've already instantiated a vector of this type.
1639 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001640 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001641 void *InsertPos = 0;
1642 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1643 return QualType(VTP, 0);
1644
1645 // If the element type isn't canonical, this won't be a canonical type either,
1646 // so fill in the canonical type field.
1647 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001648 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001649 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Steve Naroff73322922007-07-18 18:00:27 +00001651 // Get the new insert position for the node we care about.
1652 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001653 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001654 }
John McCall6b304a02009-09-24 23:30:46 +00001655 ExtVectorType *New = new (*this, TypeAlignment)
1656 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001657 VectorTypes.InsertNode(New, InsertPos);
1658 Types.push_back(New);
1659 return QualType(New, 0);
1660}
1661
Mike Stump1eb44332009-09-09 15:08:12 +00001662QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001663 Expr *SizeExpr,
1664 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001665 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001666 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001667 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001669 void *InsertPos = 0;
1670 DependentSizedExtVectorType *Canon
1671 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1672 DependentSizedExtVectorType *New;
1673 if (Canon) {
1674 // We already have a canonical version of this array type; use it as
1675 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001676 New = new (*this, TypeAlignment)
1677 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1678 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001679 } else {
1680 QualType CanonVecTy = getCanonicalType(vecType);
1681 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001682 New = new (*this, TypeAlignment)
1683 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1684 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001685 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1686 } else {
1687 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1688 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001689 New = new (*this, TypeAlignment)
1690 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001691 }
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001694 Types.push_back(New);
1695 return QualType(New, 0);
1696}
1697
Douglas Gregor72564e72009-02-26 23:50:07 +00001698/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001699///
Mike Stump24556362009-07-25 21:26:53 +00001700QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 // Unique functions, to guarantee there is only one function of a particular
1702 // structure.
1703 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001704 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001707 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001708 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001712 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001713 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001716 FunctionNoProtoType *NewIP =
1717 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001718 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720
John McCall6b304a02009-09-24 23:30:46 +00001721 FunctionNoProtoType *New = new (*this, TypeAlignment)
1722 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001724 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 return QualType(New, 0);
1726}
1727
1728/// getFunctionType - Return a normal function type with a typed argument
1729/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001730QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001731 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001732 unsigned TypeQuals, bool hasExceptionSpec,
1733 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001734 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 // Unique functions, to guarantee there is only one function of a particular
1736 // structure.
1737 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001738 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001739 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001740 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001741
1742 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001743 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001744 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001746
1747 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001748 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001750 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 isCanonical = false;
1752
1753 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001754 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 QualType Canonical;
1756 if (!isCanonical) {
1757 llvm::SmallVector<QualType, 16> CanonicalArgs;
1758 CanonicalArgs.reserve(NumArgs);
1759 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001760 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001761
Chris Lattnerf52ab252008-04-06 22:59:24 +00001762 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001763 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001764 isVariadic, TypeQuals, false,
1765 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001766
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001768 FunctionProtoType *NewIP =
1769 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001770 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001772
Douglas Gregor72564e72009-02-26 23:50:07 +00001773 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001774 // for two variable size arrays (for parameter and exception types) at the
1775 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001776 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001777 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1778 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001779 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001780 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001781 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001782 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001784 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 return QualType(FTP, 0);
1786}
1787
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001788/// getTypeDeclType - Return the unique reference to the type for the
1789/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001790QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001791 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001792 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001794 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001795 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001796 else if (isa<TemplateTypeParmDecl>(Decl)) {
1797 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001798 } else if (ObjCInterfaceDecl *ObjCInterface
1799 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001800 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001801
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001802 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001803 if (PrevDecl)
1804 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001805 else
John McCall6b304a02009-09-24 23:30:46 +00001806 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001807 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001808 if (PrevDecl)
1809 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001810 else
John McCall6b304a02009-09-24 23:30:46 +00001811 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001812 } else if (UnresolvedUsingTypenameDecl *Using =
1813 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1814 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001815 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001816 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001817
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001818 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001819 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001820}
1821
Reid Spencer5f016e22007-07-11 17:01:13 +00001822/// getTypedefType - Return the unique reference to the type for the
1823/// specified typename decl.
1824QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1825 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Chris Lattnerf52ab252008-04-06 22:59:24 +00001827 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001828 Decl->TypeForDecl = new(*this, TypeAlignment)
1829 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 Types.push_back(Decl->TypeForDecl);
1831 return QualType(Decl->TypeForDecl, 0);
1832}
1833
John McCall49a832b2009-10-18 09:09:24 +00001834/// \brief Retrieve a substitution-result type.
1835QualType
1836ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1837 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001838 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001839 && "replacement types must always be canonical");
1840
1841 llvm::FoldingSetNodeID ID;
1842 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1843 void *InsertPos = 0;
1844 SubstTemplateTypeParmType *SubstParm
1845 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1846
1847 if (!SubstParm) {
1848 SubstParm = new (*this, TypeAlignment)
1849 SubstTemplateTypeParmType(Parm, Replacement);
1850 Types.push_back(SubstParm);
1851 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1852 }
1853
1854 return QualType(SubstParm, 0);
1855}
1856
Douglas Gregorfab9d672009-02-05 23:33:38 +00001857/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001858/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001859/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001860QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001861 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001862 IdentifierInfo *Name) {
1863 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001864 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001865 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001866 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001867 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1868
1869 if (TypeParm)
1870 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001872 if (Name) {
1873 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001874 TypeParm = new (*this, TypeAlignment)
1875 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001876 } else
John McCall6b304a02009-09-24 23:30:46 +00001877 TypeParm = new (*this, TypeAlignment)
1878 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001879
1880 Types.push_back(TypeParm);
1881 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1882
1883 return QualType(TypeParm, 0);
1884}
1885
Mike Stump1eb44332009-09-09 15:08:12 +00001886QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001887ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001888 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001889 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001890 unsigned NumArgs = Args.size();
1891
John McCall833ca992009-10-29 08:12:44 +00001892 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1893 ArgVec.reserve(NumArgs);
1894 for (unsigned i = 0; i != NumArgs; ++i)
1895 ArgVec.push_back(Args[i].getArgument());
1896
1897 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1898}
1899
1900QualType
1901ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001902 const TemplateArgument *Args,
1903 unsigned NumArgs,
1904 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001905 if (!Canon.isNull())
1906 Canon = getCanonicalType(Canon);
1907 else {
1908 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001909 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1910 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1911 CanonArgs.reserve(NumArgs);
1912 for (unsigned I = 0; I != NumArgs; ++I)
1913 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1914
1915 // Determine whether this canonical template specialization type already
1916 // exists.
1917 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001918 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001919 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001920
1921 void *InsertPos = 0;
1922 TemplateSpecializationType *Spec
1923 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Douglas Gregor1275ae02009-07-28 23:00:59 +00001925 if (!Spec) {
1926 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001927 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001928 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001929 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001930 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001931 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001932 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001933 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001934 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001935 }
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Douglas Gregorb88e8882009-07-30 17:40:51 +00001937 if (Canon.isNull())
1938 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001939 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001940 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001941 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001942
Douglas Gregor1275ae02009-07-28 23:00:59 +00001943 // Allocate the (non-canonical) template specialization type, but don't
1944 // try to unique it: these types typically have location information that
1945 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001946 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001947 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001948 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001949 TemplateSpecializationType *Spec
1950 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001951 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Douglas Gregor55f6b142009-02-09 18:46:07 +00001953 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001954 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001955}
1956
Mike Stump1eb44332009-09-09 15:08:12 +00001957QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001958ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001959 QualType NamedType) {
1960 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001961 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001962
1963 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001964 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001965 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1966 if (T)
1967 return QualType(T, 0);
1968
Mike Stump1eb44332009-09-09 15:08:12 +00001969 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001970 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001971 Types.push_back(T);
1972 QualifiedNameTypes.InsertNode(T, InsertPos);
1973 return QualType(T, 0);
1974}
1975
Mike Stump1eb44332009-09-09 15:08:12 +00001976QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001977 const IdentifierInfo *Name,
1978 QualType Canon) {
1979 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1980
1981 if (Canon.isNull()) {
1982 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1983 if (CanonNNS != NNS)
1984 Canon = getTypenameType(CanonNNS, Name);
1985 }
1986
1987 llvm::FoldingSetNodeID ID;
1988 TypenameType::Profile(ID, NNS, Name);
1989
1990 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001991 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001992 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1993 if (T)
1994 return QualType(T, 0);
1995
1996 T = new (*this) TypenameType(NNS, Name, Canon);
1997 Types.push_back(T);
1998 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001999 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002000}
2001
Mike Stump1eb44332009-09-09 15:08:12 +00002002QualType
2003ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002004 const TemplateSpecializationType *TemplateId,
2005 QualType Canon) {
2006 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2007
2008 if (Canon.isNull()) {
2009 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2010 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2011 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2012 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002013 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002014 assert(CanonTemplateId &&
2015 "Canonical type must also be a template specialization type");
2016 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2017 }
2018 }
2019
2020 llvm::FoldingSetNodeID ID;
2021 TypenameType::Profile(ID, NNS, TemplateId);
2022
2023 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002024 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00002025 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2026 if (T)
2027 return QualType(T, 0);
2028
2029 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2030 Types.push_back(T);
2031 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002032 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002033}
2034
John McCall7da24312009-09-05 00:15:47 +00002035QualType
2036ASTContext::getElaboratedType(QualType UnderlyingType,
2037 ElaboratedType::TagKind Tag) {
2038 llvm::FoldingSetNodeID ID;
2039 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002040
John McCall7da24312009-09-05 00:15:47 +00002041 void *InsertPos = 0;
2042 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2043 if (T)
2044 return QualType(T, 0);
2045
2046 QualType Canon = getCanonicalType(UnderlyingType);
2047
2048 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2049 Types.push_back(T);
2050 ElaboratedTypes.InsertNode(T, InsertPos);
2051 return QualType(T, 0);
2052}
2053
Chris Lattner88cb27a2008-04-07 04:56:42 +00002054/// CmpProtocolNames - Comparison predicate for sorting protocols
2055/// alphabetically.
2056static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2057 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002058 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002059}
2060
John McCall54e14c42009-10-22 22:37:11 +00002061static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2062 unsigned NumProtocols) {
2063 if (NumProtocols == 0) return true;
2064
2065 for (unsigned i = 1; i != NumProtocols; ++i)
2066 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2067 return false;
2068 return true;
2069}
2070
2071static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002072 unsigned &NumProtocols) {
2073 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Chris Lattner88cb27a2008-04-07 04:56:42 +00002075 // Sort protocols, keyed by name.
2076 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2077
2078 // Remove duplicates.
2079 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2080 NumProtocols = ProtocolsEnd-Protocols;
2081}
2082
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002083/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2084/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002085QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002086 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002087 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002088 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002089 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002090
2091 void *InsertPos = 0;
2092 if (ObjCObjectPointerType *QT =
2093 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2094 return QualType(QT, 0);
2095
John McCall54e14c42009-10-22 22:37:11 +00002096 // Sort the protocol list alphabetically to canonicalize it.
2097 QualType Canonical;
2098 if (!InterfaceT.isCanonical() ||
2099 !areSortedAndUniqued(Protocols, NumProtocols)) {
2100 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2101 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2102 unsigned UniqueCount = NumProtocols;
2103
2104 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2105 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2106
2107 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2108 &Sorted[0], UniqueCount);
2109 } else {
2110 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2111 Protocols, NumProtocols);
2112 }
2113
2114 // Regenerate InsertPos.
2115 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2116 }
2117
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002118 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002119 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002120 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002122 Types.push_back(QType);
2123 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2124 return QualType(QType, 0);
2125}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002126
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002127/// getObjCInterfaceType - Return the unique reference to the type for the
2128/// specified ObjC interface decl. The list of protocols is optional.
2129QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002130 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002131 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002132 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002134 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002135 if (ObjCInterfaceType *QT =
2136 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002137 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002138
John McCall54e14c42009-10-22 22:37:11 +00002139 // Sort the protocol list alphabetically to canonicalize it.
2140 QualType Canonical;
2141 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2142 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2143 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2144
2145 unsigned UniqueCount = NumProtocols;
2146 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2147
2148 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2149
2150 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2151 }
2152
John McCall6b304a02009-09-24 23:30:46 +00002153 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002154 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002155 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002156
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002157 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002158 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002159 return QualType(QType, 0);
2160}
2161
Douglas Gregor72564e72009-02-26 23:50:07 +00002162/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2163/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002164/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002165/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002166/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002167QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002168 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002169 if (tofExpr->isTypeDependent()) {
2170 llvm::FoldingSetNodeID ID;
2171 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregorb1975722009-07-30 23:18:24 +00002173 void *InsertPos = 0;
2174 DependentTypeOfExprType *Canon
2175 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2176 if (Canon) {
2177 // We already have a "canonical" version of an identical, dependent
2178 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002179 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002180 QualType((TypeOfExprType*)Canon, 0));
2181 }
2182 else {
2183 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002184 Canon
2185 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002186 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2187 toe = Canon;
2188 }
2189 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002190 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002191 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002192 }
Steve Naroff9752f252007-08-01 18:02:17 +00002193 Types.push_back(toe);
2194 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002195}
2196
Steve Naroff9752f252007-08-01 18:02:17 +00002197/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2198/// TypeOfType AST's. The only motivation to unique these nodes would be
2199/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002200/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002201/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002202QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002203 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002204 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002205 Types.push_back(tot);
2206 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002207}
2208
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002209/// getDecltypeForExpr - Given an expr, will return the decltype for that
2210/// expression, according to the rules in C++0x [dcl.type.simple]p4
2211static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002212 if (e->isTypeDependent())
2213 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002215 // If e is an id expression or a class member access, decltype(e) is defined
2216 // as the type of the entity named by e.
2217 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2218 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2219 return VD->getType();
2220 }
2221 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2222 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2223 return FD->getType();
2224 }
2225 // If e is a function call or an invocation of an overloaded operator,
2226 // (parentheses around e are ignored), decltype(e) is defined as the
2227 // return type of that function.
2228 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2229 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002231 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002232
2233 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002234 // defined as T&, otherwise decltype(e) is defined as T.
2235 if (e->isLvalue(Context) == Expr::LV_Valid)
2236 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002238 return T;
2239}
2240
Anders Carlsson395b4752009-06-24 19:06:50 +00002241/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2242/// DecltypeType AST's. The only motivation to unique these nodes would be
2243/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002244/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002245/// on canonical type's (which are always unique).
2246QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002247 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002248 if (e->isTypeDependent()) {
2249 llvm::FoldingSetNodeID ID;
2250 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002252 void *InsertPos = 0;
2253 DependentDecltypeType *Canon
2254 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2255 if (Canon) {
2256 // We already have a "canonical" version of an equivalent, dependent
2257 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002258 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002259 QualType((DecltypeType*)Canon, 0));
2260 }
2261 else {
2262 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002263 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002264 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2265 dt = Canon;
2266 }
2267 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002268 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002269 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002270 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002271 Types.push_back(dt);
2272 return QualType(dt, 0);
2273}
2274
Reid Spencer5f016e22007-07-11 17:01:13 +00002275/// getTagDeclType - Return the unique reference to the type for the
2276/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002277QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002278 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002279 // FIXME: What is the design on getTagDeclType when it requires casting
2280 // away const? mutable?
2281 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002282}
2283
Mike Stump1eb44332009-09-09 15:08:12 +00002284/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2285/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2286/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002287CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002288 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002289}
2290
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002291/// getSignedWCharType - Return the type of "signed wchar_t".
2292/// Used when in C++, as a GCC extension.
2293QualType ASTContext::getSignedWCharType() const {
2294 // FIXME: derive from "Target" ?
2295 return WCharTy;
2296}
2297
2298/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2299/// Used when in C++, as a GCC extension.
2300QualType ASTContext::getUnsignedWCharType() const {
2301 // FIXME: derive from "Target" ?
2302 return UnsignedIntTy;
2303}
2304
Chris Lattner8b9023b2007-07-13 03:05:23 +00002305/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2306/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2307QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002308 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002309}
2310
Chris Lattnere6327742008-04-02 05:18:44 +00002311//===----------------------------------------------------------------------===//
2312// Type Operators
2313//===----------------------------------------------------------------------===//
2314
John McCall54e14c42009-10-22 22:37:11 +00002315CanQualType ASTContext::getCanonicalParamType(QualType T) {
2316 // Push qualifiers into arrays, and then discard any remaining
2317 // qualifiers.
2318 T = getCanonicalType(T);
2319 const Type *Ty = T.getTypePtr();
2320
2321 QualType Result;
2322 if (isa<ArrayType>(Ty)) {
2323 Result = getArrayDecayedType(QualType(Ty,0));
2324 } else if (isa<FunctionType>(Ty)) {
2325 Result = getPointerType(QualType(Ty, 0));
2326 } else {
2327 Result = QualType(Ty, 0);
2328 }
2329
2330 return CanQualType::CreateUnsafe(Result);
2331}
2332
Chris Lattner77c96472008-04-06 22:41:35 +00002333/// getCanonicalType - Return the canonical (structural) type corresponding to
2334/// the specified potentially non-canonical type. The non-canonical version
2335/// of a type may have many "decorated" versions of types. Decorators can
2336/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2337/// to be free of any of these, allowing two canonical types to be compared
2338/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002339CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002340 QualifierCollector Quals;
2341 const Type *Ptr = Quals.strip(T);
2342 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002343
John McCall0953e762009-09-24 19:53:00 +00002344 // The canonical internal type will be the canonical type *except*
2345 // that we push type qualifiers down through array types.
2346
2347 // If there are no new qualifiers to push down, stop here.
2348 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002349 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002350
John McCall0953e762009-09-24 19:53:00 +00002351 // If the type qualifiers are on an array type, get the canonical
2352 // type of the array with the qualifiers applied to the element
2353 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002354 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2355 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002356 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002358 // Get the canonical version of the element with the extra qualifiers on it.
2359 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002360 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002361 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002363 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002364 return CanQualType::CreateUnsafe(
2365 getConstantArrayType(NewEltTy, CAT->getSize(),
2366 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002367 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002368 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002369 return CanQualType::CreateUnsafe(
2370 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002371 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor898574e2008-12-05 23:32:09 +00002373 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002374 return CanQualType::CreateUnsafe(
2375 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002376 DSAT->getSizeExpr() ?
2377 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002378 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002379 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002380 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002381
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002382 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002383 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002384 VAT->getSizeExpr() ?
2385 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002386 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002387 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002388 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002389}
2390
John McCall80ad16f2009-11-24 18:42:40 +00002391DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2392 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2393 return TD->getDeclName();
2394
2395 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2396 if (DTN->isIdentifier()) {
2397 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2398 } else {
2399 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2400 }
2401 }
2402
John McCall0bd6feb2009-12-02 08:04:21 +00002403 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2404 assert(Storage);
2405 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002406}
2407
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002408TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2409 // If this template name refers to a template, the canonical
2410 // template name merely stores the template itself.
2411 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002412 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002413
John McCall0bd6feb2009-12-02 08:04:21 +00002414 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002415
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002416 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2417 assert(DTN && "Non-dependent template names must refer to template decls.");
2418 return DTN->CanonicalTemplateName;
2419}
2420
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002421bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2422 X = getCanonicalTemplateName(X);
2423 Y = getCanonicalTemplateName(Y);
2424 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2425}
2426
Mike Stump1eb44332009-09-09 15:08:12 +00002427TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002428ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2429 switch (Arg.getKind()) {
2430 case TemplateArgument::Null:
2431 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002432
Douglas Gregor1275ae02009-07-28 23:00:59 +00002433 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002434 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Douglas Gregor1275ae02009-07-28 23:00:59 +00002436 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002437 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Douglas Gregor788cd062009-11-11 01:00:40 +00002439 case TemplateArgument::Template:
2440 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2441
Douglas Gregor1275ae02009-07-28 23:00:59 +00002442 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002443 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002444 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Douglas Gregor1275ae02009-07-28 23:00:59 +00002446 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002447 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregor1275ae02009-07-28 23:00:59 +00002449 case TemplateArgument::Pack: {
2450 // FIXME: Allocate in ASTContext
2451 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2452 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002453 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002454 AEnd = Arg.pack_end();
2455 A != AEnd; (void)++A, ++Idx)
2456 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Douglas Gregor1275ae02009-07-28 23:00:59 +00002458 TemplateArgument Result;
2459 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2460 return Result;
2461 }
2462 }
2463
2464 // Silence GCC warning
2465 assert(false && "Unhandled template argument kind");
2466 return TemplateArgument();
2467}
2468
Douglas Gregord57959a2009-03-27 23:10:48 +00002469NestedNameSpecifier *
2470ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002471 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002472 return 0;
2473
2474 switch (NNS->getKind()) {
2475 case NestedNameSpecifier::Identifier:
2476 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002477 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002478 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2479 NNS->getAsIdentifier());
2480
2481 case NestedNameSpecifier::Namespace:
2482 // A namespace is canonical; build a nested-name-specifier with
2483 // this namespace and no prefix.
2484 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2485
2486 case NestedNameSpecifier::TypeSpec:
2487 case NestedNameSpecifier::TypeSpecWithTemplate: {
2488 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002489 return NestedNameSpecifier::Create(*this, 0,
2490 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002491 T.getTypePtr());
2492 }
2493
2494 case NestedNameSpecifier::Global:
2495 // The global specifier is canonical and unique.
2496 return NNS;
2497 }
2498
2499 // Required to silence a GCC warning
2500 return 0;
2501}
2502
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002503
2504const ArrayType *ASTContext::getAsArrayType(QualType T) {
2505 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002506 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002507 // Handle the common positive case fast.
2508 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2509 return AT;
2510 }
Mike Stump1eb44332009-09-09 15:08:12 +00002511
John McCall0953e762009-09-24 19:53:00 +00002512 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002513 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002514 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002515 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002516
John McCall0953e762009-09-24 19:53:00 +00002517 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002518 // implements C99 6.7.3p8: "If the specification of an array type includes
2519 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521 // If we get here, we either have type qualifiers on the type, or we have
2522 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002523 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002524
John McCall0953e762009-09-24 19:53:00 +00002525 QualifierCollector Qs;
2526 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002528 // If we have a simple case, just return now.
2529 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002530 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002531 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002533 // Otherwise, we have an array and we have qualifiers on it. Push the
2534 // qualifiers into the array element type and return a new array type.
2535 // Get the canonical version of the element with the extra qualifiers on it.
2536 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002537 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002539 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2540 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2541 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002542 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002543 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2544 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2545 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002546 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002547
Mike Stump1eb44332009-09-09 15:08:12 +00002548 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002549 = dyn_cast<DependentSizedArrayType>(ATy))
2550 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002551 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002552 DSAT->getSizeExpr() ?
2553 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002554 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002555 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002556 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002557
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002558 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002559 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002560 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002561 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002562 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002563 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002564 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002565}
2566
2567
Chris Lattnere6327742008-04-02 05:18:44 +00002568/// getArrayDecayedType - Return the properly qualified result of decaying the
2569/// specified array type to a pointer. This operation is non-trivial when
2570/// handling typedefs etc. The canonical type of "T" must be an array type,
2571/// this returns a pointer to a properly qualified element of the array.
2572///
2573/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2574QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002575 // Get the element type with 'getAsArrayType' so that we don't lose any
2576 // typedefs in the element type of the array. This also handles propagation
2577 // of type qualifiers from the array type into the element type if present
2578 // (C99 6.7.3p8).
2579 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2580 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002582 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002583
2584 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002585 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002586}
2587
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002588QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002589 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002590 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002591 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002592 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2593 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002594 } else {
John McCall0953e762009-09-24 19:53:00 +00002595 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002596 }
2597 }
2598}
2599
Anders Carlssonfbbce492009-09-25 01:23:32 +00002600QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2601 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Anders Carlssonfbbce492009-09-25 01:23:32 +00002603 if (const ArrayType *AT = getAsArrayType(ElemTy))
2604 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Anders Carlsson6183a992008-12-21 03:44:36 +00002606 return ElemTy;
2607}
2608
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002609/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002610uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002611ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2612 uint64_t ElementCount = 1;
2613 do {
2614 ElementCount *= CA->getSize().getZExtValue();
2615 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2616 } while (CA);
2617 return ElementCount;
2618}
2619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620/// getFloatingRank - Return a relative rank for floating point types.
2621/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002622static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002623 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002625
John McCall183700f2009-09-21 23:43:11 +00002626 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2627 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002628 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 case BuiltinType::Float: return FloatRank;
2630 case BuiltinType::Double: return DoubleRank;
2631 case BuiltinType::LongDouble: return LongDoubleRank;
2632 }
2633}
2634
Mike Stump1eb44332009-09-09 15:08:12 +00002635/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2636/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002637/// 'typeDomain' is a real floating point or complex type.
2638/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002639QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2640 QualType Domain) const {
2641 FloatingRank EltRank = getFloatingRank(Size);
2642 if (Domain->isComplexType()) {
2643 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002644 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002645 case FloatRank: return FloatComplexTy;
2646 case DoubleRank: return DoubleComplexTy;
2647 case LongDoubleRank: return LongDoubleComplexTy;
2648 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 }
Chris Lattner1361b112008-04-06 23:58:54 +00002650
2651 assert(Domain->isRealFloatingType() && "Unknown domain!");
2652 switch (EltRank) {
2653 default: assert(0 && "getFloatingRank(): illegal value for rank");
2654 case FloatRank: return FloatTy;
2655 case DoubleRank: return DoubleTy;
2656 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002657 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002658}
2659
Chris Lattner7cfeb082008-04-06 23:55:33 +00002660/// getFloatingTypeOrder - Compare the rank of the two specified floating
2661/// point types, ignoring the domain of the type (i.e. 'double' ==
2662/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002663/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002664int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2665 FloatingRank LHSR = getFloatingRank(LHS);
2666 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Chris Lattnera75cea32008-04-06 23:38:49 +00002668 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002669 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002670 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002671 return 1;
2672 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002673}
2674
Chris Lattnerf52ab252008-04-06 22:59:24 +00002675/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2676/// routine will assert if passed a built-in type that isn't an integer or enum,
2677/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002678unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002679 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002680 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002681 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002682
Eli Friedmana3426752009-07-05 23:44:27 +00002683 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2684 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2685
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002686 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2687 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2688
2689 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2690 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2691
Eli Friedmanf98aba32009-02-13 02:31:07 +00002692 // There are two things which impact the integer rank: the width, and
2693 // the ordering of builtins. The builtin ordering is encoded in the
2694 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002695 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002696 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002697
Chris Lattnerf52ab252008-04-06 22:59:24 +00002698 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002699 default: assert(0 && "getIntegerRank(): not a built-in integer");
2700 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002701 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002702 case BuiltinType::Char_S:
2703 case BuiltinType::Char_U:
2704 case BuiltinType::SChar:
2705 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002706 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002707 case BuiltinType::Short:
2708 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002709 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002710 case BuiltinType::Int:
2711 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002712 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002713 case BuiltinType::Long:
2714 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002715 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002716 case BuiltinType::LongLong:
2717 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002718 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002719 case BuiltinType::Int128:
2720 case BuiltinType::UInt128:
2721 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002722 }
2723}
2724
Eli Friedman04e83572009-08-20 04:21:42 +00002725/// \brief Whether this is a promotable bitfield reference according
2726/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2727///
2728/// \returns the type this bit-field will promote to, or NULL if no
2729/// promotion occurs.
2730QualType ASTContext::isPromotableBitField(Expr *E) {
2731 FieldDecl *Field = E->getBitField();
2732 if (!Field)
2733 return QualType();
2734
2735 QualType FT = Field->getType();
2736
2737 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2738 uint64_t BitWidth = BitWidthAP.getZExtValue();
2739 uint64_t IntSize = getTypeSize(IntTy);
2740 // GCC extension compatibility: if the bit-field size is less than or equal
2741 // to the size of int, it gets promoted no matter what its type is.
2742 // For instance, unsigned long bf : 4 gets promoted to signed int.
2743 if (BitWidth < IntSize)
2744 return IntTy;
2745
2746 if (BitWidth == IntSize)
2747 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2748
2749 // Types bigger than int are not subject to promotions, and therefore act
2750 // like the base type.
2751 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2752 // is ridiculous.
2753 return QualType();
2754}
2755
Eli Friedmana95d7572009-08-19 07:44:53 +00002756/// getPromotedIntegerType - Returns the type that Promotable will
2757/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2758/// integer type.
2759QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2760 assert(!Promotable.isNull());
2761 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002762 if (const EnumType *ET = Promotable->getAs<EnumType>())
2763 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002764 if (Promotable->isSignedIntegerType())
2765 return IntTy;
2766 uint64_t PromotableSize = getTypeSize(Promotable);
2767 uint64_t IntSize = getTypeSize(IntTy);
2768 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2769 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2770}
2771
Mike Stump1eb44332009-09-09 15:08:12 +00002772/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002773/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002774/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002775int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002776 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2777 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002778 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Chris Lattnerf52ab252008-04-06 22:59:24 +00002780 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2781 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Chris Lattner7cfeb082008-04-06 23:55:33 +00002783 unsigned LHSRank = getIntegerRank(LHSC);
2784 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Chris Lattner7cfeb082008-04-06 23:55:33 +00002786 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2787 if (LHSRank == RHSRank) return 0;
2788 return LHSRank > RHSRank ? 1 : -1;
2789 }
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Chris Lattner7cfeb082008-04-06 23:55:33 +00002791 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2792 if (LHSUnsigned) {
2793 // If the unsigned [LHS] type is larger, return it.
2794 if (LHSRank >= RHSRank)
2795 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002796
Chris Lattner7cfeb082008-04-06 23:55:33 +00002797 // If the signed type can represent all values of the unsigned type, it
2798 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002799 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002800 return -1;
2801 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002802
Chris Lattner7cfeb082008-04-06 23:55:33 +00002803 // If the unsigned [RHS] type is larger, return it.
2804 if (RHSRank >= LHSRank)
2805 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Chris Lattner7cfeb082008-04-06 23:55:33 +00002807 // If the signed type can represent all values of the unsigned type, it
2808 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002809 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002810 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002812
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002813static RecordDecl *
2814CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2815 SourceLocation L, IdentifierInfo *Id) {
2816 if (Ctx.getLangOptions().CPlusPlus)
2817 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2818 else
2819 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2820}
2821
Mike Stump1eb44332009-09-09 15:08:12 +00002822// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002823QualType ASTContext::getCFConstantStringType() {
2824 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002825 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002826 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2827 &Idents.get("NSConstantString"));
2828
Anders Carlssonf06273f2007-11-19 00:25:30 +00002829 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Anders Carlsson71993dd2007-08-17 05:31:46 +00002831 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002832 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002833 // int flags;
2834 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002835 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002836 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002837 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002838 FieldTypes[3] = LongTy;
2839
Anders Carlsson71993dd2007-08-17 05:31:46 +00002840 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002841 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002842 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002843 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002844 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002845 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002846 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002847 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002848 }
2849
2850 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002851 }
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Anders Carlsson71993dd2007-08-17 05:31:46 +00002853 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002854}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002855
Douglas Gregor319ac892009-04-23 22:29:11 +00002856void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002857 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002858 assert(Rec && "Invalid CFConstantStringType");
2859 CFConstantStringTypeDecl = Rec->getDecl();
2860}
2861
Mike Stump1eb44332009-09-09 15:08:12 +00002862QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002863 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002864 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002865 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2866 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002868 QualType FieldTypes[] = {
2869 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002870 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002871 getPointerType(UnsignedLongTy),
2872 getConstantArrayType(UnsignedLongTy,
2873 llvm::APInt(32, 5), ArrayType::Normal, 0)
2874 };
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Douglas Gregor44b43212008-12-11 16:49:14 +00002876 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002877 FieldDecl *Field = FieldDecl::Create(*this,
2878 ObjCFastEnumerationStateTypeDecl,
2879 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002880 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002881 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002882 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002883 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002884 }
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Douglas Gregor44b43212008-12-11 16:49:14 +00002886 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002887 }
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002889 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2890}
2891
Mike Stumpadaaad32009-10-20 02:12:22 +00002892QualType ASTContext::getBlockDescriptorType() {
2893 if (BlockDescriptorType)
2894 return getTagDeclType(BlockDescriptorType);
2895
2896 RecordDecl *T;
2897 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002898 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2899 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002900
2901 QualType FieldTypes[] = {
2902 UnsignedLongTy,
2903 UnsignedLongTy,
2904 };
2905
2906 const char *FieldNames[] = {
2907 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002908 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002909 };
2910
2911 for (size_t i = 0; i < 2; ++i) {
2912 FieldDecl *Field = FieldDecl::Create(*this,
2913 T,
2914 SourceLocation(),
2915 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002916 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002917 /*BitWidth=*/0,
2918 /*Mutable=*/false);
2919 T->addDecl(Field);
2920 }
2921
2922 T->completeDefinition(*this);
2923
2924 BlockDescriptorType = T;
2925
2926 return getTagDeclType(BlockDescriptorType);
2927}
2928
2929void ASTContext::setBlockDescriptorType(QualType T) {
2930 const RecordType *Rec = T->getAs<RecordType>();
2931 assert(Rec && "Invalid BlockDescriptorType");
2932 BlockDescriptorType = Rec->getDecl();
2933}
2934
Mike Stump083c25e2009-10-22 00:49:09 +00002935QualType ASTContext::getBlockDescriptorExtendedType() {
2936 if (BlockDescriptorExtendedType)
2937 return getTagDeclType(BlockDescriptorExtendedType);
2938
2939 RecordDecl *T;
2940 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002941 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2942 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002943
2944 QualType FieldTypes[] = {
2945 UnsignedLongTy,
2946 UnsignedLongTy,
2947 getPointerType(VoidPtrTy),
2948 getPointerType(VoidPtrTy)
2949 };
2950
2951 const char *FieldNames[] = {
2952 "reserved",
2953 "Size",
2954 "CopyFuncPtr",
2955 "DestroyFuncPtr"
2956 };
2957
2958 for (size_t i = 0; i < 4; ++i) {
2959 FieldDecl *Field = FieldDecl::Create(*this,
2960 T,
2961 SourceLocation(),
2962 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002963 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00002964 /*BitWidth=*/0,
2965 /*Mutable=*/false);
2966 T->addDecl(Field);
2967 }
2968
2969 T->completeDefinition(*this);
2970
2971 BlockDescriptorExtendedType = T;
2972
2973 return getTagDeclType(BlockDescriptorExtendedType);
2974}
2975
2976void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2977 const RecordType *Rec = T->getAs<RecordType>();
2978 assert(Rec && "Invalid BlockDescriptorType");
2979 BlockDescriptorExtendedType = Rec->getDecl();
2980}
2981
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002982bool ASTContext::BlockRequiresCopying(QualType Ty) {
2983 if (Ty->isBlockPointerType())
2984 return true;
2985 if (isObjCNSObjectType(Ty))
2986 return true;
2987 if (Ty->isObjCObjectPointerType())
2988 return true;
2989 return false;
2990}
2991
2992QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2993 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002994 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002995 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002996 // unsigned int __flags;
2997 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002998 // void *__copy_helper; // as needed
2999 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003000 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003001 // } *
3002
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003003 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3004
3005 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003006 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003007 llvm::SmallString<36> Name;
3008 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3009 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003010 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003011 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3012 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003013 T->startDefinition();
3014 QualType Int32Ty = IntTy;
3015 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3016 QualType FieldTypes[] = {
3017 getPointerType(VoidPtrTy),
3018 getPointerType(getTagDeclType(T)),
3019 Int32Ty,
3020 Int32Ty,
3021 getPointerType(VoidPtrTy),
3022 getPointerType(VoidPtrTy),
3023 Ty
3024 };
3025
3026 const char *FieldNames[] = {
3027 "__isa",
3028 "__forwarding",
3029 "__flags",
3030 "__size",
3031 "__copy_helper",
3032 "__destroy_helper",
3033 DeclName,
3034 };
3035
3036 for (size_t i = 0; i < 7; ++i) {
3037 if (!HasCopyAndDispose && i >=4 && i <= 5)
3038 continue;
3039 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3040 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003041 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003042 /*BitWidth=*/0, /*Mutable=*/false);
3043 T->addDecl(Field);
3044 }
3045
3046 T->completeDefinition(*this);
3047
3048 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003049}
3050
3051
3052QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003053 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003054 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003055 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003056 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003057 llvm::SmallString<36> Name;
3058 llvm::raw_svector_ostream(Name) << "__block_literal_"
3059 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003060 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003061 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3062 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003063 QualType FieldTypes[] = {
3064 getPointerType(VoidPtrTy),
3065 IntTy,
3066 IntTy,
3067 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003068 (BlockHasCopyDispose ?
3069 getPointerType(getBlockDescriptorExtendedType()) :
3070 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003071 };
3072
3073 const char *FieldNames[] = {
3074 "__isa",
3075 "__flags",
3076 "__reserved",
3077 "__FuncPtr",
3078 "__descriptor"
3079 };
3080
3081 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003082 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003083 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003084 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003085 /*BitWidth=*/0, /*Mutable=*/false);
3086 T->addDecl(Field);
3087 }
3088
3089 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3090 const Expr *E = BlockDeclRefDecls[i];
3091 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3092 clang::IdentifierInfo *Name = 0;
3093 if (BDRE) {
3094 const ValueDecl *D = BDRE->getDecl();
3095 Name = &Idents.get(D->getName());
3096 }
3097 QualType FieldType = E->getType();
3098
3099 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003100 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3101 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003102
3103 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003104 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003105 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003106 T->addDecl(Field);
3107 }
3108
3109 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003110
3111 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003112}
3113
Douglas Gregor319ac892009-04-23 22:29:11 +00003114void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003115 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003116 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3117 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3118}
3119
Anders Carlssone8c49532007-10-29 06:33:42 +00003120// This returns true if a type has been typedefed to BOOL:
3121// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003122static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003123 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003124 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3125 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003127 return false;
3128}
3129
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003130/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003131/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003132int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003133 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003135 // Make all integer and enum types at least as large as an int
3136 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003137 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003138 // Treat arrays as pointers, since that's how they're passed in.
3139 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003140 sz = getTypeSize(VoidPtrTy);
3141 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003142}
3143
David Chisnall5e530af2009-11-17 19:33:30 +00003144/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3145/// declaration.
3146void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3147 std::string& S) {
3148 const BlockDecl *Decl = Expr->getBlockDecl();
3149 QualType BlockTy =
3150 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3151 // Encode result type.
3152 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3153 // Compute size of all parameters.
3154 // Start with computing size of a pointer in number of bytes.
3155 // FIXME: There might(should) be a better way of doing this computation!
3156 SourceLocation Loc;
3157 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3158 int ParmOffset = PtrSize;
3159 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3160 E = Decl->param_end(); PI != E; ++PI) {
3161 QualType PType = (*PI)->getType();
3162 int sz = getObjCEncodingTypeSize(PType);
3163 assert (sz > 0 && "BlockExpr - Incomplete param type");
3164 ParmOffset += sz;
3165 }
3166 // Size of the argument frame
3167 S += llvm::utostr(ParmOffset);
3168 // Block pointer and offset.
3169 S += "@?0";
3170 ParmOffset = PtrSize;
3171
3172 // Argument types.
3173 ParmOffset = PtrSize;
3174 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3175 Decl->param_end(); PI != E; ++PI) {
3176 ParmVarDecl *PVDecl = *PI;
3177 QualType PType = PVDecl->getOriginalType();
3178 if (const ArrayType *AT =
3179 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3180 // Use array's original type only if it has known number of
3181 // elements.
3182 if (!isa<ConstantArrayType>(AT))
3183 PType = PVDecl->getType();
3184 } else if (PType->isFunctionType())
3185 PType = PVDecl->getType();
3186 getObjCEncodingForType(PType, S);
3187 S += llvm::utostr(ParmOffset);
3188 ParmOffset += getObjCEncodingTypeSize(PType);
3189 }
3190}
3191
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003193/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003194void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003195 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003196 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003197 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003198 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003199 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003200 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003201 // Compute size of all parameters.
3202 // Start with computing size of a pointer in number of bytes.
3203 // FIXME: There might(should) be a better way of doing this computation!
3204 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003205 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003206 // The first two arguments (self and _cmd) are pointers; account for
3207 // their size.
3208 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003209 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3210 E = Decl->param_end(); PI != E; ++PI) {
3211 QualType PType = (*PI)->getType();
3212 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003213 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003214 ParmOffset += sz;
3215 }
3216 S += llvm::utostr(ParmOffset);
3217 S += "@0:";
3218 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003220 // Argument types.
3221 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003222 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3223 E = Decl->param_end(); PI != E; ++PI) {
3224 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003225 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003226 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003227 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3228 // Use array's original type only if it has known number of
3229 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003230 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003231 PType = PVDecl->getType();
3232 } else if (PType->isFunctionType())
3233 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003234 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003235 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003236 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003237 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003238 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003239 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003240 }
3241}
3242
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003243/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003244/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003245/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3246/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003247/// Property attributes are stored as a comma-delimited C string. The simple
3248/// attributes readonly and bycopy are encoded as single characters. The
3249/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3250/// encoded as single characters, followed by an identifier. Property types
3251/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003252/// these attributes are defined by the following enumeration:
3253/// @code
3254/// enum PropertyAttributes {
3255/// kPropertyReadOnly = 'R', // property is read-only.
3256/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3257/// kPropertyByref = '&', // property is a reference to the value last assigned
3258/// kPropertyDynamic = 'D', // property is dynamic
3259/// kPropertyGetter = 'G', // followed by getter selector name
3260/// kPropertySetter = 'S', // followed by setter selector name
3261/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3262/// kPropertyType = 't' // followed by old-style type encoding.
3263/// kPropertyWeak = 'W' // 'weak' property
3264/// kPropertyStrong = 'P' // property GC'able
3265/// kPropertyNonAtomic = 'N' // property non-atomic
3266/// };
3267/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003268void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003269 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003270 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003271 // Collect information from the property implementation decl(s).
3272 bool Dynamic = false;
3273 ObjCPropertyImplDecl *SynthesizePID = 0;
3274
3275 // FIXME: Duplicated code due to poor abstraction.
3276 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003277 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003278 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3279 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003280 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003281 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003282 ObjCPropertyImplDecl *PID = *i;
3283 if (PID->getPropertyDecl() == PD) {
3284 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3285 Dynamic = true;
3286 } else {
3287 SynthesizePID = PID;
3288 }
3289 }
3290 }
3291 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003292 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003293 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003294 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003295 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003296 ObjCPropertyImplDecl *PID = *i;
3297 if (PID->getPropertyDecl() == PD) {
3298 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3299 Dynamic = true;
3300 } else {
3301 SynthesizePID = PID;
3302 }
3303 }
Mike Stump1eb44332009-09-09 15:08:12 +00003304 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003305 }
3306 }
3307
3308 // FIXME: This is not very efficient.
3309 S = "T";
3310
3311 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003312 // GCC has some special rules regarding encoding of properties which
3313 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003314 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003315 true /* outermost type */,
3316 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003317
3318 if (PD->isReadOnly()) {
3319 S += ",R";
3320 } else {
3321 switch (PD->getSetterKind()) {
3322 case ObjCPropertyDecl::Assign: break;
3323 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003324 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003325 }
3326 }
3327
3328 // It really isn't clear at all what this means, since properties
3329 // are "dynamic by default".
3330 if (Dynamic)
3331 S += ",D";
3332
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003333 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3334 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003336 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3337 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003338 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003339 }
3340
3341 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3342 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003343 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003344 }
3345
3346 if (SynthesizePID) {
3347 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3348 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003349 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003350 }
3351
3352 // FIXME: OBJCGC: weak & strong
3353}
3354
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003355/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003356/// Another legacy compatibility encoding: 32-bit longs are encoded as
3357/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003358/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3359///
3360void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003361 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003362 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003363 if (BT->getKind() == BuiltinType::ULong &&
3364 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003365 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003366 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003367 if (BT->getKind() == BuiltinType::Long &&
3368 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003369 PointeeTy = IntTy;
3370 }
3371 }
3372}
3373
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003374void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003375 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003376 // We follow the behavior of gcc, expanding structures which are
3377 // directly pointed to, and expanding embedded structures. Note that
3378 // these rules are sufficient to prevent recursive encoding of the
3379 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003380 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003381 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003382}
3383
Mike Stump1eb44332009-09-09 15:08:12 +00003384static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003385 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003386 const Expr *E = FD->getBitWidth();
3387 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3388 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003389 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003390 S += 'b';
3391 S += llvm::utostr(N);
3392}
3393
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003394// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003395void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3396 bool ExpandPointedToStructures,
3397 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003398 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003399 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003400 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003401 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003402 if (FD && FD->isBitField())
3403 return EncodeBitField(this, S, FD);
3404 char encoding;
3405 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003406 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003407 case BuiltinType::Void: encoding = 'v'; break;
3408 case BuiltinType::Bool: encoding = 'B'; break;
3409 case BuiltinType::Char_U:
3410 case BuiltinType::UChar: encoding = 'C'; break;
3411 case BuiltinType::UShort: encoding = 'S'; break;
3412 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003413 case BuiltinType::ULong:
3414 encoding =
3415 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003416 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003417 case BuiltinType::UInt128: encoding = 'T'; break;
3418 case BuiltinType::ULongLong: encoding = 'Q'; break;
3419 case BuiltinType::Char_S:
3420 case BuiltinType::SChar: encoding = 'c'; break;
3421 case BuiltinType::Short: encoding = 's'; break;
3422 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003423 case BuiltinType::Long:
3424 encoding =
3425 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003426 break;
3427 case BuiltinType::LongLong: encoding = 'q'; break;
3428 case BuiltinType::Int128: encoding = 't'; break;
3429 case BuiltinType::Float: encoding = 'f'; break;
3430 case BuiltinType::Double: encoding = 'd'; break;
3431 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003432 }
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003434 S += encoding;
3435 return;
3436 }
Mike Stump1eb44332009-09-09 15:08:12 +00003437
John McCall183700f2009-09-21 23:43:11 +00003438 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003439 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003440 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003441 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003442 return;
3443 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003444
Ted Kremenek6217b802009-07-29 21:53:49 +00003445 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003446 if (PT->isObjCSelType()) {
3447 S += ':';
3448 return;
3449 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003450 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003451
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003452 bool isReadOnly = false;
3453 // For historical/compatibility reasons, the read-only qualifier of the
3454 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3455 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003456 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003457 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003458 if (OutermostType && T.isConstQualified()) {
3459 isReadOnly = true;
3460 S += 'r';
3461 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003462 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003463 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003464 while (P->getAs<PointerType>())
3465 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003466 if (P.isConstQualified()) {
3467 isReadOnly = true;
3468 S += 'r';
3469 }
3470 }
3471 if (isReadOnly) {
3472 // Another legacy compatibility encoding. Some ObjC qualifier and type
3473 // combinations need to be rearranged.
3474 // Rewrite "in const" from "nr" to "rn"
3475 const char * s = S.c_str();
3476 int len = S.length();
3477 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3478 std::string replace = "rn";
3479 S.replace(S.end()-2, S.end(), replace);
3480 }
3481 }
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003483 if (PointeeTy->isCharType()) {
3484 // char pointer types should be encoded as '*' unless it is a
3485 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003486 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003487 S += '*';
3488 return;
3489 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003490 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003491 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3492 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3493 S += '#';
3494 return;
3495 }
3496 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3497 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3498 S += '@';
3499 return;
3500 }
3501 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003502 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003503 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003504 getLegacyIntegralTypeEncoding(PointeeTy);
3505
Mike Stump1eb44332009-09-09 15:08:12 +00003506 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003507 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003508 return;
3509 }
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003511 if (const ArrayType *AT =
3512 // Ignore type qualifiers etc.
3513 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003514 if (isa<IncompleteArrayType>(AT)) {
3515 // Incomplete arrays are encoded as a pointer to the array element.
3516 S += '^';
3517
Mike Stump1eb44332009-09-09 15:08:12 +00003518 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003519 false, ExpandStructures, FD);
3520 } else {
3521 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Anders Carlsson559a8332009-02-22 01:38:57 +00003523 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3524 S += llvm::utostr(CAT->getSize().getZExtValue());
3525 else {
3526 //Variable length arrays are encoded as a regular array with 0 elements.
3527 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3528 S += '0';
3529 }
Mike Stump1eb44332009-09-09 15:08:12 +00003530
3531 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003532 false, ExpandStructures, FD);
3533 S += ']';
3534 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003535 return;
3536 }
Mike Stump1eb44332009-09-09 15:08:12 +00003537
John McCall183700f2009-09-21 23:43:11 +00003538 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003539 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003540 return;
3541 }
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Ted Kremenek6217b802009-07-29 21:53:49 +00003543 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003544 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003545 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003546 // Anonymous structures print as '?'
3547 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3548 S += II->getName();
3549 } else {
3550 S += '?';
3551 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003552 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003553 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003554 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3555 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003556 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003557 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003558 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003559 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003560 S += '"';
3561 }
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003563 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003564 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003565 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003566 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003567 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003568 QualType qt = Field->getType();
3569 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003570 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003571 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003572 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003573 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003574 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003575 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003576 return;
3577 }
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003579 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003580 if (FD && FD->isBitField())
3581 EncodeBitField(this, S, FD);
3582 else
3583 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003584 return;
3585 }
Mike Stump1eb44332009-09-09 15:08:12 +00003586
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003587 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003588 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003589 return;
3590 }
Mike Stump1eb44332009-09-09 15:08:12 +00003591
John McCall0953e762009-09-24 19:53:00 +00003592 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003593 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003594 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003595 S += '{';
3596 const IdentifierInfo *II = OI->getIdentifier();
3597 S += II->getName();
3598 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003599 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003600 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003601 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003602 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003603 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003604 RecFields[i]);
3605 else
Mike Stump1eb44332009-09-09 15:08:12 +00003606 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003607 FD);
3608 }
3609 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003610 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003611 }
Mike Stump1eb44332009-09-09 15:08:12 +00003612
John McCall183700f2009-09-21 23:43:11 +00003613 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003614 if (OPT->isObjCIdType()) {
3615 S += '@';
3616 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003617 }
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Steve Naroff27d20a22009-10-28 22:03:49 +00003619 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3620 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3621 // Since this is a binary compatibility issue, need to consult with runtime
3622 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003623 S += '#';
3624 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003625 }
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003627 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003628 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003629 ExpandPointedToStructures,
3630 ExpandStructures, FD);
3631 if (FD || EncodingProperty) {
3632 // Note that we do extended encoding of protocol qualifer list
3633 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003634 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003635 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3636 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003637 S += '<';
3638 S += (*I)->getNameAsString();
3639 S += '>';
3640 }
3641 S += '"';
3642 }
3643 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003644 }
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003646 QualType PointeeTy = OPT->getPointeeType();
3647 if (!EncodingProperty &&
3648 isa<TypedefType>(PointeeTy.getTypePtr())) {
3649 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003650 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003651 // {...};
3652 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003653 getObjCEncodingForTypeImpl(PointeeTy, S,
3654 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003655 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003656 return;
3657 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003658
3659 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003660 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003661 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003662 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003663 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3664 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003665 S += '<';
3666 S += (*I)->getNameAsString();
3667 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003668 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003669 S += '"';
3670 }
3671 return;
3672 }
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003674 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003675}
3676
Mike Stump1eb44332009-09-09 15:08:12 +00003677void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003678 std::string& S) const {
3679 if (QT & Decl::OBJC_TQ_In)
3680 S += 'n';
3681 if (QT & Decl::OBJC_TQ_Inout)
3682 S += 'N';
3683 if (QT & Decl::OBJC_TQ_Out)
3684 S += 'o';
3685 if (QT & Decl::OBJC_TQ_Bycopy)
3686 S += 'O';
3687 if (QT & Decl::OBJC_TQ_Byref)
3688 S += 'R';
3689 if (QT & Decl::OBJC_TQ_Oneway)
3690 S += 'V';
3691}
3692
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003693void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003694 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003696 BuiltinVaListType = T;
3697}
3698
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003699void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003700 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003701}
3702
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003703void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003704 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003705}
3706
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003707void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003708 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003709}
3710
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003711void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003712 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003713}
3714
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003715void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003716 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003717 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003719 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003720}
3721
John McCall0bd6feb2009-12-02 08:04:21 +00003722/// \brief Retrieve the template name that corresponds to a non-empty
3723/// lookup.
3724TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3725 NamedDecl * const *End) {
3726 unsigned size = End - Begin;
3727 assert(size > 1 && "set is not overloaded!");
3728
3729 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3730 size * sizeof(FunctionTemplateDecl*));
3731 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3732
3733 NamedDecl **Storage = OT->getStorage();
3734 for (NamedDecl * const *I = Begin; I != End; ++I) {
3735 NamedDecl *D = *I;
3736 assert(isa<FunctionTemplateDecl>(D) ||
3737 (isa<UsingShadowDecl>(D) &&
3738 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3739 *Storage++ = D;
3740 }
3741
3742 return TemplateName(OT);
3743}
3744
Douglas Gregor7532dc62009-03-30 22:58:21 +00003745/// \brief Retrieve the template name that represents a qualified
3746/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003747TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003748 bool TemplateKeyword,
3749 TemplateDecl *Template) {
3750 llvm::FoldingSetNodeID ID;
3751 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3752
3753 void *InsertPos = 0;
3754 QualifiedTemplateName *QTN =
3755 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3756 if (!QTN) {
3757 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3758 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3759 }
3760
3761 return TemplateName(QTN);
3762}
3763
3764/// \brief Retrieve the template name that represents a dependent
3765/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003766TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003767 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003768 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003769 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003770
3771 llvm::FoldingSetNodeID ID;
3772 DependentTemplateName::Profile(ID, NNS, Name);
3773
3774 void *InsertPos = 0;
3775 DependentTemplateName *QTN =
3776 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3777
3778 if (QTN)
3779 return TemplateName(QTN);
3780
3781 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3782 if (CanonNNS == NNS) {
3783 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3784 } else {
3785 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3786 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3787 }
3788
3789 DependentTemplateNames.InsertNode(QTN, InsertPos);
3790 return TemplateName(QTN);
3791}
3792
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003793/// \brief Retrieve the template name that represents a dependent
3794/// template name such as \c MetaFun::template operator+.
3795TemplateName
3796ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3797 OverloadedOperatorKind Operator) {
3798 assert((!NNS || NNS->isDependent()) &&
3799 "Nested name specifier must be dependent");
3800
3801 llvm::FoldingSetNodeID ID;
3802 DependentTemplateName::Profile(ID, NNS, Operator);
3803
3804 void *InsertPos = 0;
3805 DependentTemplateName *QTN =
3806 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3807
3808 if (QTN)
3809 return TemplateName(QTN);
3810
3811 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3812 if (CanonNNS == NNS) {
3813 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3814 } else {
3815 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3816 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3817 }
3818
3819 DependentTemplateNames.InsertNode(QTN, InsertPos);
3820 return TemplateName(QTN);
3821}
3822
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003823/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003824/// TargetInfo, produce the corresponding type. The unsigned @p Type
3825/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003826CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003827 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003828 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003829 case TargetInfo::SignedShort: return ShortTy;
3830 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3831 case TargetInfo::SignedInt: return IntTy;
3832 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3833 case TargetInfo::SignedLong: return LongTy;
3834 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3835 case TargetInfo::SignedLongLong: return LongLongTy;
3836 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3837 }
3838
3839 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003840 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003841}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003842
3843//===----------------------------------------------------------------------===//
3844// Type Predicates.
3845//===----------------------------------------------------------------------===//
3846
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003847/// isObjCNSObjectType - Return true if this is an NSObject object using
3848/// NSObject attribute on a c-style pointer type.
3849/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003850/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003851///
3852bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3853 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3854 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003855 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003856 return true;
3857 }
Mike Stump1eb44332009-09-09 15:08:12 +00003858 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003859}
3860
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003861/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3862/// garbage collection attribute.
3863///
John McCall0953e762009-09-24 19:53:00 +00003864Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3865 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003866 if (getLangOptions().ObjC1 &&
3867 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003868 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003869 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003870 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003871 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003872 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003873 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003874 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003875 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003876 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003877 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003878 // Non-pointers have none gc'able attribute regardless of the attribute
3879 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003880 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003881 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003882 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003883 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003884}
3885
Chris Lattner6ac46a42008-04-07 06:51:04 +00003886//===----------------------------------------------------------------------===//
3887// Type Compatibility Testing
3888//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003889
Mike Stump1eb44332009-09-09 15:08:12 +00003890/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003891/// compatible.
3892static bool areCompatVectorTypes(const VectorType *LHS,
3893 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003894 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003895 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003896 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003897}
3898
Steve Naroff4084c302009-07-23 01:01:38 +00003899//===----------------------------------------------------------------------===//
3900// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3901//===----------------------------------------------------------------------===//
3902
3903/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3904/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003905bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3906 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003907 if (lProto == rProto)
3908 return true;
3909 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3910 E = rProto->protocol_end(); PI != E; ++PI)
3911 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3912 return true;
3913 return false;
3914}
3915
Steve Naroff4084c302009-07-23 01:01:38 +00003916/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3917/// return true if lhs's protocols conform to rhs's protocol; false
3918/// otherwise.
3919bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3920 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3921 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3922 return false;
3923}
3924
3925/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3926/// ObjCQualifiedIDType.
3927bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3928 bool compare) {
3929 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003930 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003931 lhs->isObjCIdType() || lhs->isObjCClassType())
3932 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003933 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003934 rhs->isObjCIdType() || rhs->isObjCClassType())
3935 return true;
3936
3937 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003938 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Steve Naroff4084c302009-07-23 01:01:38 +00003940 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003941
Steve Naroff4084c302009-07-23 01:01:38 +00003942 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003943 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003944 // make sure we check the class hierarchy.
3945 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3946 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3947 E = lhsQID->qual_end(); I != E; ++I) {
3948 // when comparing an id<P> on lhs with a static type on rhs,
3949 // see if static class implements all of id's protocols, directly or
3950 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003951 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003952 return false;
3953 }
3954 }
3955 // If there are no qualifiers and no interface, we have an 'id'.
3956 return true;
3957 }
Mike Stump1eb44332009-09-09 15:08:12 +00003958 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003959 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3960 E = lhsQID->qual_end(); I != E; ++I) {
3961 ObjCProtocolDecl *lhsProto = *I;
3962 bool match = false;
3963
3964 // when comparing an id<P> on lhs with a static type on rhs,
3965 // see if static class implements all of id's protocols, directly or
3966 // through its super class and categories.
3967 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3968 E = rhsOPT->qual_end(); J != E; ++J) {
3969 ObjCProtocolDecl *rhsProto = *J;
3970 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3971 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3972 match = true;
3973 break;
3974 }
3975 }
Mike Stump1eb44332009-09-09 15:08:12 +00003976 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003977 // make sure we check the class hierarchy.
3978 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3979 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3980 E = lhsQID->qual_end(); I != E; ++I) {
3981 // when comparing an id<P> on lhs with a static type on rhs,
3982 // see if static class implements all of id's protocols, directly or
3983 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003984 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003985 match = true;
3986 break;
3987 }
3988 }
3989 }
3990 if (!match)
3991 return false;
3992 }
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Steve Naroff4084c302009-07-23 01:01:38 +00003994 return true;
3995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Steve Naroff4084c302009-07-23 01:01:38 +00003997 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3998 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3999
Mike Stump1eb44332009-09-09 15:08:12 +00004000 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004001 lhs->getAsObjCInterfacePointerType()) {
4002 if (lhsOPT->qual_empty()) {
4003 bool match = false;
4004 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4005 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4006 E = rhsQID->qual_end(); I != E; ++I) {
4007 // when comparing an id<P> on lhs with a static type on rhs,
4008 // see if static class implements all of id's protocols, directly or
4009 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004010 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004011 match = true;
4012 break;
4013 }
4014 }
4015 if (!match)
4016 return false;
4017 }
4018 return true;
4019 }
Mike Stump1eb44332009-09-09 15:08:12 +00004020 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004021 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4022 E = lhsOPT->qual_end(); I != E; ++I) {
4023 ObjCProtocolDecl *lhsProto = *I;
4024 bool match = false;
4025
4026 // when comparing an id<P> on lhs with a static type on rhs,
4027 // see if static class implements all of id's protocols, directly or
4028 // through its super class and categories.
4029 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4030 E = rhsQID->qual_end(); J != E; ++J) {
4031 ObjCProtocolDecl *rhsProto = *J;
4032 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4033 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4034 match = true;
4035 break;
4036 }
4037 }
4038 if (!match)
4039 return false;
4040 }
4041 return true;
4042 }
4043 return false;
4044}
4045
Eli Friedman3d815e72008-08-22 00:56:42 +00004046/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004047/// compatible for assignment from RHS to LHS. This handles validation of any
4048/// protocol qualifiers on the LHS or RHS.
4049///
Steve Naroff14108da2009-07-10 23:34:53 +00004050bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4051 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004052 // If either type represents the built-in 'id' or 'Class' types, return true.
4053 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004054 return true;
4055
Steve Naroff4084c302009-07-23 01:01:38 +00004056 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004057 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4058 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004059 false);
4060
Steve Naroff14108da2009-07-10 23:34:53 +00004061 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4062 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004063 if (LHS && RHS) // We have 2 user-defined types.
4064 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Steve Naroff4084c302009-07-23 01:01:38 +00004066 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004067}
4068
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004069/// getIntersectionOfProtocols - This routine finds the intersection of set
4070/// of protocols inherited from two distinct objective-c pointer objects.
4071/// It is used to build composite qualifier list of the composite type of
4072/// the conditional expression involving two objective-c pointer objects.
4073static
4074void getIntersectionOfProtocols(ASTContext &Context,
4075 const ObjCObjectPointerType *LHSOPT,
4076 const ObjCObjectPointerType *RHSOPT,
4077 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4078
4079 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4080 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4081
4082 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4083 unsigned LHSNumProtocols = LHS->getNumProtocols();
4084 if (LHSNumProtocols > 0)
4085 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4086 else {
4087 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4088 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4089 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4090 LHSInheritedProtocols.end());
4091 }
4092
4093 unsigned RHSNumProtocols = RHS->getNumProtocols();
4094 if (RHSNumProtocols > 0) {
4095 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4096 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4097 if (InheritedProtocolSet.count(RHSProtocols[i]))
4098 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4099 }
4100 else {
4101 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4102 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4103 // FIXME. This may cause duplication of protocols in the list, but should
4104 // be harmless.
4105 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4106 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4107 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4108 }
4109}
4110
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004111/// areCommonBaseCompatible - Returns common base class of the two classes if
4112/// one found. Note that this is O'2 algorithm. But it will be called as the
4113/// last type comparison in a ?-exp of ObjC pointer types before a
4114/// warning is issued. So, its invokation is extremely rare.
4115QualType ASTContext::areCommonBaseCompatible(
4116 const ObjCObjectPointerType *LHSOPT,
4117 const ObjCObjectPointerType *RHSOPT) {
4118 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4119 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4120 if (!LHS || !RHS)
4121 return QualType();
4122
4123 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4124 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4125 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004126 if (canAssignObjCInterfaces(LHS, RHS)) {
4127 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4128 getIntersectionOfProtocols(*this,
4129 LHSOPT, RHSOPT, IntersectionOfProtocols);
4130 if (IntersectionOfProtocols.empty())
4131 LHSTy = getObjCObjectPointerType(LHSTy);
4132 else
4133 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4134 IntersectionOfProtocols.size());
4135 return LHSTy;
4136 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004137 }
4138
4139 return QualType();
4140}
4141
Eli Friedman3d815e72008-08-22 00:56:42 +00004142bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4143 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004144 // Verify that the base decls are compatible: the RHS must be a subclass of
4145 // the LHS.
4146 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4147 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Chris Lattner6ac46a42008-04-07 06:51:04 +00004149 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4150 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004151 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004152 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004153
Chris Lattner6ac46a42008-04-07 06:51:04 +00004154 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4155 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004156 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004157 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004158
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004159 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4160 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004161 LHSPI != LHSPE; LHSPI++) {
4162 bool RHSImplementsProtocol = false;
4163
4164 // If the RHS doesn't implement the protocol on the left, the types
4165 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004166 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004167 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004168 RHSPI != RHSPE; RHSPI++) {
4169 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004170 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004171 break;
4172 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004173 }
4174 // FIXME: For better diagnostics, consider passing back the protocol name.
4175 if (!RHSImplementsProtocol)
4176 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004177 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004178 // The RHS implements all protocols listed on the LHS.
4179 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004180}
4181
Steve Naroff389bf462009-02-12 17:52:19 +00004182bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4183 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004184 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4185 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004186
Steve Naroff14108da2009-07-10 23:34:53 +00004187 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004188 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004189
4190 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4191 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004192}
4193
Mike Stump1eb44332009-09-09 15:08:12 +00004194/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004195/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004196/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004197/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004198bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4199 return !mergeTypes(LHS, RHS).isNull();
4200}
4201
4202QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004203 const FunctionType *lbase = lhs->getAs<FunctionType>();
4204 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004205 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4206 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004207 bool allLTypes = true;
4208 bool allRTypes = true;
4209
4210 // Check return type
4211 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4212 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004213 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4214 allLTypes = false;
4215 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4216 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004217 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004218 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4219 if (NoReturn != lbase->getNoReturnAttr())
4220 allLTypes = false;
4221 if (NoReturn != rbase->getNoReturnAttr())
4222 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004223
Eli Friedman3d815e72008-08-22 00:56:42 +00004224 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004225 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4226 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004227 unsigned lproto_nargs = lproto->getNumArgs();
4228 unsigned rproto_nargs = rproto->getNumArgs();
4229
4230 // Compatible functions must have the same number of arguments
4231 if (lproto_nargs != rproto_nargs)
4232 return QualType();
4233
4234 // Variadic and non-variadic functions aren't compatible
4235 if (lproto->isVariadic() != rproto->isVariadic())
4236 return QualType();
4237
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004238 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4239 return QualType();
4240
Eli Friedman3d815e72008-08-22 00:56:42 +00004241 // Check argument compatibility
4242 llvm::SmallVector<QualType, 10> types;
4243 for (unsigned i = 0; i < lproto_nargs; i++) {
4244 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4245 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4246 QualType argtype = mergeTypes(largtype, rargtype);
4247 if (argtype.isNull()) return QualType();
4248 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004249 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4250 allLTypes = false;
4251 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4252 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004253 }
4254 if (allLTypes) return lhs;
4255 if (allRTypes) return rhs;
4256 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004257 lproto->isVariadic(), lproto->getTypeQuals(),
4258 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004259 }
4260
4261 if (lproto) allRTypes = false;
4262 if (rproto) allLTypes = false;
4263
Douglas Gregor72564e72009-02-26 23:50:07 +00004264 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004265 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004266 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004267 if (proto->isVariadic()) return QualType();
4268 // Check that the types are compatible with the types that
4269 // would result from default argument promotions (C99 6.7.5.3p15).
4270 // The only types actually affected are promotable integer
4271 // types and floats, which would be passed as a different
4272 // type depending on whether the prototype is visible.
4273 unsigned proto_nargs = proto->getNumArgs();
4274 for (unsigned i = 0; i < proto_nargs; ++i) {
4275 QualType argTy = proto->getArgType(i);
4276 if (argTy->isPromotableIntegerType() ||
4277 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4278 return QualType();
4279 }
4280
4281 if (allLTypes) return lhs;
4282 if (allRTypes) return rhs;
4283 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004284 proto->getNumArgs(), proto->isVariadic(),
4285 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004286 }
4287
4288 if (allLTypes) return lhs;
4289 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004290 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004291}
4292
4293QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004294 // C++ [expr]: If an expression initially has the type "reference to T", the
4295 // type is adjusted to "T" prior to any further analysis, the expression
4296 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004297 // expression is an lvalue unless the reference is an rvalue reference and
4298 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004299 // FIXME: C++ shouldn't be going through here! The rules are different
4300 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004301 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4302 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004303 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004304 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004305 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004306 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004307
Eli Friedman3d815e72008-08-22 00:56:42 +00004308 QualType LHSCan = getCanonicalType(LHS),
4309 RHSCan = getCanonicalType(RHS);
4310
4311 // If two types are identical, they are compatible.
4312 if (LHSCan == RHSCan)
4313 return LHS;
4314
John McCall0953e762009-09-24 19:53:00 +00004315 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004316 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4317 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004318 if (LQuals != RQuals) {
4319 // If any of these qualifiers are different, we have a type
4320 // mismatch.
4321 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4322 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4323 return QualType();
4324
4325 // Exactly one GC qualifier difference is allowed: __strong is
4326 // okay if the other type has no GC qualifier but is an Objective
4327 // C object pointer (i.e. implicitly strong by default). We fix
4328 // this by pretending that the unqualified type was actually
4329 // qualified __strong.
4330 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4331 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4332 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4333
4334 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4335 return QualType();
4336
4337 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4338 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4339 }
4340 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4341 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4342 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004343 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004344 }
4345
4346 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004347
Eli Friedman852d63b2009-06-01 01:22:52 +00004348 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4349 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004350
Chris Lattner1adb8832008-01-14 05:45:46 +00004351 // We want to consider the two function types to be the same for these
4352 // comparisons, just force one to the other.
4353 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4354 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004355
4356 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004357 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4358 LHSClass = Type::ConstantArray;
4359 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4360 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Nate Begeman213541a2008-04-18 23:10:10 +00004362 // Canonicalize ExtVector -> Vector.
4363 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4364 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Chris Lattnera36a61f2008-04-07 05:43:21 +00004366 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004367 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004368 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004369 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004370 // Compatibility is based on the underlying type, not the promotion
4371 // type.
John McCall183700f2009-09-21 23:43:11 +00004372 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004373 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4374 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004375 }
John McCall183700f2009-09-21 23:43:11 +00004376 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004377 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4378 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004379 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004380
Eli Friedman3d815e72008-08-22 00:56:42 +00004381 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004382 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004383
Steve Naroff4a746782008-01-09 22:43:08 +00004384 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004385 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004386#define TYPE(Class, Base)
4387#define ABSTRACT_TYPE(Class, Base)
4388#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4389#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4390#include "clang/AST/TypeNodes.def"
4391 assert(false && "Non-canonical and dependent types shouldn't get here");
4392 return QualType();
4393
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004394 case Type::LValueReference:
4395 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004396 case Type::MemberPointer:
4397 assert(false && "C++ should never be in mergeTypes");
4398 return QualType();
4399
4400 case Type::IncompleteArray:
4401 case Type::VariableArray:
4402 case Type::FunctionProto:
4403 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004404 assert(false && "Types are eliminated above");
4405 return QualType();
4406
Chris Lattner1adb8832008-01-14 05:45:46 +00004407 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004408 {
4409 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004410 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4411 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004412 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4413 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004414 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004415 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004416 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004417 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004418 return getPointerType(ResultType);
4419 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004420 case Type::BlockPointer:
4421 {
4422 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004423 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4424 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004425 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4426 if (ResultType.isNull()) return QualType();
4427 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4428 return LHS;
4429 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4430 return RHS;
4431 return getBlockPointerType(ResultType);
4432 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004433 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004434 {
4435 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4436 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4437 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4438 return QualType();
4439
4440 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4441 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4442 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4443 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004444 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4445 return LHS;
4446 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4447 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004448 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4449 ArrayType::ArraySizeModifier(), 0);
4450 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4451 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004452 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4453 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004454 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4455 return LHS;
4456 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4457 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004458 if (LVAT) {
4459 // FIXME: This isn't correct! But tricky to implement because
4460 // the array's size has to be the size of LHS, but the type
4461 // has to be different.
4462 return LHS;
4463 }
4464 if (RVAT) {
4465 // FIXME: This isn't correct! But tricky to implement because
4466 // the array's size has to be the size of RHS, but the type
4467 // has to be different.
4468 return RHS;
4469 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004470 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4471 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004472 return getIncompleteArrayType(ResultType,
4473 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004474 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004475 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004476 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004477 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004478 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004479 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004480 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004481 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004482 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004483 case Type::Complex:
4484 // Distinct complex types are incompatible.
4485 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004486 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004487 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004488 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004489 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004490 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004491 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004492 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004493 // FIXME: This should be type compatibility, e.g. whether
4494 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004495 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4496 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004497 if (LHSIface && RHSIface &&
4498 canAssignObjCInterfaces(LHSIface, RHSIface))
4499 return LHS;
4500
Eli Friedman3d815e72008-08-22 00:56:42 +00004501 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004502 }
Steve Naroff14108da2009-07-10 23:34:53 +00004503 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004504 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4505 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004506 return LHS;
4507
Steve Naroffbc76dd02008-12-10 22:14:21 +00004508 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004509 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004510 case Type::FixedWidthInt:
4511 // Distinct fixed-width integers are not compatible.
4512 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004513 case Type::TemplateSpecialization:
4514 assert(false && "Dependent types have no size");
4515 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004516 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004517
4518 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004519}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004520
Chris Lattner5426bf62008-04-07 07:01:58 +00004521//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004522// Integer Predicates
4523//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004524
Eli Friedmanad74a752008-06-28 06:23:08 +00004525unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004526 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004527 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004528 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004529 return FWIT->getWidth();
4530 }
John McCall842aef82009-12-09 09:09:27 +00004531 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004532 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004533 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004534 return (unsigned)getTypeSize(T);
4535}
4536
4537QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4538 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004539
4540 // Turn <4 x signed int> -> <4 x unsigned int>
4541 if (const VectorType *VTy = T->getAs<VectorType>())
4542 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4543 VTy->getNumElements());
4544
4545 // For enums, we return the unsigned version of the base type.
4546 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004547 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004548
4549 const BuiltinType *BTy = T->getAs<BuiltinType>();
4550 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004551 switch (BTy->getKind()) {
4552 case BuiltinType::Char_S:
4553 case BuiltinType::SChar:
4554 return UnsignedCharTy;
4555 case BuiltinType::Short:
4556 return UnsignedShortTy;
4557 case BuiltinType::Int:
4558 return UnsignedIntTy;
4559 case BuiltinType::Long:
4560 return UnsignedLongTy;
4561 case BuiltinType::LongLong:
4562 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004563 case BuiltinType::Int128:
4564 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004565 default:
4566 assert(0 && "Unexpected signed integer type");
4567 return QualType();
4568 }
4569}
4570
Douglas Gregor2cf26342009-04-09 22:27:44 +00004571ExternalASTSource::~ExternalASTSource() { }
4572
4573void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004574
4575
4576//===----------------------------------------------------------------------===//
4577// Builtin Type Computation
4578//===----------------------------------------------------------------------===//
4579
4580/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4581/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004582static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004583 ASTContext::GetBuiltinTypeError &Error,
4584 bool AllowTypeModifiers = true) {
4585 // Modifiers.
4586 int HowLong = 0;
4587 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004588
Chris Lattner86df27b2009-06-14 00:45:47 +00004589 // Read the modifiers first.
4590 bool Done = false;
4591 while (!Done) {
4592 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004593 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004594 case 'S':
4595 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4596 assert(!Signed && "Can't use 'S' modifier multiple times!");
4597 Signed = true;
4598 break;
4599 case 'U':
4600 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4601 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4602 Unsigned = true;
4603 break;
4604 case 'L':
4605 assert(HowLong <= 2 && "Can't have LLLL modifier");
4606 ++HowLong;
4607 break;
4608 }
4609 }
4610
4611 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004612
Chris Lattner86df27b2009-06-14 00:45:47 +00004613 // Read the base type.
4614 switch (*Str++) {
4615 default: assert(0 && "Unknown builtin type letter!");
4616 case 'v':
4617 assert(HowLong == 0 && !Signed && !Unsigned &&
4618 "Bad modifiers used with 'v'!");
4619 Type = Context.VoidTy;
4620 break;
4621 case 'f':
4622 assert(HowLong == 0 && !Signed && !Unsigned &&
4623 "Bad modifiers used with 'f'!");
4624 Type = Context.FloatTy;
4625 break;
4626 case 'd':
4627 assert(HowLong < 2 && !Signed && !Unsigned &&
4628 "Bad modifiers used with 'd'!");
4629 if (HowLong)
4630 Type = Context.LongDoubleTy;
4631 else
4632 Type = Context.DoubleTy;
4633 break;
4634 case 's':
4635 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4636 if (Unsigned)
4637 Type = Context.UnsignedShortTy;
4638 else
4639 Type = Context.ShortTy;
4640 break;
4641 case 'i':
4642 if (HowLong == 3)
4643 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4644 else if (HowLong == 2)
4645 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4646 else if (HowLong == 1)
4647 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4648 else
4649 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4650 break;
4651 case 'c':
4652 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4653 if (Signed)
4654 Type = Context.SignedCharTy;
4655 else if (Unsigned)
4656 Type = Context.UnsignedCharTy;
4657 else
4658 Type = Context.CharTy;
4659 break;
4660 case 'b': // boolean
4661 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4662 Type = Context.BoolTy;
4663 break;
4664 case 'z': // size_t.
4665 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4666 Type = Context.getSizeType();
4667 break;
4668 case 'F':
4669 Type = Context.getCFConstantStringType();
4670 break;
4671 case 'a':
4672 Type = Context.getBuiltinVaListType();
4673 assert(!Type.isNull() && "builtin va list type not initialized!");
4674 break;
4675 case 'A':
4676 // This is a "reference" to a va_list; however, what exactly
4677 // this means depends on how va_list is defined. There are two
4678 // different kinds of va_list: ones passed by value, and ones
4679 // passed by reference. An example of a by-value va_list is
4680 // x86, where va_list is a char*. An example of by-ref va_list
4681 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4682 // we want this argument to be a char*&; for x86-64, we want
4683 // it to be a __va_list_tag*.
4684 Type = Context.getBuiltinVaListType();
4685 assert(!Type.isNull() && "builtin va list type not initialized!");
4686 if (Type->isArrayType()) {
4687 Type = Context.getArrayDecayedType(Type);
4688 } else {
4689 Type = Context.getLValueReferenceType(Type);
4690 }
4691 break;
4692 case 'V': {
4693 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004694 unsigned NumElements = strtoul(Str, &End, 10);
4695 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Chris Lattner86df27b2009-06-14 00:45:47 +00004697 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Chris Lattner86df27b2009-06-14 00:45:47 +00004699 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4700 Type = Context.getVectorType(ElementType, NumElements);
4701 break;
4702 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004703 case 'X': {
4704 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4705 Type = Context.getComplexType(ElementType);
4706 break;
4707 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004708 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004709 Type = Context.getFILEType();
4710 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004711 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004712 return QualType();
4713 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004714 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004715 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004716 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004717 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004718 else
4719 Type = Context.getjmp_bufType();
4720
Mike Stumpfd612db2009-07-28 23:47:15 +00004721 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004722 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004723 return QualType();
4724 }
4725 break;
Mike Stump782fa302009-07-28 02:25:19 +00004726 }
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Chris Lattner86df27b2009-06-14 00:45:47 +00004728 if (!AllowTypeModifiers)
4729 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Chris Lattner86df27b2009-06-14 00:45:47 +00004731 Done = false;
4732 while (!Done) {
4733 switch (*Str++) {
4734 default: Done = true; --Str; break;
4735 case '*':
4736 Type = Context.getPointerType(Type);
4737 break;
4738 case '&':
4739 Type = Context.getLValueReferenceType(Type);
4740 break;
4741 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4742 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004743 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004744 break;
4745 }
4746 }
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Chris Lattner86df27b2009-06-14 00:45:47 +00004748 return Type;
4749}
4750
4751/// GetBuiltinType - Return the type for the specified builtin.
4752QualType ASTContext::GetBuiltinType(unsigned id,
4753 GetBuiltinTypeError &Error) {
4754 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Chris Lattner86df27b2009-06-14 00:45:47 +00004756 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Chris Lattner86df27b2009-06-14 00:45:47 +00004758 Error = GE_None;
4759 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4760 if (Error != GE_None)
4761 return QualType();
4762 while (TypeStr[0] && TypeStr[0] != '.') {
4763 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4764 if (Error != GE_None)
4765 return QualType();
4766
4767 // Do array -> pointer decay. The builtin should use the decayed type.
4768 if (Ty->isArrayType())
4769 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004770
Chris Lattner86df27b2009-06-14 00:45:47 +00004771 ArgTypes.push_back(Ty);
4772 }
4773
4774 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4775 "'.' should only occur at end of builtin type list!");
4776
4777 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4778 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4779 return getFunctionNoProtoType(ResType);
4780 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4781 TypeStr[0] == '.', 0);
4782}
Eli Friedmana95d7572009-08-19 07:44:53 +00004783
4784QualType
4785ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4786 // Perform the usual unary conversions. We do this early so that
4787 // integral promotions to "int" can allow us to exit early, in the
4788 // lhs == rhs check. Also, for conversion purposes, we ignore any
4789 // qualifiers. For example, "const float" and "float" are
4790 // equivalent.
4791 if (lhs->isPromotableIntegerType())
4792 lhs = getPromotedIntegerType(lhs);
4793 else
4794 lhs = lhs.getUnqualifiedType();
4795 if (rhs->isPromotableIntegerType())
4796 rhs = getPromotedIntegerType(rhs);
4797 else
4798 rhs = rhs.getUnqualifiedType();
4799
4800 // If both types are identical, no conversion is needed.
4801 if (lhs == rhs)
4802 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Eli Friedmana95d7572009-08-19 07:44:53 +00004804 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4805 // The caller can deal with this (e.g. pointer + int).
4806 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4807 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004808
4809 // At this point, we have two different arithmetic types.
4810
Eli Friedmana95d7572009-08-19 07:44:53 +00004811 // Handle complex types first (C99 6.3.1.8p1).
4812 if (lhs->isComplexType() || rhs->isComplexType()) {
4813 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004814 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004815 // convert the rhs to the lhs complex type.
4816 return lhs;
4817 }
Mike Stump1eb44332009-09-09 15:08:12 +00004818 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004819 // convert the lhs to the rhs complex type.
4820 return rhs;
4821 }
4822 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004823 // When both operands are complex, the shorter operand is converted to the
4824 // type of the longer, and that is the type of the result. This corresponds
4825 // to what is done when combining two real floating-point operands.
4826 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004827 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004828 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004829 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004830 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004831 // "double _Complex" is promoted to "long double _Complex".
4832 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004833
4834 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004835 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004836 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004837 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004838 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004839 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4840 // domains match. This is a requirement for our implementation, C99
4841 // does not require this promotion.
4842 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4843 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4844 return rhs;
4845 } else { // handle "_Complex double, double".
4846 return lhs;
4847 }
4848 }
4849 return lhs; // The domain/size match exactly.
4850 }
4851 // Now handle "real" floating types (i.e. float, double, long double).
4852 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4853 // if we have an integer operand, the result is the real floating type.
4854 if (rhs->isIntegerType()) {
4855 // convert rhs to the lhs floating point type.
4856 return lhs;
4857 }
4858 if (rhs->isComplexIntegerType()) {
4859 // convert rhs to the complex floating point type.
4860 return getComplexType(lhs);
4861 }
4862 if (lhs->isIntegerType()) {
4863 // convert lhs to the rhs floating point type.
4864 return rhs;
4865 }
Mike Stump1eb44332009-09-09 15:08:12 +00004866 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004867 // convert lhs to the complex floating point type.
4868 return getComplexType(rhs);
4869 }
4870 // We have two real floating types, float/complex combos were handled above.
4871 // Convert the smaller operand to the bigger result.
4872 int result = getFloatingTypeOrder(lhs, rhs);
4873 if (result > 0) // convert the rhs
4874 return lhs;
4875 assert(result < 0 && "illegal float comparison");
4876 return rhs; // convert the lhs
4877 }
4878 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4879 // Handle GCC complex int extension.
4880 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4881 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4882
4883 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004884 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004885 rhsComplexInt->getElementType()) >= 0)
4886 return lhs; // convert the rhs
4887 return rhs;
4888 } else if (lhsComplexInt && rhs->isIntegerType()) {
4889 // convert the rhs to the lhs complex type.
4890 return lhs;
4891 } else if (rhsComplexInt && lhs->isIntegerType()) {
4892 // convert the lhs to the rhs complex type.
4893 return rhs;
4894 }
4895 }
4896 // Finally, we have two differing integer types.
4897 // The rules for this case are in C99 6.3.1.8
4898 int compare = getIntegerTypeOrder(lhs, rhs);
4899 bool lhsSigned = lhs->isSignedIntegerType(),
4900 rhsSigned = rhs->isSignedIntegerType();
4901 QualType destType;
4902 if (lhsSigned == rhsSigned) {
4903 // Same signedness; use the higher-ranked type
4904 destType = compare >= 0 ? lhs : rhs;
4905 } else if (compare != (lhsSigned ? 1 : -1)) {
4906 // The unsigned type has greater than or equal rank to the
4907 // signed type, so use the unsigned type
4908 destType = lhsSigned ? rhs : lhs;
4909 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4910 // The two types are different widths; if we are here, that
4911 // means the signed type is larger than the unsigned type, so
4912 // use the signed type.
4913 destType = lhsSigned ? lhs : rhs;
4914 } else {
4915 // The signed type is higher-ranked than the unsigned type,
4916 // but isn't actually any bigger (like unsigned int and long
4917 // on most 32-bit systems). Use the unsigned type corresponding
4918 // to the signed type.
4919 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4920 }
4921 return destType;
4922}