blob: c8caeb62b31144054ef928e6f45b2ca0c26ff356 [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 Kremenek3478eb62010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
62
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000063 if (FreeMemory) {
64 // Deallocate all the types.
65 while (!Types.empty()) {
66 Types.back()->Destroy(*this);
67 Types.pop_back();
68 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000069
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000070 for (llvm::FoldingSet<ExtQuals>::iterator
71 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
72 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000073 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000074 }
75 }
76
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000077 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
78 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
79 // Increment in loop to prevent using deallocated memory.
80 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
81 delete R;
82 }
83
84 for (llvm::DenseMap<const ObjCContainerDecl*,
85 const ASTRecordLayout*>::iterator
86 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
87 // Increment in loop to prevent using deallocated memory.
88 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
89 delete R;
Nuno Lopesb74668e2008-12-17 22:30:25 +000090 }
91
Douglas Gregorab452ba2009-03-26 23:50:42 +000092 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000093 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
94 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000095 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000096 NNS != NNSEnd; ) {
97 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000098 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000099 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000100
101 if (GlobalNestedNameSpecifier)
102 GlobalNestedNameSpecifier->Destroy(*this);
103
Eli Friedmanb26153c2008-05-27 03:08:09 +0000104 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000105}
106
Mike Stump1eb44332009-09-09 15:08:12 +0000107void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000108ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
109 ExternalSource.reset(Source.take());
110}
111
Reid Spencer5f016e22007-07-11 17:01:13 +0000112void ASTContext::PrintStats() const {
113 fprintf(stderr, "*** AST Context Stats:\n");
114 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000115
Douglas Gregordbe833d2009-05-26 14:40:08 +0000116 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000117#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000118#define ABSTRACT_TYPE(Name, Parent)
119#include "clang/AST/TypeNodes.def"
120 0 // Extra
121 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000122
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
124 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000125 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 }
127
Douglas Gregordbe833d2009-05-26 14:40:08 +0000128 unsigned Idx = 0;
129 unsigned TotalBytes = 0;
130#define TYPE(Name, Parent) \
131 if (counts[Idx]) \
132 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
133 TotalBytes += counts[Idx] * sizeof(Name##Type); \
134 ++Idx;
135#define ABSTRACT_TYPE(Name, Parent)
136#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Douglas Gregordbe833d2009-05-26 14:40:08 +0000138 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000139
140 if (ExternalSource.get()) {
141 fprintf(stderr, "\n");
142 ExternalSource->PrintStats();
143 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000144}
145
146
John McCalle27ec8a2009-10-23 23:03:21 +0000147void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000148 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000149 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000150 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000151}
152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153void ASTContext::InitBuiltinTypes() {
154 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 // C99 6.2.5p19.
157 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 // C99 6.2.5p2.
160 InitBuiltinType(BoolTy, BuiltinType::Bool);
161 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000162 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 InitBuiltinType(CharTy, BuiltinType::Char_S);
164 else
165 InitBuiltinType(CharTy, BuiltinType::Char_U);
166 // C99 6.2.5p4.
167 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
168 InitBuiltinType(ShortTy, BuiltinType::Short);
169 InitBuiltinType(IntTy, BuiltinType::Int);
170 InitBuiltinType(LongTy, BuiltinType::Long);
171 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 // C99 6.2.5p6.
174 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
175 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
176 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
177 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
178 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 // C99 6.2.5p10.
181 InitBuiltinType(FloatTy, BuiltinType::Float);
182 InitBuiltinType(DoubleTy, BuiltinType::Double);
183 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000184
Chris Lattner2df9ced2009-04-30 02:43:43 +0000185 // GNU extension, 128-bit integers.
186 InitBuiltinType(Int128Ty, BuiltinType::Int128);
187 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
188
Chris Lattner3a250322009-02-26 23:43:47 +0000189 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
190 InitBuiltinType(WCharTy, BuiltinType::WChar);
191 else // C99
192 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000193
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000194 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
195 InitBuiltinType(Char16Ty, BuiltinType::Char16);
196 else // C99
197 Char16Ty = getFromTargetType(Target.getChar16Type());
198
199 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
200 InitBuiltinType(Char32Ty, BuiltinType::Char32);
201 else // C99
202 Char32Ty = getFromTargetType(Target.getChar32Type());
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000205 InitBuiltinType(OverloadTy, BuiltinType::Overload);
206
207 // Placeholder type for type-dependent expressions whose type is
208 // completely unknown. No code should ever check a type against
209 // DependentTy and users should never see it; however, it is here to
210 // help diagnose failures to properly check for type-dependent
211 // expressions.
212 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213
Mike Stump1eb44332009-09-09 15:08:12 +0000214 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000215 // not yet been deduced.
216 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // C99 6.2.5p11.
219 FloatComplexTy = getComplexType(FloatTy);
220 DoubleComplexTy = getComplexType(DoubleTy);
221 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222
Steve Naroff7e219e42007-10-15 14:41:52 +0000223 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Steve Naroffde2e22d2009-07-15 18:40:39 +0000225 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
226 ObjCIdTypedefType = QualType();
227 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000228 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000230 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000231 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
232 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000233 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000234
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000237 // void * type
238 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000239
240 // nullptr type (C++0x 2.14.7)
241 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000242}
243
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000244MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000245ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000246 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000247 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 = InstantiatedFromStaticDataMember.find(Var);
249 if (Pos == InstantiatedFromStaticDataMember.end())
250 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Douglas Gregor7caa6822009-07-24 20:34:43 +0000252 return Pos->second;
253}
254
Mike Stump1eb44332009-09-09 15:08:12 +0000255void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000256ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
257 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000258 assert(Inst->isStaticDataMember() && "Not a static data member");
259 assert(Tmpl->isStaticDataMember() && "Not a static data member");
260 assert(!InstantiatedFromStaticDataMember[Inst] &&
261 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000262 InstantiatedFromStaticDataMember[Inst]
263 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000264}
265
John McCall7ba107a2009-11-18 02:36:19 +0000266NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000267ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000268 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000269 = InstantiatedFromUsingDecl.find(UUD);
270 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000271 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Anders Carlsson0d8df782009-08-29 19:37:28 +0000273 return Pos->second;
274}
275
276void
John McCalled976492009-12-04 22:46:56 +0000277ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
278 assert((isa<UsingDecl>(Pattern) ||
279 isa<UnresolvedUsingValueDecl>(Pattern) ||
280 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
281 "pattern decl is not a using decl");
282 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
283 InstantiatedFromUsingDecl[Inst] = Pattern;
284}
285
286UsingShadowDecl *
287ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
288 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
289 = InstantiatedFromUsingShadowDecl.find(Inst);
290 if (Pos == InstantiatedFromUsingShadowDecl.end())
291 return 0;
292
293 return Pos->second;
294}
295
296void
297ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
298 UsingShadowDecl *Pattern) {
299 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
300 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000301}
302
Anders Carlssond8b285f2009-09-01 04:26:58 +0000303FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
304 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
305 = InstantiatedFromUnnamedFieldDecl.find(Field);
306 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
307 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Anders Carlssond8b285f2009-09-01 04:26:58 +0000309 return Pos->second;
310}
311
312void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
313 FieldDecl *Tmpl) {
314 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
315 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
316 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
317 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Anders Carlssond8b285f2009-09-01 04:26:58 +0000319 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
320}
321
Douglas Gregor2e222532009-07-02 17:08:52 +0000322namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000323 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000324 : std::binary_function<SourceRange, SourceRange, bool> {
325 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Douglas Gregor2e222532009-07-02 17:08:52 +0000327 public:
328 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor2e222532009-07-02 17:08:52 +0000330 bool operator()(SourceRange X, SourceRange Y) {
331 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
332 }
333 };
334}
335
336/// \brief Determine whether the given comment is a Doxygen-style comment.
337///
338/// \param Start the start of the comment text.
339///
340/// \param End the end of the comment text.
341///
342/// \param Member whether we want to check whether this is a member comment
343/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
344/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000345static bool
346isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000347 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000348 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
350 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
351 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor2e222532009-07-02 17:08:52 +0000353 if (End - Start < 4)
354 return false;
355
356 assert(Start[0] == '/' && "Not a comment?");
357 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
358 return false;
359 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
360 return false;
361
362 return (Start[3] == '<') == Member;
363}
364
365/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000366/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000367const char *ASTContext::getCommentForDecl(const Decl *D) {
368 if (!D)
369 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregor2e222532009-07-02 17:08:52 +0000371 // Check whether we have cached a comment string for this declaration
372 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000373 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000374 = DeclComments.find(D);
375 if (Pos != DeclComments.end())
376 return Pos->second.c_str();
377
Mike Stump1eb44332009-09-09 15:08:12 +0000378 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000379 // that source, do so now.
380 if (ExternalSource && !LoadedExternalComments) {
381 std::vector<SourceRange> LoadedComments;
382 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 if (!LoadedComments.empty())
385 Comments.insert(Comments.begin(), LoadedComments.begin(),
386 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 LoadedExternalComments = true;
389 }
Mike Stump1eb44332009-09-09 15:08:12 +0000390
391 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000392 if (Comments.empty())
393 return 0;
394
395 // If the declaration doesn't map directly to a location in a file, we
396 // can't find the comment.
397 SourceLocation DeclStartLoc = D->getLocStart();
398 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
399 return 0;
400
401 // Find the comment that occurs just before this declaration.
402 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000403 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000404 SourceRange(DeclStartLoc),
405 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregor2e222532009-07-02 17:08:52 +0000407 // Decompose the location for the start of the declaration and find the
408 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000409 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000411 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000412 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Douglas Gregor2e222532009-07-02 17:08:52 +0000414 // First check whether we have a comment for a member.
415 if (LastComment != Comments.end() &&
416 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
417 isDoxygenComment(SourceMgr, *LastComment, true)) {
418 std::pair<FileID, unsigned> LastCommentEndDecomp
419 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
420 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
421 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000422 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000423 LastCommentEndDecomp.second)) {
424 // The Doxygen member comment comes after the declaration starts and
425 // is on the same line and in the same file as the declaration. This
426 // is the comment we want.
427 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000428 Result.append(FileBufferStart +
429 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000430 FileBufferStart + LastCommentEndDecomp.second + 1);
431 return Result.c_str();
432 }
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Douglas Gregor2e222532009-07-02 17:08:52 +0000435 if (LastComment == Comments.begin())
436 return 0;
437 --LastComment;
438
439 // Decompose the end of the comment.
440 std::pair<FileID, unsigned> LastCommentEndDecomp
441 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregor2e222532009-07-02 17:08:52 +0000443 // If the comment and the declaration aren't in the same file, then they
444 // aren't related.
445 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-07-02 17:08:52 +0000448 // Check that we actually have a Doxygen comment.
449 if (!isDoxygenComment(SourceMgr, *LastComment))
450 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Douglas Gregor2e222532009-07-02 17:08:52 +0000452 // Compute the starting line for the declaration and for the end of the
453 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000454 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000455 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
456 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000457 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000458 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Douglas Gregor2e222532009-07-02 17:08:52 +0000460 // If the comment does not end on the line prior to the declaration, then
461 // the comment is not associated with the declaration at all.
462 if (CommentEndLine + 1 != DeclStartLine)
463 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Douglas Gregor2e222532009-07-02 17:08:52 +0000465 // We have a comment, but there may be more comments on the previous lines.
466 // Keep looking so long as the comments are still Doxygen comments and are
467 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000468 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000469 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
470 std::vector<SourceRange>::iterator FirstComment = LastComment;
471 while (FirstComment != Comments.begin()) {
472 // Look at the previous comment
473 --FirstComment;
474 std::pair<FileID, unsigned> Decomp
475 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Douglas Gregor2e222532009-07-02 17:08:52 +0000477 // If this previous comment is in a different file, we're done.
478 if (Decomp.first != DeclStartDecomp.first) {
479 ++FirstComment;
480 break;
481 }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregor2e222532009-07-02 17:08:52 +0000483 // If this comment is not a Doxygen comment, we're done.
484 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
485 ++FirstComment;
486 break;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregor2e222532009-07-02 17:08:52 +0000489 // If the line number is not what we expected, we're done.
490 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
491 if (Line != ExpectedLine) {
492 ++FirstComment;
493 break;
494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregor2e222532009-07-02 17:08:52 +0000496 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000497 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000498 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor2e222532009-07-02 17:08:52 +0000501 // The iterator range [FirstComment, LastComment] contains all of the
502 // BCPL comments that, together, are associated with this declaration.
503 // Form a single comment block string for this declaration that concatenates
504 // all of these comments.
505 std::string &Result = DeclComments[D];
506 while (FirstComment != LastComment) {
507 std::pair<FileID, unsigned> DecompStart
508 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
509 std::pair<FileID, unsigned> DecompEnd
510 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
511 Result.append(FileBufferStart + DecompStart.second,
512 FileBufferStart + DecompEnd.second + 1);
513 ++FirstComment;
514 }
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Douglas Gregor2e222532009-07-02 17:08:52 +0000516 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000517 Result.append(FileBufferStart +
518 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000519 FileBufferStart + LastCommentEndDecomp.second + 1);
520 return Result.c_str();
521}
522
Chris Lattner464175b2007-07-18 17:52:12 +0000523//===----------------------------------------------------------------------===//
524// Type Sizing and Analysis
525//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000526
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
528/// scalar floating point type.
529const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000530 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000531 assert(BT && "Not a floating point type!");
532 switch (BT->getKind()) {
533 default: assert(0 && "Not a floating point type!");
534 case BuiltinType::Float: return Target.getFloatFormat();
535 case BuiltinType::Double: return Target.getDoubleFormat();
536 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
537 }
538}
539
Ken Dyck8b752f12010-01-27 17:10:57 +0000540/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000541/// specified decl. Note that bitfields do not have a valid alignment, so
542/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000543/// If @p RefAsPointee, references are treated like their underlying type
544/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000545CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546 unsigned Align = Target.getCharWidth();
547
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000548 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000549 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000550
Chris Lattneraf707ab2009-01-24 21:53:27 +0000551 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
552 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000553 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000554 if (RefAsPointee)
555 T = RT->getPointeeType();
556 else
557 T = getPointerType(RT->getPointeeType());
558 }
559 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000560 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000561 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
562 T = cast<ArrayType>(T)->getElementType();
563
564 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
565 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000566 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000567
Ken Dyck8b752f12010-01-27 17:10:57 +0000568 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000569}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000570
Chris Lattnera7674d82007-07-13 22:13:22 +0000571/// getTypeSize - Return the size of the specified type, in bits. This method
572/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000573///
574/// FIXME: Pointers into different addr spaces could have different sizes and
575/// alignment requirements: getPointerInfo should take an AddrSpace, this
576/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000577std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000578ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000579 uint64_t Width=0;
580 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000581 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000582#define TYPE(Class, Base)
583#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000584#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000585#define DEPENDENT_TYPE(Class, Base) case Type::Class:
586#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000587 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000588 break;
589
Chris Lattner692233e2007-07-13 22:27:08 +0000590 case Type::FunctionNoProto:
591 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000592 // GCC extension: alignof(function) = 32 bits
593 Width = 0;
594 Align = 32;
595 break;
596
Douglas Gregor72564e72009-02-26 23:50:07 +0000597 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000598 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000599 Width = 0;
600 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
601 break;
602
Steve Narofffb22d962007-08-30 01:06:46 +0000603 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000604 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner98be4942008-03-05 18:54:05 +0000606 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000607 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000608 Align = EltInfo.second;
609 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000610 }
Nate Begeman213541a2008-04-18 23:10:10 +0000611 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000612 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000613 const VectorType *VT = cast<VectorType>(T);
614 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
615 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000616 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000617 // If the alignment is not a power of 2, round up to the next power of 2.
618 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000619 if (VT->getNumElements() & (VT->getNumElements()-1)) {
620 Align = llvm::NextPowerOf2(Align);
621 Width = llvm::RoundUpToAlignment(Width, Align);
622 }
Chris Lattner030d8842007-07-19 22:06:24 +0000623 break;
624 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000625
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000626 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000627 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000628 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000629 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000630 // GCC extension: alignof(void) = 8 bits.
631 Width = 0;
632 Align = 8;
633 break;
634
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000635 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000636 Width = Target.getBoolWidth();
637 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000639 case BuiltinType::Char_S:
640 case BuiltinType::Char_U:
641 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000643 Width = Target.getCharWidth();
644 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000646 case BuiltinType::WChar:
647 Width = Target.getWCharWidth();
648 Align = Target.getWCharAlign();
649 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000650 case BuiltinType::Char16:
651 Width = Target.getChar16Width();
652 Align = Target.getChar16Align();
653 break;
654 case BuiltinType::Char32:
655 Width = Target.getChar32Width();
656 Align = Target.getChar32Align();
657 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000658 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000659 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000660 Width = Target.getShortWidth();
661 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000663 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000664 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000665 Width = Target.getIntWidth();
666 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000667 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000668 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000669 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000670 Width = Target.getLongWidth();
671 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000672 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000673 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000675 Width = Target.getLongLongWidth();
676 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000677 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000678 case BuiltinType::Int128:
679 case BuiltinType::UInt128:
680 Width = 128;
681 Align = 128; // int128_t is 128-bit aligned on all targets.
682 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000684 Width = Target.getFloatWidth();
685 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000688 Width = Target.getDoubleWidth();
689 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
691 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000692 Width = Target.getLongDoubleWidth();
693 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000694 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000695 case BuiltinType::NullPtr:
696 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
697 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000698 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000699 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000700 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000701 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000702 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000703 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000704 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000705 case Type::BlockPointer: {
706 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
707 Width = Target.getPointerWidth(AS);
708 Align = Target.getPointerAlign(AS);
709 break;
710 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000711 case Type::LValueReference:
712 case Type::RValueReference: {
713 // alignof and sizeof should never enter this code path here, so we go
714 // the pointer route.
715 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
716 Width = Target.getPointerWidth(AS);
717 Align = Target.getPointerAlign(AS);
718 break;
719 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000720 case Type::Pointer: {
721 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000722 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 Align = Target.getPointerAlign(AS);
724 break;
725 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000726 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000727 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000728 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000729 getTypeInfo(getPointerDiffType());
730 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000731 if (Pointee->isFunctionType())
732 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000733 Align = PtrDiffInfo.second;
734 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000735 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000736 case Type::Complex: {
737 // Complex types have the same alignment as their elements, but twice the
738 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000739 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000740 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000741 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000742 Align = EltInfo.second;
743 break;
744 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000745 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000746 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000747 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
748 Width = Layout.getSize();
749 Align = Layout.getAlignment();
750 break;
751 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000752 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000753 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000754 const TagType *TT = cast<TagType>(T);
755
756 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000757 Width = 1;
758 Align = 1;
759 break;
760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Daniel Dunbar1d751182008-11-08 05:48:37 +0000762 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000763 return getTypeInfo(ET->getDecl()->getIntegerType());
764
Daniel Dunbar1d751182008-11-08 05:48:37 +0000765 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000766 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
767 Width = Layout.getSize();
768 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000769 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000770 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000771
Chris Lattner9fcfe922009-10-22 05:17:15 +0000772 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000773 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
774 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000775
Chris Lattner9fcfe922009-10-22 05:17:15 +0000776 case Type::Elaborated:
777 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
778 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000779
Douglas Gregor18857642009-04-30 17:32:17 +0000780 case Type::Typedef: {
781 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000782 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000783 Align = std::max(Aligned->getMaxAlignment(),
784 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000785 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
786 } else
787 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000788 break;
Chris Lattner71763312008-04-06 22:05:18 +0000789 }
Douglas Gregor18857642009-04-30 17:32:17 +0000790
791 case Type::TypeOfExpr:
792 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
793 .getTypePtr());
794
795 case Type::TypeOf:
796 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
797
Anders Carlsson395b4752009-06-24 19:06:50 +0000798 case Type::Decltype:
799 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
800 .getTypePtr());
801
Douglas Gregor18857642009-04-30 17:32:17 +0000802 case Type::QualifiedName:
803 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Douglas Gregor18857642009-04-30 17:32:17 +0000805 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000806 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000807 "Cannot request the size of a dependent type");
808 // FIXME: this is likely to be wrong once we support template
809 // aliases, since a template alias could refer to a typedef that
810 // has an __aligned__ attribute on it.
811 return getTypeInfo(getCanonicalType(T));
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner464175b2007-07-18 17:52:12 +0000814 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000815 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000816}
817
Ken Dyckbdc601b2009-12-22 14:23:30 +0000818/// getTypeSizeInChars - Return the size of the specified type, in characters.
819/// This method does not work on incomplete types.
820CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000821 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000822}
823CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000824 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000825}
826
Ken Dyck16e20cc2010-01-26 17:25:18 +0000827/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000828/// characters. This method does not work on incomplete types.
829CharUnits ASTContext::getTypeAlignInChars(QualType T) {
830 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
831}
832CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
833 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
834}
835
Chris Lattner34ebde42009-01-27 18:08:34 +0000836/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
837/// type for the current target in bits. This can be different than the ABI
838/// alignment in cases where it is beneficial for performance to overalign
839/// a data type.
840unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
841 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000842
843 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000844 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000845 T = CT->getElementType().getTypePtr();
846 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
847 T->isSpecificBuiltinType(BuiltinType::LongLong))
848 return std::max(ABIAlign, (unsigned)getTypeSize(T));
849
Chris Lattner34ebde42009-01-27 18:08:34 +0000850 return ABIAlign;
851}
852
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000853static void CollectLocalObjCIvars(ASTContext *Ctx,
854 const ObjCInterfaceDecl *OI,
855 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000856 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
857 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000858 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000859 if (!IVDecl->isInvalidDecl())
860 Fields.push_back(cast<FieldDecl>(IVDecl));
861 }
862}
863
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000864void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
865 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
866 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
867 CollectObjCIvars(SuperClass, Fields);
868 CollectLocalObjCIvars(this, OI, Fields);
869}
870
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000871/// ShallowCollectObjCIvars -
872/// Collect all ivars, including those synthesized, in the current class.
873///
874void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000876 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
877 E = OI->ivar_end(); I != E; ++I) {
878 Ivars.push_back(*I);
879 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000880
881 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000882}
883
Fariborz Jahanian98200742009-05-12 18:14:29 +0000884void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
885 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000886 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
887 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000888 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
889 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Fariborz Jahanian98200742009-05-12 18:14:29 +0000891 // Also look into nested protocols.
892 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
893 E = PD->protocol_end(); P != E; ++P)
894 CollectProtocolSynthesizedIvars(*P, Ivars);
895}
896
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000897/// CollectNonClassIvars -
898/// This routine collects all other ivars which are not declared in the class.
899/// This includes synthesized ivars and those in class's implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000900///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000901void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000902 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000903 // Find ivars declared in class extension.
904 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
905 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
906 E = CDecl->ivar_end(); I != E; ++I) {
907 Ivars.push_back(*I);
908 }
909 }
910
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000911 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
912 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000913 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
914 Ivars.push_back(Ivar);
915 }
916 // Also look into interface's protocol list for properties declared
917 // in the protocol and whose ivars are synthesized.
918 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
919 PE = OI->protocol_end(); P != PE; ++P) {
920 ObjCProtocolDecl *PD = (*P);
921 CollectProtocolSynthesizedIvars(PD, Ivars);
922 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000923
924 // Also add any ivar defined in this class's implementation
925 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
926 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
927 E = ImplDecl->ivar_end(); I != E; ++I)
928 Ivars.push_back(*I);
929 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000930}
931
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000932/// CollectInheritedProtocols - Collect all protocols in current class and
933/// those inherited by it.
934void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000935 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
937 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
938 PE = OI->protocol_end(); P != PE; ++P) {
939 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000940 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000941 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
942 PE = Proto->protocol_end(); P != PE; ++P)
943 CollectInheritedProtocols(*P, Protocols);
944 }
945
946 // Categories of this Interface.
947 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
948 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
949 CollectInheritedProtocols(CDeclChain, Protocols);
950 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
951 while (SD) {
952 CollectInheritedProtocols(SD, Protocols);
953 SD = SD->getSuperClass();
954 }
955 return;
956 }
957 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
958 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
959 PE = OC->protocol_end(); P != PE; ++P) {
960 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000961 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000962 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
963 PE = Proto->protocol_end(); P != PE; ++P)
964 CollectInheritedProtocols(*P, Protocols);
965 }
966 return;
967 }
968 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
969 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
970 PE = OP->protocol_end(); P != PE; ++P) {
971 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000972 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000973 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
974 PE = Proto->protocol_end(); P != PE; ++P)
975 CollectInheritedProtocols(*P, Protocols);
976 }
977 return;
978 }
979}
980
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000981unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
982 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000983 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
984 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000985 if ((*I)->getPropertyIvarDecl())
986 ++count;
987
988 // Also look into nested protocols.
989 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
990 E = PD->protocol_end(); P != E; ++P)
991 count += CountProtocolSynthesizedIvars(*P);
992 return count;
993}
994
Mike Stump1eb44332009-09-09 15:08:12 +0000995unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000996 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000997 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
998 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000999 if ((*I)->getPropertyIvarDecl())
1000 ++count;
1001 }
1002 // Also look into interface's protocol list for properties declared
1003 // in the protocol and whose ivars are synthesized.
1004 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1005 PE = OI->protocol_end(); P != PE; ++P) {
1006 ObjCProtocolDecl *PD = (*P);
1007 count += CountProtocolSynthesizedIvars(PD);
1008 }
1009 return count;
1010}
1011
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001012/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1013ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1014 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1015 I = ObjCImpls.find(D);
1016 if (I != ObjCImpls.end())
1017 return cast<ObjCImplementationDecl>(I->second);
1018 return 0;
1019}
1020/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1021ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1022 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1023 I = ObjCImpls.find(D);
1024 if (I != ObjCImpls.end())
1025 return cast<ObjCCategoryImplDecl>(I->second);
1026 return 0;
1027}
1028
1029/// \brief Set the implementation of ObjCInterfaceDecl.
1030void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1031 ObjCImplementationDecl *ImplD) {
1032 assert(IFaceD && ImplD && "Passed null params");
1033 ObjCImpls[IFaceD] = ImplD;
1034}
1035/// \brief Set the implementation of ObjCCategoryDecl.
1036void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1037 ObjCCategoryImplDecl *ImplD) {
1038 assert(CatD && ImplD && "Passed null params");
1039 ObjCImpls[CatD] = ImplD;
1040}
1041
John McCalla93c9342009-12-07 02:54:59 +00001042/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001043///
John McCalla93c9342009-12-07 02:54:59 +00001044/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001045/// the TypeLoc wrappers.
1046///
1047/// \param T the type that will be the basis for type source info. This type
1048/// should refer to how the declarator was written in source code, not to
1049/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001050TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001051 unsigned DataSize) {
1052 if (!DataSize)
1053 DataSize = TypeLoc::getFullDataSizeForType(T);
1054 else
1055 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001056 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001057
John McCalla93c9342009-12-07 02:54:59 +00001058 TypeSourceInfo *TInfo =
1059 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1060 new (TInfo) TypeSourceInfo(T);
1061 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001062}
1063
John McCalla93c9342009-12-07 02:54:59 +00001064TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001065 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001066 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001067 DI->getTypeLoc().initialize(L);
1068 return DI;
1069}
1070
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001071/// getInterfaceLayoutImpl - Get or compute information about the
1072/// layout of the given interface.
1073///
1074/// \param Impl - If given, also include the layout of the interface's
1075/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001076const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001077ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1078 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001079 assert(!D->isForwardDecl() && "Invalid interface decl!");
1080
Devang Patel44a3dde2008-06-04 21:54:36 +00001081 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001082 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001083 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1084 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1085 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001086
Daniel Dunbar453addb2009-05-03 11:16:44 +00001087 // Add in synthesized ivar count if laying out an implementation.
1088 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001089 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001090 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001091 // entry. Note we can't cache this because we simply free all
1092 // entries later; however we shouldn't look up implementations
1093 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001094 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001095 return getObjCLayout(D, 0);
1096 }
1097
Mike Stump1eb44332009-09-09 15:08:12 +00001098 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001099 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1100 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Devang Patel44a3dde2008-06-04 21:54:36 +00001102 return *NewEntry;
1103}
1104
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001105const ASTRecordLayout &
1106ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1107 return getObjCLayout(D, 0);
1108}
1109
1110const ASTRecordLayout &
1111ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1112 return getObjCLayout(D->getClassInterface(), D);
1113}
1114
Devang Patel88a981b2007-11-01 19:11:01 +00001115/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001116/// specified record (struct/union/class), which indicates its size and field
1117/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001118const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001119 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001120 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001121
Chris Lattner464175b2007-07-18 17:52:12 +00001122 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001123 // Note that we can't save a reference to the entry because this function
1124 // is recursive.
1125 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001126 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001127
Mike Stump1eb44332009-09-09 15:08:12 +00001128 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001129 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001130 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Chris Lattner5d2a6302007-07-18 18:26:58 +00001132 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001133}
1134
Anders Carlssonf53df232009-12-07 04:35:11 +00001135const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001136 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001137 assert(RD && "Cannot get key function for forward declarations!");
1138
1139 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1140 if (!Entry)
1141 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1142 else
1143 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1144 "Key function changed!");
1145
1146 return Entry;
1147}
1148
Chris Lattnera7674d82007-07-13 22:13:22 +00001149//===----------------------------------------------------------------------===//
1150// Type creation/memoization methods
1151//===----------------------------------------------------------------------===//
1152
John McCall0953e762009-09-24 19:53:00 +00001153QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1154 unsigned Fast = Quals.getFastQualifiers();
1155 Quals.removeFastQualifiers();
1156
1157 // Check if we've already instantiated this type.
1158 llvm::FoldingSetNodeID ID;
1159 ExtQuals::Profile(ID, TypeNode, Quals);
1160 void *InsertPos = 0;
1161 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1162 assert(EQ->getQualifiers() == Quals);
1163 QualType T = QualType(EQ, Fast);
1164 return T;
1165 }
1166
John McCall6b304a02009-09-24 23:30:46 +00001167 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001168 ExtQualNodes.InsertNode(New, InsertPos);
1169 QualType T = QualType(New, Fast);
1170 return T;
1171}
1172
1173QualType ASTContext::getVolatileType(QualType T) {
1174 QualType CanT = getCanonicalType(T);
1175 if (CanT.isVolatileQualified()) return T;
1176
1177 QualifierCollector Quals;
1178 const Type *TypeNode = Quals.strip(T);
1179 Quals.addVolatile();
1180
1181 return getExtQualType(TypeNode, Quals);
1182}
1183
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001184QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001185 QualType CanT = getCanonicalType(T);
1186 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001187 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001188
John McCall0953e762009-09-24 19:53:00 +00001189 // If we are composing extended qualifiers together, merge together
1190 // into one ExtQuals node.
1191 QualifierCollector Quals;
1192 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
John McCall0953e762009-09-24 19:53:00 +00001194 // If this type already has an address space specified, it cannot get
1195 // another one.
1196 assert(!Quals.hasAddressSpace() &&
1197 "Type cannot be in multiple addr spaces!");
1198 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
John McCall0953e762009-09-24 19:53:00 +00001200 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001201}
1202
Chris Lattnerb7d25532009-02-18 22:53:11 +00001203QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001204 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001205 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001206 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001207 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001209 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001210 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001211 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001212 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1213 return getPointerType(ResultType);
1214 }
1215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216
John McCall0953e762009-09-24 19:53:00 +00001217 // If we are composing extended qualifiers together, merge together
1218 // into one ExtQuals node.
1219 QualifierCollector Quals;
1220 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
John McCall0953e762009-09-24 19:53:00 +00001222 // If this type already has an ObjCGC specified, it cannot get
1223 // another one.
1224 assert(!Quals.hasObjCGCAttr() &&
1225 "Type cannot have multiple ObjCGCs!");
1226 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
John McCall0953e762009-09-24 19:53:00 +00001228 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001229}
Chris Lattnera7674d82007-07-13 22:13:22 +00001230
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001231static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1232 bool AddNoReturn,
1233 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001234 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001235 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1236 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001237 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1238 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001239 if (ResultType == Pointee)
1240 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001241
1242 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001243 } else if (const BlockPointerType *BlockPointer
1244 = T->getAs<BlockPointerType>()) {
1245 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001246 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1247 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001248 if (ResultType == Pointee)
1249 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001250
1251 ResultType = Context.getBlockPointerType(ResultType);
1252 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1253 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001254 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001255
Douglas Gregor43c79c22009-12-09 00:47:37 +00001256 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001257 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1258 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001259 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001260 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001261 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001262 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1263 FPT->getNumArgs(), FPT->isVariadic(),
1264 FPT->getTypeQuals(),
1265 FPT->hasExceptionSpec(),
1266 FPT->hasAnyExceptionSpec(),
1267 FPT->getNumExceptions(),
1268 FPT->exception_begin(),
1269 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001270 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001271 } else
1272 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001273
1274 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1275}
1276
1277QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1278 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1279}
1280
1281QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1282 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001283}
1284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285/// getComplexType - Return the uniqued reference to the type for a complex
1286/// number with the specified element type.
1287QualType ASTContext::getComplexType(QualType T) {
1288 // Unique pointers, to guarantee there is only one pointer of a particular
1289 // structure.
1290 llvm::FoldingSetNodeID ID;
1291 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 void *InsertPos = 0;
1294 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1295 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 // If the pointee type isn't canonical, this won't be a canonical type either,
1298 // so fill in the canonical type field.
1299 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001300 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001301 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 // Get the new insert position for the node we care about.
1304 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001305 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 }
John McCall6b304a02009-09-24 23:30:46 +00001307 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 Types.push_back(New);
1309 ComplexTypes.InsertNode(New, InsertPos);
1310 return QualType(New, 0);
1311}
1312
Reid Spencer5f016e22007-07-11 17:01:13 +00001313/// getPointerType - Return the uniqued reference to the type for a pointer to
1314/// the specified type.
1315QualType ASTContext::getPointerType(QualType T) {
1316 // Unique pointers, to guarantee there is only one pointer of a particular
1317 // structure.
1318 llvm::FoldingSetNodeID ID;
1319 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 void *InsertPos = 0;
1322 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1323 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 // If the pointee type isn't canonical, this won't be a canonical type either,
1326 // so fill in the canonical type field.
1327 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001328 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001329 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // Get the new insert position for the node we care about.
1332 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001333 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 }
John McCall6b304a02009-09-24 23:30:46 +00001335 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 Types.push_back(New);
1337 PointerTypes.InsertNode(New, InsertPos);
1338 return QualType(New, 0);
1339}
1340
Mike Stump1eb44332009-09-09 15:08:12 +00001341/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001342/// a pointer to the specified block.
1343QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001344 assert(T->isFunctionType() && "block of function types only");
1345 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001346 // structure.
1347 llvm::FoldingSetNodeID ID;
1348 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Steve Naroff5618bd42008-08-27 16:04:49 +00001350 void *InsertPos = 0;
1351 if (BlockPointerType *PT =
1352 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1353 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001354
1355 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001356 // type either so fill in the canonical type field.
1357 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001358 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001359 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Steve Naroff5618bd42008-08-27 16:04:49 +00001361 // Get the new insert position for the node we care about.
1362 BlockPointerType *NewIP =
1363 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001364 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001365 }
John McCall6b304a02009-09-24 23:30:46 +00001366 BlockPointerType *New
1367 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001368 Types.push_back(New);
1369 BlockPointerTypes.InsertNode(New, InsertPos);
1370 return QualType(New, 0);
1371}
1372
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001373/// getLValueReferenceType - Return the uniqued reference to the type for an
1374/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001375QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 // Unique pointers, to guarantee there is only one pointer of a particular
1377 // structure.
1378 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001379 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001380
1381 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001382 if (LValueReferenceType *RT =
1383 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001385
John McCall54e14c42009-10-22 22:37:11 +00001386 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1387
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // If the referencee type isn't canonical, this won't be a canonical type
1389 // either, so fill in the canonical type field.
1390 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001391 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1392 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1393 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001394
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001396 LValueReferenceType *NewIP =
1397 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001398 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 }
1400
John McCall6b304a02009-09-24 23:30:46 +00001401 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001402 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1403 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001405 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001406
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001407 return QualType(New, 0);
1408}
1409
1410/// getRValueReferenceType - Return the uniqued reference to the type for an
1411/// rvalue reference to the specified type.
1412QualType ASTContext::getRValueReferenceType(QualType T) {
1413 // Unique pointers, to guarantee there is only one pointer of a particular
1414 // structure.
1415 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001416 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001417
1418 void *InsertPos = 0;
1419 if (RValueReferenceType *RT =
1420 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1421 return QualType(RT, 0);
1422
John McCall54e14c42009-10-22 22:37:11 +00001423 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1424
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001425 // If the referencee type isn't canonical, this won't be a canonical type
1426 // either, so fill in the canonical type field.
1427 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001428 if (InnerRef || !T.isCanonical()) {
1429 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1430 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001431
1432 // Get the new insert position for the node we care about.
1433 RValueReferenceType *NewIP =
1434 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1435 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1436 }
1437
John McCall6b304a02009-09-24 23:30:46 +00001438 RValueReferenceType *New
1439 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001440 Types.push_back(New);
1441 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 return QualType(New, 0);
1443}
1444
Sebastian Redlf30208a2009-01-24 21:16:55 +00001445/// getMemberPointerType - Return the uniqued reference to the type for a
1446/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001447QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001448 // Unique pointers, to guarantee there is only one pointer of a particular
1449 // structure.
1450 llvm::FoldingSetNodeID ID;
1451 MemberPointerType::Profile(ID, T, Cls);
1452
1453 void *InsertPos = 0;
1454 if (MemberPointerType *PT =
1455 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1456 return QualType(PT, 0);
1457
1458 // If the pointee or class type isn't canonical, this won't be a canonical
1459 // type either, so fill in the canonical type field.
1460 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001461 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001462 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1463
1464 // Get the new insert position for the node we care about.
1465 MemberPointerType *NewIP =
1466 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1467 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1468 }
John McCall6b304a02009-09-24 23:30:46 +00001469 MemberPointerType *New
1470 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001471 Types.push_back(New);
1472 MemberPointerTypes.InsertNode(New, InsertPos);
1473 return QualType(New, 0);
1474}
1475
Mike Stump1eb44332009-09-09 15:08:12 +00001476/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001477/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001478QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001479 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001480 ArrayType::ArraySizeModifier ASM,
1481 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001482 assert((EltTy->isDependentType() ||
1483 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001484 "Constant array of VLAs is illegal!");
1485
Chris Lattner38aeec72009-05-13 04:12:56 +00001486 // Convert the array size into a canonical width matching the pointer size for
1487 // the target.
1488 llvm::APInt ArySize(ArySizeIn);
1489 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001492 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001495 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001496 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 // If the element type isn't canonical, this won't be a canonical type either,
1500 // so fill in the canonical type field.
1501 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001502 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001503 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001504 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001506 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001507 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001508 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
John McCall6b304a02009-09-24 23:30:46 +00001511 ConstantArrayType *New = new(*this,TypeAlignment)
1512 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001513 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 Types.push_back(New);
1515 return QualType(New, 0);
1516}
1517
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001518/// getVariableArrayType - Returns a non-unique reference to the type for a
1519/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001520QualType ASTContext::getVariableArrayType(QualType EltTy,
1521 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001522 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001523 unsigned EltTypeQuals,
1524 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001525 // Since we don't unique expressions, it isn't possible to unique VLA's
1526 // that have an expression provided for their size.
1527
John McCall6b304a02009-09-24 23:30:46 +00001528 VariableArrayType *New = new(*this, TypeAlignment)
1529 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001530
1531 VariableArrayTypes.push_back(New);
1532 Types.push_back(New);
1533 return QualType(New, 0);
1534}
1535
Douglas Gregor898574e2008-12-05 23:32:09 +00001536/// getDependentSizedArrayType - Returns a non-unique reference to
1537/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001538/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001539QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1540 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001541 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001542 unsigned EltTypeQuals,
1543 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001544 assert((!NumElts || NumElts->isTypeDependent() ||
1545 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001546 "Size must be type- or value-dependent!");
1547
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001548 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001549 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001550 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001551
1552 if (NumElts) {
1553 // Dependently-sized array types that do not have a specified
1554 // number of elements will have their sizes deduced from an
1555 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001556 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1557 EltTypeQuals, NumElts);
1558
1559 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1560 }
1561
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001562 DependentSizedArrayType *New;
1563 if (Canon) {
1564 // We already have a canonical version of this array type; use it as
1565 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001566 New = new (*this, TypeAlignment)
1567 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1568 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001569 } else {
1570 QualType CanonEltTy = getCanonicalType(EltTy);
1571 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001572 New = new (*this, TypeAlignment)
1573 DependentSizedArrayType(*this, EltTy, QualType(),
1574 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001575
Douglas Gregor789b1f62010-02-04 18:10:26 +00001576 if (NumElts) {
1577 DependentSizedArrayType *CanonCheck
1578 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1579 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1580 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001581 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001582 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001583 } else {
1584 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1585 ASM, EltTypeQuals,
1586 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001587 New = new (*this, TypeAlignment)
1588 DependentSizedArrayType(*this, EltTy, Canon,
1589 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001590 }
1591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor898574e2008-12-05 23:32:09 +00001593 Types.push_back(New);
1594 return QualType(New, 0);
1595}
1596
Eli Friedmanc5773c42008-02-15 18:16:39 +00001597QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1598 ArrayType::ArraySizeModifier ASM,
1599 unsigned EltTypeQuals) {
1600 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001601 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001602
1603 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001604 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001605 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1606 return QualType(ATP, 0);
1607
1608 // If the element type isn't canonical, this won't be a canonical type
1609 // either, so fill in the canonical type field.
1610 QualType Canonical;
1611
John McCall467b27b2009-10-22 20:10:53 +00001612 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001613 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001614 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001615
1616 // Get the new insert position for the node we care about.
1617 IncompleteArrayType *NewIP =
1618 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001619 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001620 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001621
John McCall6b304a02009-09-24 23:30:46 +00001622 IncompleteArrayType *New = new (*this, TypeAlignment)
1623 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001624
1625 IncompleteArrayTypes.InsertNode(New, InsertPos);
1626 Types.push_back(New);
1627 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001628}
1629
Steve Naroff73322922007-07-18 18:00:27 +00001630/// getVectorType - Return the unique reference to a vector type of
1631/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001632QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1633 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Chris Lattnerf52ab252008-04-06 22:59:24 +00001636 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001637 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 // Check if we've already instantiated a vector of this type.
1640 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001641 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1642 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 void *InsertPos = 0;
1644 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1645 return QualType(VTP, 0);
1646
1647 // If the element type isn't canonical, this won't be a canonical type either,
1648 // so fill in the canonical type field.
1649 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001650 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1651 Canonical = getVectorType(getCanonicalType(vecType),
1652 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 // Get the new insert position for the node we care about.
1655 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001656 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 }
John McCall6b304a02009-09-24 23:30:46 +00001658 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001659 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 VectorTypes.InsertNode(New, InsertPos);
1661 Types.push_back(New);
1662 return QualType(New, 0);
1663}
1664
Nate Begeman213541a2008-04-18 23:10:10 +00001665/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001666/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001667QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001668 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Chris Lattnerf52ab252008-04-06 22:59:24 +00001670 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001671 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Steve Naroff73322922007-07-18 18:00:27 +00001673 // Check if we've already instantiated a vector of this type.
1674 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001675 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001676 void *InsertPos = 0;
1677 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1678 return QualType(VTP, 0);
1679
1680 // If the element type isn't canonical, this won't be a canonical type either,
1681 // so fill in the canonical type field.
1682 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001683 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001684 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Steve Naroff73322922007-07-18 18:00:27 +00001686 // Get the new insert position for the node we care about.
1687 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001688 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001689 }
John McCall6b304a02009-09-24 23:30:46 +00001690 ExtVectorType *New = new (*this, TypeAlignment)
1691 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001692 VectorTypes.InsertNode(New, InsertPos);
1693 Types.push_back(New);
1694 return QualType(New, 0);
1695}
1696
Mike Stump1eb44332009-09-09 15:08:12 +00001697QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001698 Expr *SizeExpr,
1699 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001700 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001701 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001702 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001704 void *InsertPos = 0;
1705 DependentSizedExtVectorType *Canon
1706 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1707 DependentSizedExtVectorType *New;
1708 if (Canon) {
1709 // We already have a canonical version of this array type; use it as
1710 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001711 New = new (*this, TypeAlignment)
1712 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1713 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001714 } else {
1715 QualType CanonVecTy = getCanonicalType(vecType);
1716 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001717 New = new (*this, TypeAlignment)
1718 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1719 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001720
1721 DependentSizedExtVectorType *CanonCheck
1722 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1723 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1724 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001725 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1726 } else {
1727 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1728 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001729 New = new (*this, TypeAlignment)
1730 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001731 }
1732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001734 Types.push_back(New);
1735 return QualType(New, 0);
1736}
1737
Douglas Gregor72564e72009-02-26 23:50:07 +00001738/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001739///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001740QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1741 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 // Unique functions, to guarantee there is only one function of a particular
1743 // structure.
1744 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001745 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001748 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001749 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001753 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001754 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001755 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001756 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001759 FunctionNoProtoType *NewIP =
1760 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001761 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
John McCall6b304a02009-09-24 23:30:46 +00001764 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001765 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001767 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 return QualType(New, 0);
1769}
1770
1771/// getFunctionType - Return a normal function type with a typed argument
1772/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001773QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001774 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001775 unsigned TypeQuals, bool hasExceptionSpec,
1776 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001777 const QualType *ExArray, bool NoReturn,
1778 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // Unique functions, to guarantee there is only one function of a particular
1780 // structure.
1781 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001782 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001783 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001784 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001785
1786 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001787 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001788 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001790
1791 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001792 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001794 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 isCanonical = false;
1796
1797 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001798 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001800 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 llvm::SmallVector<QualType, 16> CanonicalArgs;
1802 CanonicalArgs.reserve(NumArgs);
1803 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001804 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001805
Chris Lattnerf52ab252008-04-06 22:59:24 +00001806 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001807 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001808 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001809 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001810 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001811
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001813 FunctionProtoType *NewIP =
1814 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001815 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001817
Douglas Gregor72564e72009-02-26 23:50:07 +00001818 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001819 // for two variable size arrays (for parameter and exception types) at the
1820 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001821 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001822 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1823 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001824 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001825 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001826 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001827 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001829 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 return QualType(FTP, 0);
1831}
1832
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001833/// getTypeDeclType - Return the unique reference to the type for the
1834/// specified type declaration.
John McCall19c85762010-02-16 03:57:14 +00001835QualType ASTContext::getTypeDeclType(const TypeDecl *Decl,
1836 const TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001837 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001838 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
John McCall19c85762010-02-16 03:57:14 +00001840 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001841 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001842 else if (isa<TemplateTypeParmDecl>(Decl)) {
1843 assert(false && "Template type parameter types are always available.");
John McCall19c85762010-02-16 03:57:14 +00001844 } else if (const ObjCInterfaceDecl *ObjCInterface
Mike Stump9fdbab32009-07-31 02:02:20 +00001845 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001846 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001847
John McCall19c85762010-02-16 03:57:14 +00001848 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001849 if (PrevDecl)
1850 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001851 else
John McCall6b304a02009-09-24 23:30:46 +00001852 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001853 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001854 if (PrevDecl)
1855 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001856 else
John McCall6b304a02009-09-24 23:30:46 +00001857 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001858 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001859 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1860 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001861 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001862 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001863
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001864 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001865 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001866}
1867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868/// getTypedefType - Return the unique reference to the type for the
1869/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001870QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Chris Lattnerf52ab252008-04-06 22:59:24 +00001873 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001874 Decl->TypeForDecl = new(*this, TypeAlignment)
1875 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 Types.push_back(Decl->TypeForDecl);
1877 return QualType(Decl->TypeForDecl, 0);
1878}
1879
John McCall49a832b2009-10-18 09:09:24 +00001880/// \brief Retrieve a substitution-result type.
1881QualType
1882ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1883 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001884 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001885 && "replacement types must always be canonical");
1886
1887 llvm::FoldingSetNodeID ID;
1888 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1889 void *InsertPos = 0;
1890 SubstTemplateTypeParmType *SubstParm
1891 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1892
1893 if (!SubstParm) {
1894 SubstParm = new (*this, TypeAlignment)
1895 SubstTemplateTypeParmType(Parm, Replacement);
1896 Types.push_back(SubstParm);
1897 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1898 }
1899
1900 return QualType(SubstParm, 0);
1901}
1902
Douglas Gregorfab9d672009-02-05 23:33:38 +00001903/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001904/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001905/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001906QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001907 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001908 IdentifierInfo *Name) {
1909 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001910 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001911 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001912 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001913 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1914
1915 if (TypeParm)
1916 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001918 if (Name) {
1919 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001920 TypeParm = new (*this, TypeAlignment)
1921 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001922
1923 TemplateTypeParmType *TypeCheck
1924 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1925 assert(!TypeCheck && "Template type parameter canonical type broken");
1926 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001927 } else
John McCall6b304a02009-09-24 23:30:46 +00001928 TypeParm = new (*this, TypeAlignment)
1929 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001930
1931 Types.push_back(TypeParm);
1932 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1933
1934 return QualType(TypeParm, 0);
1935}
1936
Mike Stump1eb44332009-09-09 15:08:12 +00001937QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001938ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001939 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001940 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001941 unsigned NumArgs = Args.size();
1942
John McCall833ca992009-10-29 08:12:44 +00001943 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1944 ArgVec.reserve(NumArgs);
1945 for (unsigned i = 0; i != NumArgs; ++i)
1946 ArgVec.push_back(Args[i].getArgument());
1947
1948 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1949}
1950
1951QualType
1952ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001953 const TemplateArgument *Args,
1954 unsigned NumArgs,
1955 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001956 if (!Canon.isNull())
1957 Canon = getCanonicalType(Canon);
1958 else {
1959 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001960 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1961 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1962 CanonArgs.reserve(NumArgs);
1963 for (unsigned I = 0; I != NumArgs; ++I)
1964 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1965
1966 // Determine whether this canonical template specialization type already
1967 // exists.
1968 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001969 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001970 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001971
1972 void *InsertPos = 0;
1973 TemplateSpecializationType *Spec
1974 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregor1275ae02009-07-28 23:00:59 +00001976 if (!Spec) {
1977 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001978 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001979 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001980 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001981 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001982 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001983 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001984 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001985 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Douglas Gregorb88e8882009-07-30 17:40:51 +00001988 if (Canon.isNull())
1989 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001990 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001991 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001992 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001993
Douglas Gregor1275ae02009-07-28 23:00:59 +00001994 // Allocate the (non-canonical) template specialization type, but don't
1995 // try to unique it: these types typically have location information that
1996 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001997 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001998 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001999 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002000 TemplateSpecializationType *Spec
2001 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002002 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Douglas Gregor55f6b142009-02-09 18:46:07 +00002004 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002005 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002006}
2007
Mike Stump1eb44332009-09-09 15:08:12 +00002008QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00002009ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00002010 QualType NamedType) {
2011 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00002012 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002013
2014 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002015 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00002016 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2017 if (T)
2018 return QualType(T, 0);
2019
Douglas Gregor789b1f62010-02-04 18:10:26 +00002020 QualType Canon = NamedType;
2021 if (!Canon.isCanonical()) {
2022 Canon = getCanonicalType(NamedType);
2023 QualifiedNameType *CheckT
2024 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2025 assert(!CheckT && "Qualified name canonical type broken");
2026 (void)CheckT;
2027 }
2028
2029 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002030 Types.push_back(T);
2031 QualifiedNameTypes.InsertNode(T, InsertPos);
2032 return QualType(T, 0);
2033}
2034
Mike Stump1eb44332009-09-09 15:08:12 +00002035QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002036 const IdentifierInfo *Name,
2037 QualType Canon) {
2038 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2039
2040 if (Canon.isNull()) {
2041 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2042 if (CanonNNS != NNS)
2043 Canon = getTypenameType(CanonNNS, Name);
2044 }
2045
2046 llvm::FoldingSetNodeID ID;
2047 TypenameType::Profile(ID, NNS, Name);
2048
2049 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002050 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002051 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2052 if (T)
2053 return QualType(T, 0);
2054
2055 T = new (*this) TypenameType(NNS, Name, Canon);
2056 Types.push_back(T);
2057 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002058 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002059}
2060
Mike Stump1eb44332009-09-09 15:08:12 +00002061QualType
2062ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002063 const TemplateSpecializationType *TemplateId,
2064 QualType Canon) {
2065 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2066
Douglas Gregor789b1f62010-02-04 18:10:26 +00002067 llvm::FoldingSetNodeID ID;
2068 TypenameType::Profile(ID, NNS, TemplateId);
2069
2070 void *InsertPos = 0;
2071 TypenameType *T
2072 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2073 if (T)
2074 return QualType(T, 0);
2075
Douglas Gregor17343172009-04-01 00:28:59 +00002076 if (Canon.isNull()) {
2077 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2078 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2079 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2080 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002081 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002082 assert(CanonTemplateId &&
2083 "Canonical type must also be a template specialization type");
2084 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2085 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002086
2087 TypenameType *CheckT
2088 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2089 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002090 }
2091
Douglas Gregor17343172009-04-01 00:28:59 +00002092 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2093 Types.push_back(T);
2094 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002095 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002096}
2097
John McCall7da24312009-09-05 00:15:47 +00002098QualType
2099ASTContext::getElaboratedType(QualType UnderlyingType,
2100 ElaboratedType::TagKind Tag) {
2101 llvm::FoldingSetNodeID ID;
2102 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
John McCall7da24312009-09-05 00:15:47 +00002104 void *InsertPos = 0;
2105 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2106 if (T)
2107 return QualType(T, 0);
2108
Douglas Gregor789b1f62010-02-04 18:10:26 +00002109 QualType Canon = UnderlyingType;
2110 if (!Canon.isCanonical()) {
2111 Canon = getCanonicalType(Canon);
2112 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2113 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2114 }
John McCall7da24312009-09-05 00:15:47 +00002115
2116 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2117 Types.push_back(T);
2118 ElaboratedTypes.InsertNode(T, InsertPos);
2119 return QualType(T, 0);
2120}
2121
Chris Lattner88cb27a2008-04-07 04:56:42 +00002122/// CmpProtocolNames - Comparison predicate for sorting protocols
2123/// alphabetically.
2124static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2125 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002126 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002127}
2128
John McCall54e14c42009-10-22 22:37:11 +00002129static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2130 unsigned NumProtocols) {
2131 if (NumProtocols == 0) return true;
2132
2133 for (unsigned i = 1; i != NumProtocols; ++i)
2134 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2135 return false;
2136 return true;
2137}
2138
2139static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002140 unsigned &NumProtocols) {
2141 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Chris Lattner88cb27a2008-04-07 04:56:42 +00002143 // Sort protocols, keyed by name.
2144 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2145
2146 // Remove duplicates.
2147 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2148 NumProtocols = ProtocolsEnd-Protocols;
2149}
2150
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002151/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2152/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002153QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002154 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002155 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002156 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002157 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002158
2159 void *InsertPos = 0;
2160 if (ObjCObjectPointerType *QT =
2161 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2162 return QualType(QT, 0);
2163
John McCall54e14c42009-10-22 22:37:11 +00002164 // Sort the protocol list alphabetically to canonicalize it.
2165 QualType Canonical;
2166 if (!InterfaceT.isCanonical() ||
2167 !areSortedAndUniqued(Protocols, NumProtocols)) {
2168 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2169 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2170 unsigned UniqueCount = NumProtocols;
2171
2172 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2173 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2174
2175 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2176 &Sorted[0], UniqueCount);
2177 } else {
2178 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2179 Protocols, NumProtocols);
2180 }
2181
2182 // Regenerate InsertPos.
2183 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2184 }
2185
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002186 // No match.
2187 unsigned Size = sizeof(ObjCObjectPointerType)
2188 + NumProtocols * sizeof(ObjCProtocolDecl *);
2189 void *Mem = Allocate(Size, TypeAlignment);
2190 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2191 InterfaceT,
2192 Protocols,
2193 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002195 Types.push_back(QType);
2196 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2197 return QualType(QType, 0);
2198}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002199
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002200/// getObjCInterfaceType - Return the unique reference to the type for the
2201/// specified ObjC interface decl. The list of protocols is optional.
2202QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002203 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002204 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002205 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002207 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002208 if (ObjCInterfaceType *QT =
2209 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002210 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
John McCall54e14c42009-10-22 22:37:11 +00002212 // Sort the protocol list alphabetically to canonicalize it.
2213 QualType Canonical;
2214 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2215 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2216 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2217
2218 unsigned UniqueCount = NumProtocols;
2219 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2220
2221 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2222
2223 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2224 }
2225
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002226 unsigned Size = sizeof(ObjCInterfaceType)
2227 + NumProtocols * sizeof(ObjCProtocolDecl *);
2228 void *Mem = Allocate(Size, TypeAlignment);
2229 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2230 const_cast<ObjCInterfaceDecl*>(Decl),
2231 Protocols,
2232 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002233
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002234 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002235 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002236 return QualType(QType, 0);
2237}
2238
Douglas Gregor72564e72009-02-26 23:50:07 +00002239/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2240/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002241/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002242/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002243/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002244QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002245 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002246 if (tofExpr->isTypeDependent()) {
2247 llvm::FoldingSetNodeID ID;
2248 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregorb1975722009-07-30 23:18:24 +00002250 void *InsertPos = 0;
2251 DependentTypeOfExprType *Canon
2252 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2253 if (Canon) {
2254 // We already have a "canonical" version of an identical, dependent
2255 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002256 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002257 QualType((TypeOfExprType*)Canon, 0));
2258 }
2259 else {
2260 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002261 Canon
2262 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002263 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2264 toe = Canon;
2265 }
2266 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002267 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002268 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002269 }
Steve Naroff9752f252007-08-01 18:02:17 +00002270 Types.push_back(toe);
2271 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002272}
2273
Steve Naroff9752f252007-08-01 18:02:17 +00002274/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2275/// TypeOfType AST's. The only motivation to unique these nodes would be
2276/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002277/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002278/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002279QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002280 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002281 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002282 Types.push_back(tot);
2283 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002284}
2285
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002286/// getDecltypeForExpr - Given an expr, will return the decltype for that
2287/// expression, according to the rules in C++0x [dcl.type.simple]p4
2288static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002289 if (e->isTypeDependent())
2290 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002292 // If e is an id expression or a class member access, decltype(e) is defined
2293 // as the type of the entity named by e.
2294 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2295 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2296 return VD->getType();
2297 }
2298 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2299 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2300 return FD->getType();
2301 }
2302 // If e is a function call or an invocation of an overloaded operator,
2303 // (parentheses around e are ignored), decltype(e) is defined as the
2304 // return type of that function.
2305 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2306 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002308 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002309
2310 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002311 // defined as T&, otherwise decltype(e) is defined as T.
2312 if (e->isLvalue(Context) == Expr::LV_Valid)
2313 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002315 return T;
2316}
2317
Anders Carlsson395b4752009-06-24 19:06:50 +00002318/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2319/// DecltypeType AST's. The only motivation to unique these nodes would be
2320/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002321/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002322/// on canonical type's (which are always unique).
2323QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002324 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002325 if (e->isTypeDependent()) {
2326 llvm::FoldingSetNodeID ID;
2327 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002329 void *InsertPos = 0;
2330 DependentDecltypeType *Canon
2331 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2332 if (Canon) {
2333 // We already have a "canonical" version of an equivalent, dependent
2334 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002335 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002336 QualType((DecltypeType*)Canon, 0));
2337 }
2338 else {
2339 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002340 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002341 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2342 dt = Canon;
2343 }
2344 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002345 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002346 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002347 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002348 Types.push_back(dt);
2349 return QualType(dt, 0);
2350}
2351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352/// getTagDeclType - Return the unique reference to the type for the
2353/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002354QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002355 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002356 // FIXME: What is the design on getTagDeclType when it requires casting
2357 // away const? mutable?
2358 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002359}
2360
Mike Stump1eb44332009-09-09 15:08:12 +00002361/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2362/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2363/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002364CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002365 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002366}
2367
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002368/// getSignedWCharType - Return the type of "signed wchar_t".
2369/// Used when in C++, as a GCC extension.
2370QualType ASTContext::getSignedWCharType() const {
2371 // FIXME: derive from "Target" ?
2372 return WCharTy;
2373}
2374
2375/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2376/// Used when in C++, as a GCC extension.
2377QualType ASTContext::getUnsignedWCharType() const {
2378 // FIXME: derive from "Target" ?
2379 return UnsignedIntTy;
2380}
2381
Chris Lattner8b9023b2007-07-13 03:05:23 +00002382/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2383/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2384QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002385 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002386}
2387
Chris Lattnere6327742008-04-02 05:18:44 +00002388//===----------------------------------------------------------------------===//
2389// Type Operators
2390//===----------------------------------------------------------------------===//
2391
John McCall54e14c42009-10-22 22:37:11 +00002392CanQualType ASTContext::getCanonicalParamType(QualType T) {
2393 // Push qualifiers into arrays, and then discard any remaining
2394 // qualifiers.
2395 T = getCanonicalType(T);
2396 const Type *Ty = T.getTypePtr();
2397
2398 QualType Result;
2399 if (isa<ArrayType>(Ty)) {
2400 Result = getArrayDecayedType(QualType(Ty,0));
2401 } else if (isa<FunctionType>(Ty)) {
2402 Result = getPointerType(QualType(Ty, 0));
2403 } else {
2404 Result = QualType(Ty, 0);
2405 }
2406
2407 return CanQualType::CreateUnsafe(Result);
2408}
2409
Chris Lattner77c96472008-04-06 22:41:35 +00002410/// getCanonicalType - Return the canonical (structural) type corresponding to
2411/// the specified potentially non-canonical type. The non-canonical version
2412/// of a type may have many "decorated" versions of types. Decorators can
2413/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2414/// to be free of any of these, allowing two canonical types to be compared
2415/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002416CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002417 QualifierCollector Quals;
2418 const Type *Ptr = Quals.strip(T);
2419 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002420
John McCall0953e762009-09-24 19:53:00 +00002421 // The canonical internal type will be the canonical type *except*
2422 // that we push type qualifiers down through array types.
2423
2424 // If there are no new qualifiers to push down, stop here.
2425 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002426 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002427
John McCall0953e762009-09-24 19:53:00 +00002428 // If the type qualifiers are on an array type, get the canonical
2429 // type of the array with the qualifiers applied to the element
2430 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002431 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2432 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002433 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002435 // Get the canonical version of the element with the extra qualifiers on it.
2436 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002437 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002438 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002439
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002440 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002441 return CanQualType::CreateUnsafe(
2442 getConstantArrayType(NewEltTy, CAT->getSize(),
2443 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002444 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002445 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002446 return CanQualType::CreateUnsafe(
2447 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002448 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor898574e2008-12-05 23:32:09 +00002450 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002451 return CanQualType::CreateUnsafe(
2452 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002453 DSAT->getSizeExpr() ?
2454 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002455 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002456 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002457 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002458
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002459 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002460 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002461 VAT->getSizeExpr() ?
2462 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002463 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002464 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002465 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002466}
2467
Chandler Carruth28e318c2009-12-29 07:16:59 +00002468QualType ASTContext::getUnqualifiedArrayType(QualType T,
2469 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002470 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002471 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002472 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002473 }
2474
Chandler Carruth28e318c2009-12-29 07:16:59 +00002475 const ArrayType *AT = cast<ArrayType>(T);
2476 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002477 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002478 if (Elt == UnqualElt)
2479 return T;
2480
2481 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2482 return getConstantArrayType(UnqualElt, CAT->getSize(),
2483 CAT->getSizeModifier(), 0);
2484 }
2485
2486 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2487 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2488 }
2489
2490 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2491 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2492 DSAT->getSizeModifier(), 0,
2493 SourceRange());
2494}
2495
John McCall80ad16f2009-11-24 18:42:40 +00002496DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2497 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2498 return TD->getDeclName();
2499
2500 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2501 if (DTN->isIdentifier()) {
2502 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2503 } else {
2504 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2505 }
2506 }
2507
John McCall0bd6feb2009-12-02 08:04:21 +00002508 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2509 assert(Storage);
2510 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002511}
2512
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002513TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2514 // If this template name refers to a template, the canonical
2515 // template name merely stores the template itself.
2516 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002517 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002518
John McCall0bd6feb2009-12-02 08:04:21 +00002519 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002521 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2522 assert(DTN && "Non-dependent template names must refer to template decls.");
2523 return DTN->CanonicalTemplateName;
2524}
2525
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002526bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2527 X = getCanonicalTemplateName(X);
2528 Y = getCanonicalTemplateName(Y);
2529 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2530}
2531
Mike Stump1eb44332009-09-09 15:08:12 +00002532TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002533ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2534 switch (Arg.getKind()) {
2535 case TemplateArgument::Null:
2536 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregor1275ae02009-07-28 23:00:59 +00002538 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002539 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Douglas Gregor1275ae02009-07-28 23:00:59 +00002541 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002542 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Douglas Gregor788cd062009-11-11 01:00:40 +00002544 case TemplateArgument::Template:
2545 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2546
Douglas Gregor1275ae02009-07-28 23:00:59 +00002547 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002548 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002549 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Douglas Gregor1275ae02009-07-28 23:00:59 +00002551 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002552 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002553
Douglas Gregor1275ae02009-07-28 23:00:59 +00002554 case TemplateArgument::Pack: {
2555 // FIXME: Allocate in ASTContext
2556 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2557 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002558 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002559 AEnd = Arg.pack_end();
2560 A != AEnd; (void)++A, ++Idx)
2561 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Douglas Gregor1275ae02009-07-28 23:00:59 +00002563 TemplateArgument Result;
2564 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2565 return Result;
2566 }
2567 }
2568
2569 // Silence GCC warning
2570 assert(false && "Unhandled template argument kind");
2571 return TemplateArgument();
2572}
2573
Douglas Gregord57959a2009-03-27 23:10:48 +00002574NestedNameSpecifier *
2575ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002576 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002577 return 0;
2578
2579 switch (NNS->getKind()) {
2580 case NestedNameSpecifier::Identifier:
2581 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002582 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002583 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2584 NNS->getAsIdentifier());
2585
2586 case NestedNameSpecifier::Namespace:
2587 // A namespace is canonical; build a nested-name-specifier with
2588 // this namespace and no prefix.
2589 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2590
2591 case NestedNameSpecifier::TypeSpec:
2592 case NestedNameSpecifier::TypeSpecWithTemplate: {
2593 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002594 return NestedNameSpecifier::Create(*this, 0,
2595 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002596 T.getTypePtr());
2597 }
2598
2599 case NestedNameSpecifier::Global:
2600 // The global specifier is canonical and unique.
2601 return NNS;
2602 }
2603
2604 // Required to silence a GCC warning
2605 return 0;
2606}
2607
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002608
2609const ArrayType *ASTContext::getAsArrayType(QualType T) {
2610 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002611 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002612 // Handle the common positive case fast.
2613 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2614 return AT;
2615 }
Mike Stump1eb44332009-09-09 15:08:12 +00002616
John McCall0953e762009-09-24 19:53:00 +00002617 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002618 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002619 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002620 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002621
John McCall0953e762009-09-24 19:53:00 +00002622 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002623 // implements C99 6.7.3p8: "If the specification of an array type includes
2624 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002626 // If we get here, we either have type qualifiers on the type, or we have
2627 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002628 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002629
John McCall0953e762009-09-24 19:53:00 +00002630 QualifierCollector Qs;
2631 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002633 // If we have a simple case, just return now.
2634 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002635 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002636 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002637
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002638 // Otherwise, we have an array and we have qualifiers on it. Push the
2639 // qualifiers into the array element type and return a new array type.
2640 // Get the canonical version of the element with the extra qualifiers on it.
2641 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002642 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002644 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2645 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2646 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002647 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002648 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2649 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2650 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002651 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002652
Mike Stump1eb44332009-09-09 15:08:12 +00002653 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002654 = dyn_cast<DependentSizedArrayType>(ATy))
2655 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002656 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002657 DSAT->getSizeExpr() ?
2658 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002659 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002660 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002661 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002663 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002664 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002665 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002666 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002667 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002668 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002669 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002670}
2671
2672
Chris Lattnere6327742008-04-02 05:18:44 +00002673/// getArrayDecayedType - Return the properly qualified result of decaying the
2674/// specified array type to a pointer. This operation is non-trivial when
2675/// handling typedefs etc. The canonical type of "T" must be an array type,
2676/// this returns a pointer to a properly qualified element of the array.
2677///
2678/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2679QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002680 // Get the element type with 'getAsArrayType' so that we don't lose any
2681 // typedefs in the element type of the array. This also handles propagation
2682 // of type qualifiers from the array type into the element type if present
2683 // (C99 6.7.3p8).
2684 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2685 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002687 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002688
2689 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002690 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002691}
2692
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002693QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002694 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002695 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002696 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002697 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2698 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002699 } else {
John McCall0953e762009-09-24 19:53:00 +00002700 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002701 }
2702 }
2703}
2704
Anders Carlssonfbbce492009-09-25 01:23:32 +00002705QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2706 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Anders Carlssonfbbce492009-09-25 01:23:32 +00002708 if (const ArrayType *AT = getAsArrayType(ElemTy))
2709 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Anders Carlsson6183a992008-12-21 03:44:36 +00002711 return ElemTy;
2712}
2713
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002714/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002715uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002716ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2717 uint64_t ElementCount = 1;
2718 do {
2719 ElementCount *= CA->getSize().getZExtValue();
2720 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2721 } while (CA);
2722 return ElementCount;
2723}
2724
Reid Spencer5f016e22007-07-11 17:01:13 +00002725/// getFloatingRank - Return a relative rank for floating point types.
2726/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002727static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002728 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002730
John McCall183700f2009-09-21 23:43:11 +00002731 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2732 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002733 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 case BuiltinType::Float: return FloatRank;
2735 case BuiltinType::Double: return DoubleRank;
2736 case BuiltinType::LongDouble: return LongDoubleRank;
2737 }
2738}
2739
Mike Stump1eb44332009-09-09 15:08:12 +00002740/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2741/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002742/// 'typeDomain' is a real floating point or complex type.
2743/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002744QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2745 QualType Domain) const {
2746 FloatingRank EltRank = getFloatingRank(Size);
2747 if (Domain->isComplexType()) {
2748 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002749 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002750 case FloatRank: return FloatComplexTy;
2751 case DoubleRank: return DoubleComplexTy;
2752 case LongDoubleRank: return LongDoubleComplexTy;
2753 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 }
Chris Lattner1361b112008-04-06 23:58:54 +00002755
2756 assert(Domain->isRealFloatingType() && "Unknown domain!");
2757 switch (EltRank) {
2758 default: assert(0 && "getFloatingRank(): illegal value for rank");
2759 case FloatRank: return FloatTy;
2760 case DoubleRank: return DoubleTy;
2761 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002762 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002763}
2764
Chris Lattner7cfeb082008-04-06 23:55:33 +00002765/// getFloatingTypeOrder - Compare the rank of the two specified floating
2766/// point types, ignoring the domain of the type (i.e. 'double' ==
2767/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002768/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002769int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2770 FloatingRank LHSR = getFloatingRank(LHS);
2771 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Chris Lattnera75cea32008-04-06 23:38:49 +00002773 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002774 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002775 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002776 return 1;
2777 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002778}
2779
Chris Lattnerf52ab252008-04-06 22:59:24 +00002780/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2781/// routine will assert if passed a built-in type that isn't an integer or enum,
2782/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002783unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002784 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002785 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002786 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002787
Eli Friedmana3426752009-07-05 23:44:27 +00002788 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2789 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2790
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002791 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2792 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2793
2794 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2795 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2796
Chris Lattnerf52ab252008-04-06 22:59:24 +00002797 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002798 default: assert(0 && "getIntegerRank(): not a built-in integer");
2799 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002800 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002801 case BuiltinType::Char_S:
2802 case BuiltinType::Char_U:
2803 case BuiltinType::SChar:
2804 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002805 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002806 case BuiltinType::Short:
2807 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002808 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002809 case BuiltinType::Int:
2810 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002811 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002812 case BuiltinType::Long:
2813 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002814 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002815 case BuiltinType::LongLong:
2816 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002817 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002818 case BuiltinType::Int128:
2819 case BuiltinType::UInt128:
2820 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002821 }
2822}
2823
Eli Friedman04e83572009-08-20 04:21:42 +00002824/// \brief Whether this is a promotable bitfield reference according
2825/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2826///
2827/// \returns the type this bit-field will promote to, or NULL if no
2828/// promotion occurs.
2829QualType ASTContext::isPromotableBitField(Expr *E) {
2830 FieldDecl *Field = E->getBitField();
2831 if (!Field)
2832 return QualType();
2833
2834 QualType FT = Field->getType();
2835
2836 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2837 uint64_t BitWidth = BitWidthAP.getZExtValue();
2838 uint64_t IntSize = getTypeSize(IntTy);
2839 // GCC extension compatibility: if the bit-field size is less than or equal
2840 // to the size of int, it gets promoted no matter what its type is.
2841 // For instance, unsigned long bf : 4 gets promoted to signed int.
2842 if (BitWidth < IntSize)
2843 return IntTy;
2844
2845 if (BitWidth == IntSize)
2846 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2847
2848 // Types bigger than int are not subject to promotions, and therefore act
2849 // like the base type.
2850 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2851 // is ridiculous.
2852 return QualType();
2853}
2854
Eli Friedmana95d7572009-08-19 07:44:53 +00002855/// getPromotedIntegerType - Returns the type that Promotable will
2856/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2857/// integer type.
2858QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2859 assert(!Promotable.isNull());
2860 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002861 if (const EnumType *ET = Promotable->getAs<EnumType>())
2862 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002863 if (Promotable->isSignedIntegerType())
2864 return IntTy;
2865 uint64_t PromotableSize = getTypeSize(Promotable);
2866 uint64_t IntSize = getTypeSize(IntTy);
2867 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2868 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2869}
2870
Mike Stump1eb44332009-09-09 15:08:12 +00002871/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002872/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002873/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002874int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002875 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2876 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002877 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Chris Lattnerf52ab252008-04-06 22:59:24 +00002879 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2880 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Chris Lattner7cfeb082008-04-06 23:55:33 +00002882 unsigned LHSRank = getIntegerRank(LHSC);
2883 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Chris Lattner7cfeb082008-04-06 23:55:33 +00002885 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2886 if (LHSRank == RHSRank) return 0;
2887 return LHSRank > RHSRank ? 1 : -1;
2888 }
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Chris Lattner7cfeb082008-04-06 23:55:33 +00002890 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2891 if (LHSUnsigned) {
2892 // If the unsigned [LHS] type is larger, return it.
2893 if (LHSRank >= RHSRank)
2894 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Chris Lattner7cfeb082008-04-06 23:55:33 +00002896 // If the signed type can represent all values of the unsigned type, it
2897 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002898 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002899 return -1;
2900 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002901
Chris Lattner7cfeb082008-04-06 23:55:33 +00002902 // If the unsigned [RHS] type is larger, return it.
2903 if (RHSRank >= LHSRank)
2904 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002905
Chris Lattner7cfeb082008-04-06 23:55:33 +00002906 // If the signed type can represent all values of the unsigned type, it
2907 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002908 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002909 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002910}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002911
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002912static RecordDecl *
2913CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2914 SourceLocation L, IdentifierInfo *Id) {
2915 if (Ctx.getLangOptions().CPlusPlus)
2916 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2917 else
2918 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2919}
2920
Mike Stump1eb44332009-09-09 15:08:12 +00002921// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002922QualType ASTContext::getCFConstantStringType() {
2923 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002924 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002925 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2926 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002927 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002928
Anders Carlssonf06273f2007-11-19 00:25:30 +00002929 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Anders Carlsson71993dd2007-08-17 05:31:46 +00002931 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002932 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002933 // int flags;
2934 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002935 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002936 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002937 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002938 FieldTypes[3] = LongTy;
2939
Anders Carlsson71993dd2007-08-17 05:31:46 +00002940 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002941 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002942 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002943 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002944 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002945 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002946 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002947 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002948 }
2949
Douglas Gregor838db382010-02-11 01:19:42 +00002950 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002951 }
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Anders Carlsson71993dd2007-08-17 05:31:46 +00002953 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002954}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002955
Douglas Gregor319ac892009-04-23 22:29:11 +00002956void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002957 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002958 assert(Rec && "Invalid CFConstantStringType");
2959 CFConstantStringTypeDecl = Rec->getDecl();
2960}
2961
Mike Stump1eb44332009-09-09 15:08:12 +00002962QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002963 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002964 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002965 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2966 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002967 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002969 QualType FieldTypes[] = {
2970 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002971 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002972 getPointerType(UnsignedLongTy),
2973 getConstantArrayType(UnsignedLongTy,
2974 llvm::APInt(32, 5), ArrayType::Normal, 0)
2975 };
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Douglas Gregor44b43212008-12-11 16:49:14 +00002977 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002978 FieldDecl *Field = FieldDecl::Create(*this,
2979 ObjCFastEnumerationStateTypeDecl,
2980 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002981 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002982 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002983 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002984 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002985 }
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Douglas Gregor838db382010-02-11 01:19:42 +00002987 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002988 }
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002990 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2991}
2992
Mike Stumpadaaad32009-10-20 02:12:22 +00002993QualType ASTContext::getBlockDescriptorType() {
2994 if (BlockDescriptorType)
2995 return getTagDeclType(BlockDescriptorType);
2996
2997 RecordDecl *T;
2998 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002999 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3000 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003001 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003002
3003 QualType FieldTypes[] = {
3004 UnsignedLongTy,
3005 UnsignedLongTy,
3006 };
3007
3008 const char *FieldNames[] = {
3009 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003010 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003011 };
3012
3013 for (size_t i = 0; i < 2; ++i) {
3014 FieldDecl *Field = FieldDecl::Create(*this,
3015 T,
3016 SourceLocation(),
3017 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003018 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003019 /*BitWidth=*/0,
3020 /*Mutable=*/false);
3021 T->addDecl(Field);
3022 }
3023
Douglas Gregor838db382010-02-11 01:19:42 +00003024 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003025
3026 BlockDescriptorType = T;
3027
3028 return getTagDeclType(BlockDescriptorType);
3029}
3030
3031void ASTContext::setBlockDescriptorType(QualType T) {
3032 const RecordType *Rec = T->getAs<RecordType>();
3033 assert(Rec && "Invalid BlockDescriptorType");
3034 BlockDescriptorType = Rec->getDecl();
3035}
3036
Mike Stump083c25e2009-10-22 00:49:09 +00003037QualType ASTContext::getBlockDescriptorExtendedType() {
3038 if (BlockDescriptorExtendedType)
3039 return getTagDeclType(BlockDescriptorExtendedType);
3040
3041 RecordDecl *T;
3042 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003043 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3044 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003045 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003046
3047 QualType FieldTypes[] = {
3048 UnsignedLongTy,
3049 UnsignedLongTy,
3050 getPointerType(VoidPtrTy),
3051 getPointerType(VoidPtrTy)
3052 };
3053
3054 const char *FieldNames[] = {
3055 "reserved",
3056 "Size",
3057 "CopyFuncPtr",
3058 "DestroyFuncPtr"
3059 };
3060
3061 for (size_t i = 0; i < 4; ++i) {
3062 FieldDecl *Field = FieldDecl::Create(*this,
3063 T,
3064 SourceLocation(),
3065 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003066 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003067 /*BitWidth=*/0,
3068 /*Mutable=*/false);
3069 T->addDecl(Field);
3070 }
3071
Douglas Gregor838db382010-02-11 01:19:42 +00003072 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003073
3074 BlockDescriptorExtendedType = T;
3075
3076 return getTagDeclType(BlockDescriptorExtendedType);
3077}
3078
3079void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3080 const RecordType *Rec = T->getAs<RecordType>();
3081 assert(Rec && "Invalid BlockDescriptorType");
3082 BlockDescriptorExtendedType = Rec->getDecl();
3083}
3084
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003085bool ASTContext::BlockRequiresCopying(QualType Ty) {
3086 if (Ty->isBlockPointerType())
3087 return true;
3088 if (isObjCNSObjectType(Ty))
3089 return true;
3090 if (Ty->isObjCObjectPointerType())
3091 return true;
3092 return false;
3093}
3094
3095QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3096 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003097 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003098 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003099 // unsigned int __flags;
3100 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003101 // void *__copy_helper; // as needed
3102 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003103 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003104 // } *
3105
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003106 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3107
3108 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003109 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003110 llvm::SmallString<36> Name;
3111 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3112 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003113 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003114 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3115 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003116 T->startDefinition();
3117 QualType Int32Ty = IntTy;
3118 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3119 QualType FieldTypes[] = {
3120 getPointerType(VoidPtrTy),
3121 getPointerType(getTagDeclType(T)),
3122 Int32Ty,
3123 Int32Ty,
3124 getPointerType(VoidPtrTy),
3125 getPointerType(VoidPtrTy),
3126 Ty
3127 };
3128
3129 const char *FieldNames[] = {
3130 "__isa",
3131 "__forwarding",
3132 "__flags",
3133 "__size",
3134 "__copy_helper",
3135 "__destroy_helper",
3136 DeclName,
3137 };
3138
3139 for (size_t i = 0; i < 7; ++i) {
3140 if (!HasCopyAndDispose && i >=4 && i <= 5)
3141 continue;
3142 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3143 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003144 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003145 /*BitWidth=*/0, /*Mutable=*/false);
3146 T->addDecl(Field);
3147 }
3148
Douglas Gregor838db382010-02-11 01:19:42 +00003149 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003150
3151 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003152}
3153
3154
3155QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003156 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003157 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003158 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003159 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003160 llvm::SmallString<36> Name;
3161 llvm::raw_svector_ostream(Name) << "__block_literal_"
3162 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003163 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003164 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3165 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003166 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003167 QualType FieldTypes[] = {
3168 getPointerType(VoidPtrTy),
3169 IntTy,
3170 IntTy,
3171 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003172 (BlockHasCopyDispose ?
3173 getPointerType(getBlockDescriptorExtendedType()) :
3174 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003175 };
3176
3177 const char *FieldNames[] = {
3178 "__isa",
3179 "__flags",
3180 "__reserved",
3181 "__FuncPtr",
3182 "__descriptor"
3183 };
3184
3185 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003186 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003187 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003188 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003189 /*BitWidth=*/0, /*Mutable=*/false);
3190 T->addDecl(Field);
3191 }
3192
3193 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3194 const Expr *E = BlockDeclRefDecls[i];
3195 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3196 clang::IdentifierInfo *Name = 0;
3197 if (BDRE) {
3198 const ValueDecl *D = BDRE->getDecl();
3199 Name = &Idents.get(D->getName());
3200 }
3201 QualType FieldType = E->getType();
3202
3203 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003204 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3205 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003206
3207 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003208 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003209 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003210 T->addDecl(Field);
3211 }
3212
Douglas Gregor838db382010-02-11 01:19:42 +00003213 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003214
3215 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003216}
3217
Douglas Gregor319ac892009-04-23 22:29:11 +00003218void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003219 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003220 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3221 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3222}
3223
Anders Carlssone8c49532007-10-29 06:33:42 +00003224// This returns true if a type has been typedefed to BOOL:
3225// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003226static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003227 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003228 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3229 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003231 return false;
3232}
3233
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003234/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003235/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003236CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003237 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003238
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003239 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003240 if (sz.isPositive() && type->isIntegralType())
3241 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003242 // Treat arrays as pointers, since that's how they're passed in.
3243 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003244 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003245 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003246}
3247
3248static inline
3249std::string charUnitsToString(const CharUnits &CU) {
3250 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003251}
3252
David Chisnall5e530af2009-11-17 19:33:30 +00003253/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3254/// declaration.
3255void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3256 std::string& S) {
3257 const BlockDecl *Decl = Expr->getBlockDecl();
3258 QualType BlockTy =
3259 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3260 // Encode result type.
3261 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3262 // Compute size of all parameters.
3263 // Start with computing size of a pointer in number of bytes.
3264 // FIXME: There might(should) be a better way of doing this computation!
3265 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003266 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3267 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003268 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3269 E = Decl->param_end(); PI != E; ++PI) {
3270 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003271 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003272 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003273 ParmOffset += sz;
3274 }
3275 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003276 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003277 // Block pointer and offset.
3278 S += "@?0";
3279 ParmOffset = PtrSize;
3280
3281 // Argument types.
3282 ParmOffset = PtrSize;
3283 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3284 Decl->param_end(); PI != E; ++PI) {
3285 ParmVarDecl *PVDecl = *PI;
3286 QualType PType = PVDecl->getOriginalType();
3287 if (const ArrayType *AT =
3288 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3289 // Use array's original type only if it has known number of
3290 // elements.
3291 if (!isa<ConstantArrayType>(AT))
3292 PType = PVDecl->getType();
3293 } else if (PType->isFunctionType())
3294 PType = PVDecl->getType();
3295 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003296 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003297 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003298 }
3299}
3300
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003301/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003302/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003303void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003304 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003305 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003306 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003307 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003308 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003309 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003310 // Compute size of all parameters.
3311 // Start with computing size of a pointer in number of bytes.
3312 // FIXME: There might(should) be a better way of doing this computation!
3313 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003314 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003315 // The first two arguments (self and _cmd) are pointers; account for
3316 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003317 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003318 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3319 E = Decl->param_end(); PI != E; ++PI) {
3320 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003321 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003322 assert (sz.isPositive() &&
3323 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003324 ParmOffset += sz;
3325 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003326 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003327 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003328 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003330 // Argument types.
3331 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003332 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3333 E = Decl->param_end(); PI != E; ++PI) {
3334 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003335 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003336 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003337 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3338 // Use array's original type only if it has known number of
3339 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003340 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003341 PType = PVDecl->getType();
3342 } else if (PType->isFunctionType())
3343 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003344 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003345 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003346 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003347 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003348 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003349 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003350 }
3351}
3352
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003353/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003354/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003355/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3356/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003357/// Property attributes are stored as a comma-delimited C string. The simple
3358/// attributes readonly and bycopy are encoded as single characters. The
3359/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3360/// encoded as single characters, followed by an identifier. Property types
3361/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003362/// these attributes are defined by the following enumeration:
3363/// @code
3364/// enum PropertyAttributes {
3365/// kPropertyReadOnly = 'R', // property is read-only.
3366/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3367/// kPropertyByref = '&', // property is a reference to the value last assigned
3368/// kPropertyDynamic = 'D', // property is dynamic
3369/// kPropertyGetter = 'G', // followed by getter selector name
3370/// kPropertySetter = 'S', // followed by setter selector name
3371/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3372/// kPropertyType = 't' // followed by old-style type encoding.
3373/// kPropertyWeak = 'W' // 'weak' property
3374/// kPropertyStrong = 'P' // property GC'able
3375/// kPropertyNonAtomic = 'N' // property non-atomic
3376/// };
3377/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003378void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003379 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003380 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003381 // Collect information from the property implementation decl(s).
3382 bool Dynamic = false;
3383 ObjCPropertyImplDecl *SynthesizePID = 0;
3384
3385 // FIXME: Duplicated code due to poor abstraction.
3386 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003387 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003388 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3389 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003390 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003391 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003392 ObjCPropertyImplDecl *PID = *i;
3393 if (PID->getPropertyDecl() == PD) {
3394 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3395 Dynamic = true;
3396 } else {
3397 SynthesizePID = PID;
3398 }
3399 }
3400 }
3401 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003402 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003403 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003404 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003405 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003406 ObjCPropertyImplDecl *PID = *i;
3407 if (PID->getPropertyDecl() == PD) {
3408 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3409 Dynamic = true;
3410 } else {
3411 SynthesizePID = PID;
3412 }
3413 }
Mike Stump1eb44332009-09-09 15:08:12 +00003414 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003415 }
3416 }
3417
3418 // FIXME: This is not very efficient.
3419 S = "T";
3420
3421 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003422 // GCC has some special rules regarding encoding of properties which
3423 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003424 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003425 true /* outermost type */,
3426 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003427
3428 if (PD->isReadOnly()) {
3429 S += ",R";
3430 } else {
3431 switch (PD->getSetterKind()) {
3432 case ObjCPropertyDecl::Assign: break;
3433 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003434 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003435 }
3436 }
3437
3438 // It really isn't clear at all what this means, since properties
3439 // are "dynamic by default".
3440 if (Dynamic)
3441 S += ",D";
3442
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003443 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3444 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003445
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003446 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3447 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003448 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003449 }
3450
3451 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3452 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003453 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003454 }
3455
3456 if (SynthesizePID) {
3457 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3458 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003459 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003460 }
3461
3462 // FIXME: OBJCGC: weak & strong
3463}
3464
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003465/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003466/// Another legacy compatibility encoding: 32-bit longs are encoded as
3467/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003468/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3469///
3470void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003471 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003472 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003473 if (BT->getKind() == BuiltinType::ULong &&
3474 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003475 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003476 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003477 if (BT->getKind() == BuiltinType::Long &&
3478 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003479 PointeeTy = IntTy;
3480 }
3481 }
3482}
3483
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003484void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003485 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003486 // We follow the behavior of gcc, expanding structures which are
3487 // directly pointed to, and expanding embedded structures. Note that
3488 // these rules are sufficient to prevent recursive encoding of the
3489 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003490 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003491 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003492}
3493
Mike Stump1eb44332009-09-09 15:08:12 +00003494static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003495 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003496 const Expr *E = FD->getBitWidth();
3497 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3498 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003499 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003500 S += 'b';
3501 S += llvm::utostr(N);
3502}
3503
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003504// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003505void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3506 bool ExpandPointedToStructures,
3507 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003508 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003509 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003510 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003511 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003512 if (FD && FD->isBitField())
3513 return EncodeBitField(this, S, FD);
3514 char encoding;
3515 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003516 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003517 case BuiltinType::Void: encoding = 'v'; break;
3518 case BuiltinType::Bool: encoding = 'B'; break;
3519 case BuiltinType::Char_U:
3520 case BuiltinType::UChar: encoding = 'C'; break;
3521 case BuiltinType::UShort: encoding = 'S'; break;
3522 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003523 case BuiltinType::ULong:
3524 encoding =
3525 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003526 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003527 case BuiltinType::UInt128: encoding = 'T'; break;
3528 case BuiltinType::ULongLong: encoding = 'Q'; break;
3529 case BuiltinType::Char_S:
3530 case BuiltinType::SChar: encoding = 'c'; break;
3531 case BuiltinType::Short: encoding = 's'; break;
3532 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003533 case BuiltinType::Long:
3534 encoding =
3535 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 break;
3537 case BuiltinType::LongLong: encoding = 'q'; break;
3538 case BuiltinType::Int128: encoding = 't'; break;
3539 case BuiltinType::Float: encoding = 'f'; break;
3540 case BuiltinType::Double: encoding = 'd'; break;
3541 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003542 }
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003544 S += encoding;
3545 return;
3546 }
Mike Stump1eb44332009-09-09 15:08:12 +00003547
John McCall183700f2009-09-21 23:43:11 +00003548 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003549 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003550 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003551 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003552 return;
3553 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003554
Ted Kremenek6217b802009-07-29 21:53:49 +00003555 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003556 if (PT->isObjCSelType()) {
3557 S += ':';
3558 return;
3559 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003560 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003561
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003562 bool isReadOnly = false;
3563 // For historical/compatibility reasons, the read-only qualifier of the
3564 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3565 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003566 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003567 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003568 if (OutermostType && T.isConstQualified()) {
3569 isReadOnly = true;
3570 S += 'r';
3571 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003572 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003573 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003574 while (P->getAs<PointerType>())
3575 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003576 if (P.isConstQualified()) {
3577 isReadOnly = true;
3578 S += 'r';
3579 }
3580 }
3581 if (isReadOnly) {
3582 // Another legacy compatibility encoding. Some ObjC qualifier and type
3583 // combinations need to be rearranged.
3584 // Rewrite "in const" from "nr" to "rn"
3585 const char * s = S.c_str();
3586 int len = S.length();
3587 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3588 std::string replace = "rn";
3589 S.replace(S.end()-2, S.end(), replace);
3590 }
3591 }
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003593 if (PointeeTy->isCharType()) {
3594 // char pointer types should be encoded as '*' unless it is a
3595 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003596 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003597 S += '*';
3598 return;
3599 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003600 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003601 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3602 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3603 S += '#';
3604 return;
3605 }
3606 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3607 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3608 S += '@';
3609 return;
3610 }
3611 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003612 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003613 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003614 getLegacyIntegralTypeEncoding(PointeeTy);
3615
Mike Stump1eb44332009-09-09 15:08:12 +00003616 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003617 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003618 return;
3619 }
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003621 if (const ArrayType *AT =
3622 // Ignore type qualifiers etc.
3623 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003624 if (isa<IncompleteArrayType>(AT)) {
3625 // Incomplete arrays are encoded as a pointer to the array element.
3626 S += '^';
3627
Mike Stump1eb44332009-09-09 15:08:12 +00003628 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003629 false, ExpandStructures, FD);
3630 } else {
3631 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Anders Carlsson559a8332009-02-22 01:38:57 +00003633 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3634 S += llvm::utostr(CAT->getSize().getZExtValue());
3635 else {
3636 //Variable length arrays are encoded as a regular array with 0 elements.
3637 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3638 S += '0';
3639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
3641 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003642 false, ExpandStructures, FD);
3643 S += ']';
3644 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003645 return;
3646 }
Mike Stump1eb44332009-09-09 15:08:12 +00003647
John McCall183700f2009-09-21 23:43:11 +00003648 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003649 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003650 return;
3651 }
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Ted Kremenek6217b802009-07-29 21:53:49 +00003653 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003654 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003655 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003656 // Anonymous structures print as '?'
3657 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3658 S += II->getName();
3659 } else {
3660 S += '?';
3661 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003662 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003663 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003664 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3665 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003666 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003667 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003668 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003669 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003670 S += '"';
3671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003673 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003674 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003675 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003676 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003677 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003678 QualType qt = Field->getType();
3679 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003680 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003681 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003682 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003683 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003684 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003685 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003686 return;
3687 }
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003689 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003690 if (FD && FD->isBitField())
3691 EncodeBitField(this, S, FD);
3692 else
3693 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003694 return;
3695 }
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003697 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003698 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003699 return;
3700 }
Mike Stump1eb44332009-09-09 15:08:12 +00003701
John McCall0953e762009-09-24 19:53:00 +00003702 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003703 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003704 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003705 S += '{';
3706 const IdentifierInfo *II = OI->getIdentifier();
3707 S += II->getName();
3708 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003709 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003710 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003711 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003712 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003713 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003714 RecFields[i]);
3715 else
Mike Stump1eb44332009-09-09 15:08:12 +00003716 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003717 FD);
3718 }
3719 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003720 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003721 }
Mike Stump1eb44332009-09-09 15:08:12 +00003722
John McCall183700f2009-09-21 23:43:11 +00003723 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003724 if (OPT->isObjCIdType()) {
3725 S += '@';
3726 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003727 }
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Steve Naroff27d20a22009-10-28 22:03:49 +00003729 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3730 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3731 // Since this is a binary compatibility issue, need to consult with runtime
3732 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003733 S += '#';
3734 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003735 }
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003737 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003738 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003739 ExpandPointedToStructures,
3740 ExpandStructures, FD);
3741 if (FD || EncodingProperty) {
3742 // Note that we do extended encoding of protocol qualifer list
3743 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003744 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003745 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3746 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003747 S += '<';
3748 S += (*I)->getNameAsString();
3749 S += '>';
3750 }
3751 S += '"';
3752 }
3753 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003754 }
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003756 QualType PointeeTy = OPT->getPointeeType();
3757 if (!EncodingProperty &&
3758 isa<TypedefType>(PointeeTy.getTypePtr())) {
3759 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003760 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003761 // {...};
3762 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003763 getObjCEncodingForTypeImpl(PointeeTy, S,
3764 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003765 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003766 return;
3767 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003768
3769 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003770 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003771 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003772 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003773 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3774 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003775 S += '<';
3776 S += (*I)->getNameAsString();
3777 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003778 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003779 S += '"';
3780 }
3781 return;
3782 }
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003784 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003785}
3786
Mike Stump1eb44332009-09-09 15:08:12 +00003787void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003788 std::string& S) const {
3789 if (QT & Decl::OBJC_TQ_In)
3790 S += 'n';
3791 if (QT & Decl::OBJC_TQ_Inout)
3792 S += 'N';
3793 if (QT & Decl::OBJC_TQ_Out)
3794 S += 'o';
3795 if (QT & Decl::OBJC_TQ_Bycopy)
3796 S += 'O';
3797 if (QT & Decl::OBJC_TQ_Byref)
3798 S += 'R';
3799 if (QT & Decl::OBJC_TQ_Oneway)
3800 S += 'V';
3801}
3802
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003803void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003804 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003806 BuiltinVaListType = T;
3807}
3808
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003809void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003810 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003811}
3812
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003813void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003814 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003815}
3816
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003817void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003818 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003819}
3820
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003821void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003822 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003823}
3824
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003825void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003826 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003827 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003829 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003830}
3831
John McCall0bd6feb2009-12-02 08:04:21 +00003832/// \brief Retrieve the template name that corresponds to a non-empty
3833/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003834TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3835 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003836 unsigned size = End - Begin;
3837 assert(size > 1 && "set is not overloaded!");
3838
3839 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3840 size * sizeof(FunctionTemplateDecl*));
3841 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3842
3843 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003844 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003845 NamedDecl *D = *I;
3846 assert(isa<FunctionTemplateDecl>(D) ||
3847 (isa<UsingShadowDecl>(D) &&
3848 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3849 *Storage++ = D;
3850 }
3851
3852 return TemplateName(OT);
3853}
3854
Douglas Gregor7532dc62009-03-30 22:58:21 +00003855/// \brief Retrieve the template name that represents a qualified
3856/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003857TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003858 bool TemplateKeyword,
3859 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003860 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003861 llvm::FoldingSetNodeID ID;
3862 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3863
3864 void *InsertPos = 0;
3865 QualifiedTemplateName *QTN =
3866 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3867 if (!QTN) {
3868 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3869 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3870 }
3871
3872 return TemplateName(QTN);
3873}
3874
3875/// \brief Retrieve the template name that represents a dependent
3876/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003877TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003878 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003879 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003880 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003881
3882 llvm::FoldingSetNodeID ID;
3883 DependentTemplateName::Profile(ID, NNS, Name);
3884
3885 void *InsertPos = 0;
3886 DependentTemplateName *QTN =
3887 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3888
3889 if (QTN)
3890 return TemplateName(QTN);
3891
3892 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3893 if (CanonNNS == NNS) {
3894 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3895 } else {
3896 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3897 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003898 DependentTemplateName *CheckQTN =
3899 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3900 assert(!CheckQTN && "Dependent type name canonicalization broken");
3901 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003902 }
3903
3904 DependentTemplateNames.InsertNode(QTN, InsertPos);
3905 return TemplateName(QTN);
3906}
3907
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003908/// \brief Retrieve the template name that represents a dependent
3909/// template name such as \c MetaFun::template operator+.
3910TemplateName
3911ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3912 OverloadedOperatorKind Operator) {
3913 assert((!NNS || NNS->isDependent()) &&
3914 "Nested name specifier must be dependent");
3915
3916 llvm::FoldingSetNodeID ID;
3917 DependentTemplateName::Profile(ID, NNS, Operator);
3918
3919 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003920 DependentTemplateName *QTN
3921 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003922
3923 if (QTN)
3924 return TemplateName(QTN);
3925
3926 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3927 if (CanonNNS == NNS) {
3928 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3929 } else {
3930 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3931 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003932
3933 DependentTemplateName *CheckQTN
3934 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3935 assert(!CheckQTN && "Dependent template name canonicalization broken");
3936 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003937 }
3938
3939 DependentTemplateNames.InsertNode(QTN, InsertPos);
3940 return TemplateName(QTN);
3941}
3942
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003943/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003944/// TargetInfo, produce the corresponding type. The unsigned @p Type
3945/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003946CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003947 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003948 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003949 case TargetInfo::SignedShort: return ShortTy;
3950 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3951 case TargetInfo::SignedInt: return IntTy;
3952 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3953 case TargetInfo::SignedLong: return LongTy;
3954 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3955 case TargetInfo::SignedLongLong: return LongLongTy;
3956 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3957 }
3958
3959 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003960 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003961}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003962
3963//===----------------------------------------------------------------------===//
3964// Type Predicates.
3965//===----------------------------------------------------------------------===//
3966
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003967/// isObjCNSObjectType - Return true if this is an NSObject object using
3968/// NSObject attribute on a c-style pointer type.
3969/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003970/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003971///
3972bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3973 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3974 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003975 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003976 return true;
3977 }
Mike Stump1eb44332009-09-09 15:08:12 +00003978 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003979}
3980
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003981/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3982/// garbage collection attribute.
3983///
John McCall0953e762009-09-24 19:53:00 +00003984Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3985 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003986 if (getLangOptions().ObjC1 &&
3987 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003988 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003989 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003990 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003991 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003992 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003993 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003994 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003995 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003996 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003997 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003998 // Non-pointers have none gc'able attribute regardless of the attribute
3999 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004000 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004001 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004002 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004003 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004004}
4005
Chris Lattner6ac46a42008-04-07 06:51:04 +00004006//===----------------------------------------------------------------------===//
4007// Type Compatibility Testing
4008//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004009
Mike Stump1eb44332009-09-09 15:08:12 +00004010/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004011/// compatible.
4012static bool areCompatVectorTypes(const VectorType *LHS,
4013 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004014 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004015 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004016 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004017}
4018
Steve Naroff4084c302009-07-23 01:01:38 +00004019//===----------------------------------------------------------------------===//
4020// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4021//===----------------------------------------------------------------------===//
4022
4023/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4024/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004025bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4026 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004027 if (lProto == rProto)
4028 return true;
4029 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4030 E = rProto->protocol_end(); PI != E; ++PI)
4031 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4032 return true;
4033 return false;
4034}
4035
Steve Naroff4084c302009-07-23 01:01:38 +00004036/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4037/// return true if lhs's protocols conform to rhs's protocol; false
4038/// otherwise.
4039bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4040 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4041 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4042 return false;
4043}
4044
4045/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4046/// ObjCQualifiedIDType.
4047bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4048 bool compare) {
4049 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004050 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004051 lhs->isObjCIdType() || lhs->isObjCClassType())
4052 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004053 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004054 rhs->isObjCIdType() || rhs->isObjCClassType())
4055 return true;
4056
4057 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004058 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004059
Steve Naroff4084c302009-07-23 01:01:38 +00004060 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004061
Steve Naroff4084c302009-07-23 01:01:38 +00004062 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004063 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004064 // make sure we check the class hierarchy.
4065 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4066 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4067 E = lhsQID->qual_end(); I != E; ++I) {
4068 // when comparing an id<P> on lhs with a static type on rhs,
4069 // see if static class implements all of id's protocols, directly or
4070 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004071 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004072 return false;
4073 }
4074 }
4075 // If there are no qualifiers and no interface, we have an 'id'.
4076 return true;
4077 }
Mike Stump1eb44332009-09-09 15:08:12 +00004078 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004079 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4080 E = lhsQID->qual_end(); I != E; ++I) {
4081 ObjCProtocolDecl *lhsProto = *I;
4082 bool match = false;
4083
4084 // when comparing an id<P> on lhs with a static type on rhs,
4085 // see if static class implements all of id's protocols, directly or
4086 // through its super class and categories.
4087 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4088 E = rhsOPT->qual_end(); J != E; ++J) {
4089 ObjCProtocolDecl *rhsProto = *J;
4090 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4091 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4092 match = true;
4093 break;
4094 }
4095 }
Mike Stump1eb44332009-09-09 15:08:12 +00004096 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004097 // make sure we check the class hierarchy.
4098 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4099 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4100 E = lhsQID->qual_end(); I != E; ++I) {
4101 // when comparing an id<P> on lhs with a static type on rhs,
4102 // see if static class implements all of id's protocols, directly or
4103 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004104 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004105 match = true;
4106 break;
4107 }
4108 }
4109 }
4110 if (!match)
4111 return false;
4112 }
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Steve Naroff4084c302009-07-23 01:01:38 +00004114 return true;
4115 }
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Steve Naroff4084c302009-07-23 01:01:38 +00004117 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4118 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4119
Mike Stump1eb44332009-09-09 15:08:12 +00004120 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004121 lhs->getAsObjCInterfacePointerType()) {
4122 if (lhsOPT->qual_empty()) {
4123 bool match = false;
4124 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4125 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4126 E = rhsQID->qual_end(); I != E; ++I) {
4127 // when comparing an id<P> on lhs with a static type on rhs,
4128 // see if static class implements all of id's protocols, directly or
4129 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004130 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004131 match = true;
4132 break;
4133 }
4134 }
4135 if (!match)
4136 return false;
4137 }
4138 return true;
4139 }
Mike Stump1eb44332009-09-09 15:08:12 +00004140 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004141 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4142 E = lhsOPT->qual_end(); I != E; ++I) {
4143 ObjCProtocolDecl *lhsProto = *I;
4144 bool match = false;
4145
4146 // when comparing an id<P> on lhs with a static type on rhs,
4147 // see if static class implements all of id's protocols, directly or
4148 // through its super class and categories.
4149 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4150 E = rhsQID->qual_end(); J != E; ++J) {
4151 ObjCProtocolDecl *rhsProto = *J;
4152 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4153 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4154 match = true;
4155 break;
4156 }
4157 }
4158 if (!match)
4159 return false;
4160 }
4161 return true;
4162 }
4163 return false;
4164}
4165
Eli Friedman3d815e72008-08-22 00:56:42 +00004166/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004167/// compatible for assignment from RHS to LHS. This handles validation of any
4168/// protocol qualifiers on the LHS or RHS.
4169///
Steve Naroff14108da2009-07-10 23:34:53 +00004170bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4171 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004172 // If either type represents the built-in 'id' or 'Class' types, return true.
4173 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004174 return true;
4175
Steve Naroff4084c302009-07-23 01:01:38 +00004176 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004177 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4178 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004179 false);
4180
Steve Naroff14108da2009-07-10 23:34:53 +00004181 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4182 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004183 if (LHS && RHS) // We have 2 user-defined types.
4184 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004185
Steve Naroff4084c302009-07-23 01:01:38 +00004186 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004187}
4188
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004189/// getIntersectionOfProtocols - This routine finds the intersection of set
4190/// of protocols inherited from two distinct objective-c pointer objects.
4191/// It is used to build composite qualifier list of the composite type of
4192/// the conditional expression involving two objective-c pointer objects.
4193static
4194void getIntersectionOfProtocols(ASTContext &Context,
4195 const ObjCObjectPointerType *LHSOPT,
4196 const ObjCObjectPointerType *RHSOPT,
4197 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4198
4199 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4200 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4201
4202 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4203 unsigned LHSNumProtocols = LHS->getNumProtocols();
4204 if (LHSNumProtocols > 0)
4205 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4206 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004207 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4208 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004209 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4210 LHSInheritedProtocols.end());
4211 }
4212
4213 unsigned RHSNumProtocols = RHS->getNumProtocols();
4214 if (RHSNumProtocols > 0) {
4215 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4216 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4217 if (InheritedProtocolSet.count(RHSProtocols[i]))
4218 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4219 }
4220 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004221 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004222 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004223 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4224 RHSInheritedProtocols.begin(),
4225 E = RHSInheritedProtocols.end(); I != E; ++I)
4226 if (InheritedProtocolSet.count((*I)))
4227 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004228 }
4229}
4230
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004231/// areCommonBaseCompatible - Returns common base class of the two classes if
4232/// one found. Note that this is O'2 algorithm. But it will be called as the
4233/// last type comparison in a ?-exp of ObjC pointer types before a
4234/// warning is issued. So, its invokation is extremely rare.
4235QualType ASTContext::areCommonBaseCompatible(
4236 const ObjCObjectPointerType *LHSOPT,
4237 const ObjCObjectPointerType *RHSOPT) {
4238 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4239 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4240 if (!LHS || !RHS)
4241 return QualType();
4242
4243 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4244 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4245 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004246 if (canAssignObjCInterfaces(LHS, RHS)) {
4247 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4248 getIntersectionOfProtocols(*this,
4249 LHSOPT, RHSOPT, IntersectionOfProtocols);
4250 if (IntersectionOfProtocols.empty())
4251 LHSTy = getObjCObjectPointerType(LHSTy);
4252 else
4253 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4254 IntersectionOfProtocols.size());
4255 return LHSTy;
4256 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004257 }
4258
4259 return QualType();
4260}
4261
Eli Friedman3d815e72008-08-22 00:56:42 +00004262bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4263 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004264 // Verify that the base decls are compatible: the RHS must be a subclass of
4265 // the LHS.
4266 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4267 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Chris Lattner6ac46a42008-04-07 06:51:04 +00004269 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4270 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004271 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004272 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Chris Lattner6ac46a42008-04-07 06:51:04 +00004274 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4275 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004276 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004277 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004278
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004279 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4280 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004281 LHSPI != LHSPE; LHSPI++) {
4282 bool RHSImplementsProtocol = false;
4283
4284 // If the RHS doesn't implement the protocol on the left, the types
4285 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004286 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004287 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004288 RHSPI != RHSPE; RHSPI++) {
4289 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004290 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004291 break;
4292 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004293 }
4294 // FIXME: For better diagnostics, consider passing back the protocol name.
4295 if (!RHSImplementsProtocol)
4296 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004297 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004298 // The RHS implements all protocols listed on the LHS.
4299 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004300}
4301
Steve Naroff389bf462009-02-12 17:52:19 +00004302bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4303 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004304 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4305 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Steve Naroff14108da2009-07-10 23:34:53 +00004307 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004308 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004309
4310 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4311 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004312}
4313
Mike Stump1eb44332009-09-09 15:08:12 +00004314/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004315/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004316/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004317/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004318bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004319 if (getLangOptions().CPlusPlus)
4320 return hasSameType(LHS, RHS);
4321
Eli Friedman3d815e72008-08-22 00:56:42 +00004322 return !mergeTypes(LHS, RHS).isNull();
4323}
4324
4325QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004326 const FunctionType *lbase = lhs->getAs<FunctionType>();
4327 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004328 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4329 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004330 bool allLTypes = true;
4331 bool allRTypes = true;
4332
4333 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004334 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004335 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004336 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004337 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004338 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004339 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004340 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004341 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4342 if (NoReturn != lbase->getNoReturnAttr())
4343 allLTypes = false;
4344 if (NoReturn != rbase->getNoReturnAttr())
4345 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004346 CallingConv lcc = lbase->getCallConv();
4347 CallingConv rcc = rbase->getCallConv();
4348 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004349 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004350 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004351
Eli Friedman3d815e72008-08-22 00:56:42 +00004352 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004353 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4354 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004355 unsigned lproto_nargs = lproto->getNumArgs();
4356 unsigned rproto_nargs = rproto->getNumArgs();
4357
4358 // Compatible functions must have the same number of arguments
4359 if (lproto_nargs != rproto_nargs)
4360 return QualType();
4361
4362 // Variadic and non-variadic functions aren't compatible
4363 if (lproto->isVariadic() != rproto->isVariadic())
4364 return QualType();
4365
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004366 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4367 return QualType();
4368
Eli Friedman3d815e72008-08-22 00:56:42 +00004369 // Check argument compatibility
4370 llvm::SmallVector<QualType, 10> types;
4371 for (unsigned i = 0; i < lproto_nargs; i++) {
4372 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4373 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4374 QualType argtype = mergeTypes(largtype, rargtype);
4375 if (argtype.isNull()) return QualType();
4376 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004377 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4378 allLTypes = false;
4379 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4380 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004381 }
4382 if (allLTypes) return lhs;
4383 if (allRTypes) return rhs;
4384 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004385 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004386 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004387 }
4388
4389 if (lproto) allRTypes = false;
4390 if (rproto) allLTypes = false;
4391
Douglas Gregor72564e72009-02-26 23:50:07 +00004392 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004393 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004394 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004395 if (proto->isVariadic()) return QualType();
4396 // Check that the types are compatible with the types that
4397 // would result from default argument promotions (C99 6.7.5.3p15).
4398 // The only types actually affected are promotable integer
4399 // types and floats, which would be passed as a different
4400 // type depending on whether the prototype is visible.
4401 unsigned proto_nargs = proto->getNumArgs();
4402 for (unsigned i = 0; i < proto_nargs; ++i) {
4403 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004404
4405 // Look at the promotion type of enum types, since that is the type used
4406 // to pass enum values.
4407 if (const EnumType *Enum = argTy->getAs<EnumType>())
4408 argTy = Enum->getDecl()->getPromotionType();
4409
Eli Friedman3d815e72008-08-22 00:56:42 +00004410 if (argTy->isPromotableIntegerType() ||
4411 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4412 return QualType();
4413 }
4414
4415 if (allLTypes) return lhs;
4416 if (allRTypes) return rhs;
4417 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004418 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004419 proto->getTypeQuals(),
4420 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004421 }
4422
4423 if (allLTypes) return lhs;
4424 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004425 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004426}
4427
4428QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004429 // C++ [expr]: If an expression initially has the type "reference to T", the
4430 // type is adjusted to "T" prior to any further analysis, the expression
4431 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004432 // expression is an lvalue unless the reference is an rvalue reference and
4433 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004434 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4435 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4436
Eli Friedman3d815e72008-08-22 00:56:42 +00004437 QualType LHSCan = getCanonicalType(LHS),
4438 RHSCan = getCanonicalType(RHS);
4439
4440 // If two types are identical, they are compatible.
4441 if (LHSCan == RHSCan)
4442 return LHS;
4443
John McCall0953e762009-09-24 19:53:00 +00004444 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004445 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4446 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004447 if (LQuals != RQuals) {
4448 // If any of these qualifiers are different, we have a type
4449 // mismatch.
4450 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4451 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4452 return QualType();
4453
4454 // Exactly one GC qualifier difference is allowed: __strong is
4455 // okay if the other type has no GC qualifier but is an Objective
4456 // C object pointer (i.e. implicitly strong by default). We fix
4457 // this by pretending that the unqualified type was actually
4458 // qualified __strong.
4459 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4460 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4461 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4462
4463 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4464 return QualType();
4465
4466 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4467 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4468 }
4469 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4470 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4471 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004472 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004473 }
4474
4475 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004476
Eli Friedman852d63b2009-06-01 01:22:52 +00004477 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4478 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004479
Chris Lattner1adb8832008-01-14 05:45:46 +00004480 // We want to consider the two function types to be the same for these
4481 // comparisons, just force one to the other.
4482 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4483 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004484
4485 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004486 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4487 LHSClass = Type::ConstantArray;
4488 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4489 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Nate Begeman213541a2008-04-18 23:10:10 +00004491 // Canonicalize ExtVector -> Vector.
4492 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4493 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004494
Chris Lattnera36a61f2008-04-07 05:43:21 +00004495 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004496 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004497 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004498 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004499 // Compatibility is based on the underlying type, not the promotion
4500 // type.
John McCall183700f2009-09-21 23:43:11 +00004501 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004502 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4503 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004504 }
John McCall183700f2009-09-21 23:43:11 +00004505 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004506 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4507 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004508 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004509
Eli Friedman3d815e72008-08-22 00:56:42 +00004510 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004511 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004512
Steve Naroff4a746782008-01-09 22:43:08 +00004513 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004514 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004515#define TYPE(Class, Base)
4516#define ABSTRACT_TYPE(Class, Base)
4517#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4518#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4519#include "clang/AST/TypeNodes.def"
4520 assert(false && "Non-canonical and dependent types shouldn't get here");
4521 return QualType();
4522
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004523 case Type::LValueReference:
4524 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004525 case Type::MemberPointer:
4526 assert(false && "C++ should never be in mergeTypes");
4527 return QualType();
4528
4529 case Type::IncompleteArray:
4530 case Type::VariableArray:
4531 case Type::FunctionProto:
4532 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004533 assert(false && "Types are eliminated above");
4534 return QualType();
4535
Chris Lattner1adb8832008-01-14 05:45:46 +00004536 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004537 {
4538 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004539 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4540 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004541 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4542 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004543 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004544 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004545 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004546 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004547 return getPointerType(ResultType);
4548 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004549 case Type::BlockPointer:
4550 {
4551 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004552 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4553 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004554 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4555 if (ResultType.isNull()) return QualType();
4556 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4557 return LHS;
4558 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4559 return RHS;
4560 return getBlockPointerType(ResultType);
4561 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004562 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004563 {
4564 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4565 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4566 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4567 return QualType();
4568
4569 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4570 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4571 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4572 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004573 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4574 return LHS;
4575 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4576 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004577 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4578 ArrayType::ArraySizeModifier(), 0);
4579 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4580 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004581 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4582 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004583 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4584 return LHS;
4585 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4586 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004587 if (LVAT) {
4588 // FIXME: This isn't correct! But tricky to implement because
4589 // the array's size has to be the size of LHS, but the type
4590 // has to be different.
4591 return LHS;
4592 }
4593 if (RVAT) {
4594 // FIXME: This isn't correct! But tricky to implement because
4595 // the array's size has to be the size of RHS, but the type
4596 // has to be different.
4597 return RHS;
4598 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004599 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4600 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004601 return getIncompleteArrayType(ResultType,
4602 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004603 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004604 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004605 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004606 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004607 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004608 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004609 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004610 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004611 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004612 case Type::Complex:
4613 // Distinct complex types are incompatible.
4614 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004615 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004616 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004617 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004618 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004619 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004620 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004621 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004622 // FIXME: This should be type compatibility, e.g. whether
4623 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004624 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4625 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004626 if (LHSIface && RHSIface &&
4627 canAssignObjCInterfaces(LHSIface, RHSIface))
4628 return LHS;
4629
Eli Friedman3d815e72008-08-22 00:56:42 +00004630 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004631 }
Steve Naroff14108da2009-07-10 23:34:53 +00004632 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004633 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4634 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004635 return LHS;
4636
Steve Naroffbc76dd02008-12-10 22:14:21 +00004637 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004638 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00004639 case Type::TemplateSpecialization:
4640 assert(false && "Dependent types have no size");
4641 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004642 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004643
4644 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004645}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004646
Chris Lattner5426bf62008-04-07 07:01:58 +00004647//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004648// Integer Predicates
4649//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004650
Eli Friedmanad74a752008-06-28 06:23:08 +00004651unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004652 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004653 return 1;
John McCall842aef82009-12-09 09:09:27 +00004654 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004655 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004656 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004657 return (unsigned)getTypeSize(T);
4658}
4659
4660QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4661 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004662
4663 // Turn <4 x signed int> -> <4 x unsigned int>
4664 if (const VectorType *VTy = T->getAs<VectorType>())
4665 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004666 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004667
4668 // For enums, we return the unsigned version of the base type.
4669 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004670 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004671
4672 const BuiltinType *BTy = T->getAs<BuiltinType>();
4673 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004674 switch (BTy->getKind()) {
4675 case BuiltinType::Char_S:
4676 case BuiltinType::SChar:
4677 return UnsignedCharTy;
4678 case BuiltinType::Short:
4679 return UnsignedShortTy;
4680 case BuiltinType::Int:
4681 return UnsignedIntTy;
4682 case BuiltinType::Long:
4683 return UnsignedLongTy;
4684 case BuiltinType::LongLong:
4685 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004686 case BuiltinType::Int128:
4687 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004688 default:
4689 assert(0 && "Unexpected signed integer type");
4690 return QualType();
4691 }
4692}
4693
Douglas Gregor2cf26342009-04-09 22:27:44 +00004694ExternalASTSource::~ExternalASTSource() { }
4695
4696void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004697
4698
4699//===----------------------------------------------------------------------===//
4700// Builtin Type Computation
4701//===----------------------------------------------------------------------===//
4702
4703/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4704/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004705static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004706 ASTContext::GetBuiltinTypeError &Error,
4707 bool AllowTypeModifiers = true) {
4708 // Modifiers.
4709 int HowLong = 0;
4710 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Chris Lattner86df27b2009-06-14 00:45:47 +00004712 // Read the modifiers first.
4713 bool Done = false;
4714 while (!Done) {
4715 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004716 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004717 case 'S':
4718 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4719 assert(!Signed && "Can't use 'S' modifier multiple times!");
4720 Signed = true;
4721 break;
4722 case 'U':
4723 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4724 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4725 Unsigned = true;
4726 break;
4727 case 'L':
4728 assert(HowLong <= 2 && "Can't have LLLL modifier");
4729 ++HowLong;
4730 break;
4731 }
4732 }
4733
4734 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Chris Lattner86df27b2009-06-14 00:45:47 +00004736 // Read the base type.
4737 switch (*Str++) {
4738 default: assert(0 && "Unknown builtin type letter!");
4739 case 'v':
4740 assert(HowLong == 0 && !Signed && !Unsigned &&
4741 "Bad modifiers used with 'v'!");
4742 Type = Context.VoidTy;
4743 break;
4744 case 'f':
4745 assert(HowLong == 0 && !Signed && !Unsigned &&
4746 "Bad modifiers used with 'f'!");
4747 Type = Context.FloatTy;
4748 break;
4749 case 'd':
4750 assert(HowLong < 2 && !Signed && !Unsigned &&
4751 "Bad modifiers used with 'd'!");
4752 if (HowLong)
4753 Type = Context.LongDoubleTy;
4754 else
4755 Type = Context.DoubleTy;
4756 break;
4757 case 's':
4758 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4759 if (Unsigned)
4760 Type = Context.UnsignedShortTy;
4761 else
4762 Type = Context.ShortTy;
4763 break;
4764 case 'i':
4765 if (HowLong == 3)
4766 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4767 else if (HowLong == 2)
4768 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4769 else if (HowLong == 1)
4770 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4771 else
4772 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4773 break;
4774 case 'c':
4775 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4776 if (Signed)
4777 Type = Context.SignedCharTy;
4778 else if (Unsigned)
4779 Type = Context.UnsignedCharTy;
4780 else
4781 Type = Context.CharTy;
4782 break;
4783 case 'b': // boolean
4784 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4785 Type = Context.BoolTy;
4786 break;
4787 case 'z': // size_t.
4788 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4789 Type = Context.getSizeType();
4790 break;
4791 case 'F':
4792 Type = Context.getCFConstantStringType();
4793 break;
4794 case 'a':
4795 Type = Context.getBuiltinVaListType();
4796 assert(!Type.isNull() && "builtin va list type not initialized!");
4797 break;
4798 case 'A':
4799 // This is a "reference" to a va_list; however, what exactly
4800 // this means depends on how va_list is defined. There are two
4801 // different kinds of va_list: ones passed by value, and ones
4802 // passed by reference. An example of a by-value va_list is
4803 // x86, where va_list is a char*. An example of by-ref va_list
4804 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4805 // we want this argument to be a char*&; for x86-64, we want
4806 // it to be a __va_list_tag*.
4807 Type = Context.getBuiltinVaListType();
4808 assert(!Type.isNull() && "builtin va list type not initialized!");
4809 if (Type->isArrayType()) {
4810 Type = Context.getArrayDecayedType(Type);
4811 } else {
4812 Type = Context.getLValueReferenceType(Type);
4813 }
4814 break;
4815 case 'V': {
4816 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004817 unsigned NumElements = strtoul(Str, &End, 10);
4818 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Chris Lattner86df27b2009-06-14 00:45:47 +00004820 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004821
Chris Lattner86df27b2009-06-14 00:45:47 +00004822 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004823 // FIXME: Don't know what to do about AltiVec.
4824 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004825 break;
4826 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004827 case 'X': {
4828 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4829 Type = Context.getComplexType(ElementType);
4830 break;
4831 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004832 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004833 Type = Context.getFILEType();
4834 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004835 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004836 return QualType();
4837 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004838 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004839 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004840 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004841 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004842 else
4843 Type = Context.getjmp_bufType();
4844
Mike Stumpfd612db2009-07-28 23:47:15 +00004845 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004846 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004847 return QualType();
4848 }
4849 break;
Mike Stump782fa302009-07-28 02:25:19 +00004850 }
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Chris Lattner86df27b2009-06-14 00:45:47 +00004852 if (!AllowTypeModifiers)
4853 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Chris Lattner86df27b2009-06-14 00:45:47 +00004855 Done = false;
4856 while (!Done) {
4857 switch (*Str++) {
4858 default: Done = true; --Str; break;
4859 case '*':
4860 Type = Context.getPointerType(Type);
4861 break;
4862 case '&':
4863 Type = Context.getLValueReferenceType(Type);
4864 break;
4865 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4866 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004867 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004868 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004869 case 'D':
4870 Type = Context.getVolatileType(Type);
4871 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004872 }
4873 }
Mike Stump1eb44332009-09-09 15:08:12 +00004874
Chris Lattner86df27b2009-06-14 00:45:47 +00004875 return Type;
4876}
4877
4878/// GetBuiltinType - Return the type for the specified builtin.
4879QualType ASTContext::GetBuiltinType(unsigned id,
4880 GetBuiltinTypeError &Error) {
4881 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004882
Chris Lattner86df27b2009-06-14 00:45:47 +00004883 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004884
Chris Lattner86df27b2009-06-14 00:45:47 +00004885 Error = GE_None;
4886 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4887 if (Error != GE_None)
4888 return QualType();
4889 while (TypeStr[0] && TypeStr[0] != '.') {
4890 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4891 if (Error != GE_None)
4892 return QualType();
4893
4894 // Do array -> pointer decay. The builtin should use the decayed type.
4895 if (Ty->isArrayType())
4896 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004897
Chris Lattner86df27b2009-06-14 00:45:47 +00004898 ArgTypes.push_back(Ty);
4899 }
4900
4901 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4902 "'.' should only occur at end of builtin type list!");
4903
4904 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4905 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4906 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00004907
4908 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00004909 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004910 TypeStr[0] == '.', 0, false, false, 0, 0,
4911 false, CC_Default);
Chris Lattner86df27b2009-06-14 00:45:47 +00004912}
Eli Friedmana95d7572009-08-19 07:44:53 +00004913
4914QualType
4915ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4916 // Perform the usual unary conversions. We do this early so that
4917 // integral promotions to "int" can allow us to exit early, in the
4918 // lhs == rhs check. Also, for conversion purposes, we ignore any
4919 // qualifiers. For example, "const float" and "float" are
4920 // equivalent.
4921 if (lhs->isPromotableIntegerType())
4922 lhs = getPromotedIntegerType(lhs);
4923 else
4924 lhs = lhs.getUnqualifiedType();
4925 if (rhs->isPromotableIntegerType())
4926 rhs = getPromotedIntegerType(rhs);
4927 else
4928 rhs = rhs.getUnqualifiedType();
4929
4930 // If both types are identical, no conversion is needed.
4931 if (lhs == rhs)
4932 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004933
Eli Friedmana95d7572009-08-19 07:44:53 +00004934 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4935 // The caller can deal with this (e.g. pointer + int).
4936 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4937 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004938
4939 // At this point, we have two different arithmetic types.
4940
Eli Friedmana95d7572009-08-19 07:44:53 +00004941 // Handle complex types first (C99 6.3.1.8p1).
4942 if (lhs->isComplexType() || rhs->isComplexType()) {
4943 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004944 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004945 // convert the rhs to the lhs complex type.
4946 return lhs;
4947 }
Mike Stump1eb44332009-09-09 15:08:12 +00004948 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004949 // convert the lhs to the rhs complex type.
4950 return rhs;
4951 }
4952 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004953 // When both operands are complex, the shorter operand is converted to the
4954 // type of the longer, and that is the type of the result. This corresponds
4955 // to what is done when combining two real floating-point operands.
4956 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004957 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004958 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004959 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004960 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004961 // "double _Complex" is promoted to "long double _Complex".
4962 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004963
4964 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004965 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004966 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004967 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004968 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004969 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4970 // domains match. This is a requirement for our implementation, C99
4971 // does not require this promotion.
4972 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4973 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4974 return rhs;
4975 } else { // handle "_Complex double, double".
4976 return lhs;
4977 }
4978 }
4979 return lhs; // The domain/size match exactly.
4980 }
4981 // Now handle "real" floating types (i.e. float, double, long double).
4982 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4983 // if we have an integer operand, the result is the real floating type.
4984 if (rhs->isIntegerType()) {
4985 // convert rhs to the lhs floating point type.
4986 return lhs;
4987 }
4988 if (rhs->isComplexIntegerType()) {
4989 // convert rhs to the complex floating point type.
4990 return getComplexType(lhs);
4991 }
4992 if (lhs->isIntegerType()) {
4993 // convert lhs to the rhs floating point type.
4994 return rhs;
4995 }
Mike Stump1eb44332009-09-09 15:08:12 +00004996 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004997 // convert lhs to the complex floating point type.
4998 return getComplexType(rhs);
4999 }
5000 // We have two real floating types, float/complex combos were handled above.
5001 // Convert the smaller operand to the bigger result.
5002 int result = getFloatingTypeOrder(lhs, rhs);
5003 if (result > 0) // convert the rhs
5004 return lhs;
5005 assert(result < 0 && "illegal float comparison");
5006 return rhs; // convert the lhs
5007 }
5008 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5009 // Handle GCC complex int extension.
5010 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5011 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5012
5013 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005014 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005015 rhsComplexInt->getElementType()) >= 0)
5016 return lhs; // convert the rhs
5017 return rhs;
5018 } else if (lhsComplexInt && rhs->isIntegerType()) {
5019 // convert the rhs to the lhs complex type.
5020 return lhs;
5021 } else if (rhsComplexInt && lhs->isIntegerType()) {
5022 // convert the lhs to the rhs complex type.
5023 return rhs;
5024 }
5025 }
5026 // Finally, we have two differing integer types.
5027 // The rules for this case are in C99 6.3.1.8
5028 int compare = getIntegerTypeOrder(lhs, rhs);
5029 bool lhsSigned = lhs->isSignedIntegerType(),
5030 rhsSigned = rhs->isSignedIntegerType();
5031 QualType destType;
5032 if (lhsSigned == rhsSigned) {
5033 // Same signedness; use the higher-ranked type
5034 destType = compare >= 0 ? lhs : rhs;
5035 } else if (compare != (lhsSigned ? 1 : -1)) {
5036 // The unsigned type has greater than or equal rank to the
5037 // signed type, so use the unsigned type
5038 destType = lhsSigned ? rhs : lhs;
5039 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5040 // The two types are different widths; if we are here, that
5041 // means the signed type is larger than the unsigned type, so
5042 // use the signed type.
5043 destType = lhsSigned ? lhs : rhs;
5044 } else {
5045 // The signed type is higher-ranked than the unsigned type,
5046 // but isn't actually any bigger (like unsigned int and long
5047 // on most 32-bit systems). Use the unsigned type corresponding
5048 // to the signed type.
5049 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5050 }
5051 return destType;
5052}