blob: 1112aa97b8c08a920697419afa93c4b2b3fbe7de [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,
875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
876 bool CollectSynthesized) {
877 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
878 E = OI->ivar_end(); I != E; ++I) {
879 Ivars.push_back(*I);
880 }
881 if (CollectSynthesized)
882 CollectSynthesizedIvars(OI, Ivars);
883}
884
Fariborz Jahanian98200742009-05-12 18:14:29 +0000885void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
886 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000887 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
888 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000889 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
890 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Fariborz Jahanian98200742009-05-12 18:14:29 +0000892 // Also look into nested protocols.
893 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
894 E = PD->protocol_end(); P != E; ++P)
895 CollectProtocolSynthesizedIvars(*P, Ivars);
896}
897
898/// CollectSynthesizedIvars -
899/// This routine collect synthesized ivars for the designated class.
900///
901void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
902 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000903 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
904 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000905 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
906 Ivars.push_back(Ivar);
907 }
908 // Also look into interface's protocol list for properties declared
909 // in the protocol and whose ivars are synthesized.
910 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
911 PE = OI->protocol_end(); P != PE; ++P) {
912 ObjCProtocolDecl *PD = (*P);
913 CollectProtocolSynthesizedIvars(PD, Ivars);
914 }
915}
916
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000917/// CollectInheritedProtocols - Collect all protocols in current class and
918/// those inherited by it.
919void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
920 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
921 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
922 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
923 PE = OI->protocol_end(); P != PE; ++P) {
924 ObjCProtocolDecl *Proto = (*P);
925 Protocols.push_back(Proto);
926 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
927 PE = Proto->protocol_end(); P != PE; ++P)
928 CollectInheritedProtocols(*P, Protocols);
929 }
930
931 // Categories of this Interface.
932 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
933 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
934 CollectInheritedProtocols(CDeclChain, Protocols);
935 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
936 while (SD) {
937 CollectInheritedProtocols(SD, Protocols);
938 SD = SD->getSuperClass();
939 }
940 return;
941 }
942 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
943 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
944 PE = OC->protocol_end(); P != PE; ++P) {
945 ObjCProtocolDecl *Proto = (*P);
946 Protocols.push_back(Proto);
947 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
948 PE = Proto->protocol_end(); P != PE; ++P)
949 CollectInheritedProtocols(*P, Protocols);
950 }
951 return;
952 }
953 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
954 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
955 PE = OP->protocol_end(); P != PE; ++P) {
956 ObjCProtocolDecl *Proto = (*P);
957 Protocols.push_back(Proto);
958 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
959 PE = Proto->protocol_end(); P != PE; ++P)
960 CollectInheritedProtocols(*P, Protocols);
961 }
962 return;
963 }
964}
965
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000966unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
967 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000968 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
969 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000970 if ((*I)->getPropertyIvarDecl())
971 ++count;
972
973 // Also look into nested protocols.
974 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
975 E = PD->protocol_end(); P != E; ++P)
976 count += CountProtocolSynthesizedIvars(*P);
977 return count;
978}
979
Mike Stump1eb44332009-09-09 15:08:12 +0000980unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000981 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000982 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
983 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000984 if ((*I)->getPropertyIvarDecl())
985 ++count;
986 }
987 // Also look into interface's protocol list for properties declared
988 // in the protocol and whose ivars are synthesized.
989 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
990 PE = OI->protocol_end(); P != PE; ++P) {
991 ObjCProtocolDecl *PD = (*P);
992 count += CountProtocolSynthesizedIvars(PD);
993 }
994 return count;
995}
996
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000997/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
998ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
999 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1000 I = ObjCImpls.find(D);
1001 if (I != ObjCImpls.end())
1002 return cast<ObjCImplementationDecl>(I->second);
1003 return 0;
1004}
1005/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1006ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1007 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1008 I = ObjCImpls.find(D);
1009 if (I != ObjCImpls.end())
1010 return cast<ObjCCategoryImplDecl>(I->second);
1011 return 0;
1012}
1013
1014/// \brief Set the implementation of ObjCInterfaceDecl.
1015void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1016 ObjCImplementationDecl *ImplD) {
1017 assert(IFaceD && ImplD && "Passed null params");
1018 ObjCImpls[IFaceD] = ImplD;
1019}
1020/// \brief Set the implementation of ObjCCategoryDecl.
1021void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1022 ObjCCategoryImplDecl *ImplD) {
1023 assert(CatD && ImplD && "Passed null params");
1024 ObjCImpls[CatD] = ImplD;
1025}
1026
John McCalla93c9342009-12-07 02:54:59 +00001027/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001028///
John McCalla93c9342009-12-07 02:54:59 +00001029/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001030/// the TypeLoc wrappers.
1031///
1032/// \param T the type that will be the basis for type source info. This type
1033/// should refer to how the declarator was written in source code, not to
1034/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001035TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001036 unsigned DataSize) {
1037 if (!DataSize)
1038 DataSize = TypeLoc::getFullDataSizeForType(T);
1039 else
1040 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001041 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001042
John McCalla93c9342009-12-07 02:54:59 +00001043 TypeSourceInfo *TInfo =
1044 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1045 new (TInfo) TypeSourceInfo(T);
1046 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001047}
1048
John McCalla93c9342009-12-07 02:54:59 +00001049TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001050 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001051 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001052 DI->getTypeLoc().initialize(L);
1053 return DI;
1054}
1055
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001056/// getInterfaceLayoutImpl - Get or compute information about the
1057/// layout of the given interface.
1058///
1059/// \param Impl - If given, also include the layout of the interface's
1060/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001061const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001062ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1063 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001064 assert(!D->isForwardDecl() && "Invalid interface decl!");
1065
Devang Patel44a3dde2008-06-04 21:54:36 +00001066 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001067 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001068 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1069 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1070 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001071
Daniel Dunbar453addb2009-05-03 11:16:44 +00001072 // Add in synthesized ivar count if laying out an implementation.
1073 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001074 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001075 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001076 // entry. Note we can't cache this because we simply free all
1077 // entries later; however we shouldn't look up implementations
1078 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001079 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001080 return getObjCLayout(D, 0);
1081 }
1082
Mike Stump1eb44332009-09-09 15:08:12 +00001083 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001084 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1085 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Devang Patel44a3dde2008-06-04 21:54:36 +00001087 return *NewEntry;
1088}
1089
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001090const ASTRecordLayout &
1091ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1092 return getObjCLayout(D, 0);
1093}
1094
1095const ASTRecordLayout &
1096ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1097 return getObjCLayout(D->getClassInterface(), D);
1098}
1099
Devang Patel88a981b2007-11-01 19:11:01 +00001100/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001101/// specified record (struct/union/class), which indicates its size and field
1102/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001103const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001104 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001105 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001106
Chris Lattner464175b2007-07-18 17:52:12 +00001107 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001108 // Note that we can't save a reference to the entry because this function
1109 // is recursive.
1110 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001111 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001114 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001115 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner5d2a6302007-07-18 18:26:58 +00001117 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001118}
1119
Anders Carlssonf53df232009-12-07 04:35:11 +00001120const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001121 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001122 assert(RD && "Cannot get key function for forward declarations!");
1123
1124 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1125 if (!Entry)
1126 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1127 else
1128 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1129 "Key function changed!");
1130
1131 return Entry;
1132}
1133
Chris Lattnera7674d82007-07-13 22:13:22 +00001134//===----------------------------------------------------------------------===//
1135// Type creation/memoization methods
1136//===----------------------------------------------------------------------===//
1137
John McCall0953e762009-09-24 19:53:00 +00001138QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1139 unsigned Fast = Quals.getFastQualifiers();
1140 Quals.removeFastQualifiers();
1141
1142 // Check if we've already instantiated this type.
1143 llvm::FoldingSetNodeID ID;
1144 ExtQuals::Profile(ID, TypeNode, Quals);
1145 void *InsertPos = 0;
1146 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1147 assert(EQ->getQualifiers() == Quals);
1148 QualType T = QualType(EQ, Fast);
1149 return T;
1150 }
1151
John McCall6b304a02009-09-24 23:30:46 +00001152 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001153 ExtQualNodes.InsertNode(New, InsertPos);
1154 QualType T = QualType(New, Fast);
1155 return T;
1156}
1157
1158QualType ASTContext::getVolatileType(QualType T) {
1159 QualType CanT = getCanonicalType(T);
1160 if (CanT.isVolatileQualified()) return T;
1161
1162 QualifierCollector Quals;
1163 const Type *TypeNode = Quals.strip(T);
1164 Quals.addVolatile();
1165
1166 return getExtQualType(TypeNode, Quals);
1167}
1168
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001169QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001170 QualType CanT = getCanonicalType(T);
1171 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001172 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001173
John McCall0953e762009-09-24 19:53:00 +00001174 // If we are composing extended qualifiers together, merge together
1175 // into one ExtQuals node.
1176 QualifierCollector Quals;
1177 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001178
John McCall0953e762009-09-24 19:53:00 +00001179 // If this type already has an address space specified, it cannot get
1180 // another one.
1181 assert(!Quals.hasAddressSpace() &&
1182 "Type cannot be in multiple addr spaces!");
1183 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
John McCall0953e762009-09-24 19:53:00 +00001185 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001186}
1187
Chris Lattnerb7d25532009-02-18 22:53:11 +00001188QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001189 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001190 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001191 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001192 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001194 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001195 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001196 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001197 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1198 return getPointerType(ResultType);
1199 }
1200 }
Mike Stump1eb44332009-09-09 15:08:12 +00001201
John McCall0953e762009-09-24 19:53:00 +00001202 // If we are composing extended qualifiers together, merge together
1203 // into one ExtQuals node.
1204 QualifierCollector Quals;
1205 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
John McCall0953e762009-09-24 19:53:00 +00001207 // If this type already has an ObjCGC specified, it cannot get
1208 // another one.
1209 assert(!Quals.hasObjCGCAttr() &&
1210 "Type cannot have multiple ObjCGCs!");
1211 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
John McCall0953e762009-09-24 19:53:00 +00001213 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001214}
Chris Lattnera7674d82007-07-13 22:13:22 +00001215
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001216static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1217 bool AddNoReturn,
1218 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001219 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001220 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1221 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001222 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1223 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001224 if (ResultType == Pointee)
1225 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001226
1227 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001228 } else if (const BlockPointerType *BlockPointer
1229 = T->getAs<BlockPointerType>()) {
1230 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001231 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1232 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001233 if (ResultType == Pointee)
1234 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001235
1236 ResultType = Context.getBlockPointerType(ResultType);
1237 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1238 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001239 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001240
Douglas Gregor43c79c22009-12-09 00:47:37 +00001241 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001242 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1243 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001244 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001245 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001246 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001247 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1248 FPT->getNumArgs(), FPT->isVariadic(),
1249 FPT->getTypeQuals(),
1250 FPT->hasExceptionSpec(),
1251 FPT->hasAnyExceptionSpec(),
1252 FPT->getNumExceptions(),
1253 FPT->exception_begin(),
1254 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001255 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001256 } else
1257 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001258
1259 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1260}
1261
1262QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1263 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1264}
1265
1266QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1267 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001268}
1269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270/// getComplexType - Return the uniqued reference to the type for a complex
1271/// number with the specified element type.
1272QualType ASTContext::getComplexType(QualType T) {
1273 // Unique pointers, to guarantee there is only one pointer of a particular
1274 // structure.
1275 llvm::FoldingSetNodeID ID;
1276 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 void *InsertPos = 0;
1279 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1280 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // If the pointee type isn't canonical, this won't be a canonical type either,
1283 // so fill in the canonical type field.
1284 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001285 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001286 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // Get the new insert position for the node we care about.
1289 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001290 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 }
John McCall6b304a02009-09-24 23:30:46 +00001292 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 Types.push_back(New);
1294 ComplexTypes.InsertNode(New, InsertPos);
1295 return QualType(New, 0);
1296}
1297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298/// getPointerType - Return the uniqued reference to the type for a pointer to
1299/// the specified type.
1300QualType ASTContext::getPointerType(QualType T) {
1301 // Unique pointers, to guarantee there is only one pointer of a particular
1302 // structure.
1303 llvm::FoldingSetNodeID ID;
1304 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 void *InsertPos = 0;
1307 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1308 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 // If the pointee type isn't canonical, this won't be a canonical type either,
1311 // so fill in the canonical type field.
1312 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001313 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001314 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 // Get the new insert position for the node we care about.
1317 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001318 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 }
John McCall6b304a02009-09-24 23:30:46 +00001320 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 Types.push_back(New);
1322 PointerTypes.InsertNode(New, InsertPos);
1323 return QualType(New, 0);
1324}
1325
Mike Stump1eb44332009-09-09 15:08:12 +00001326/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001327/// a pointer to the specified block.
1328QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001329 assert(T->isFunctionType() && "block of function types only");
1330 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001331 // structure.
1332 llvm::FoldingSetNodeID ID;
1333 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Steve Naroff5618bd42008-08-27 16:04:49 +00001335 void *InsertPos = 0;
1336 if (BlockPointerType *PT =
1337 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1338 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
1340 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001341 // type either so fill in the canonical type field.
1342 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001343 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001344 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Steve Naroff5618bd42008-08-27 16:04:49 +00001346 // Get the new insert position for the node we care about.
1347 BlockPointerType *NewIP =
1348 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001349 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001350 }
John McCall6b304a02009-09-24 23:30:46 +00001351 BlockPointerType *New
1352 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001353 Types.push_back(New);
1354 BlockPointerTypes.InsertNode(New, InsertPos);
1355 return QualType(New, 0);
1356}
1357
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001358/// getLValueReferenceType - Return the uniqued reference to the type for an
1359/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001360QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Unique pointers, to guarantee there is only one pointer of a particular
1362 // structure.
1363 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001364 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001365
1366 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001367 if (LValueReferenceType *RT =
1368 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001370
John McCall54e14c42009-10-22 22:37:11 +00001371 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 // If the referencee type isn't canonical, this won't be a canonical type
1374 // either, so fill in the canonical type field.
1375 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001376 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1377 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1378 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001379
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001381 LValueReferenceType *NewIP =
1382 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001383 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 }
1385
John McCall6b304a02009-09-24 23:30:46 +00001386 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001387 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1388 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001390 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001391
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001392 return QualType(New, 0);
1393}
1394
1395/// getRValueReferenceType - Return the uniqued reference to the type for an
1396/// rvalue reference to the specified type.
1397QualType ASTContext::getRValueReferenceType(QualType T) {
1398 // Unique pointers, to guarantee there is only one pointer of a particular
1399 // structure.
1400 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001401 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001402
1403 void *InsertPos = 0;
1404 if (RValueReferenceType *RT =
1405 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1406 return QualType(RT, 0);
1407
John McCall54e14c42009-10-22 22:37:11 +00001408 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1409
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001410 // If the referencee type isn't canonical, this won't be a canonical type
1411 // either, so fill in the canonical type field.
1412 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001413 if (InnerRef || !T.isCanonical()) {
1414 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1415 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001416
1417 // Get the new insert position for the node we care about.
1418 RValueReferenceType *NewIP =
1419 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1420 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1421 }
1422
John McCall6b304a02009-09-24 23:30:46 +00001423 RValueReferenceType *New
1424 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001425 Types.push_back(New);
1426 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 return QualType(New, 0);
1428}
1429
Sebastian Redlf30208a2009-01-24 21:16:55 +00001430/// getMemberPointerType - Return the uniqued reference to the type for a
1431/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001432QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001433 // Unique pointers, to guarantee there is only one pointer of a particular
1434 // structure.
1435 llvm::FoldingSetNodeID ID;
1436 MemberPointerType::Profile(ID, T, Cls);
1437
1438 void *InsertPos = 0;
1439 if (MemberPointerType *PT =
1440 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1441 return QualType(PT, 0);
1442
1443 // If the pointee or class type isn't canonical, this won't be a canonical
1444 // type either, so fill in the canonical type field.
1445 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001446 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001447 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1448
1449 // Get the new insert position for the node we care about.
1450 MemberPointerType *NewIP =
1451 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1452 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1453 }
John McCall6b304a02009-09-24 23:30:46 +00001454 MemberPointerType *New
1455 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001456 Types.push_back(New);
1457 MemberPointerTypes.InsertNode(New, InsertPos);
1458 return QualType(New, 0);
1459}
1460
Mike Stump1eb44332009-09-09 15:08:12 +00001461/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001462/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001463QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001464 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001465 ArrayType::ArraySizeModifier ASM,
1466 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001467 assert((EltTy->isDependentType() ||
1468 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001469 "Constant array of VLAs is illegal!");
1470
Chris Lattner38aeec72009-05-13 04:12:56 +00001471 // Convert the array size into a canonical width matching the pointer size for
1472 // the target.
1473 llvm::APInt ArySize(ArySizeIn);
1474 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001477 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001480 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001481 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // If the element type isn't canonical, this won't be a canonical type either,
1485 // so fill in the canonical type field.
1486 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001487 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001488 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001489 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001491 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001492 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001493 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 }
Mike Stump1eb44332009-09-09 15:08:12 +00001495
John McCall6b304a02009-09-24 23:30:46 +00001496 ConstantArrayType *New = new(*this,TypeAlignment)
1497 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001498 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 Types.push_back(New);
1500 return QualType(New, 0);
1501}
1502
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001503/// getVariableArrayType - Returns a non-unique reference to the type for a
1504/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001505QualType ASTContext::getVariableArrayType(QualType EltTy,
1506 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001507 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001508 unsigned EltTypeQuals,
1509 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001510 // Since we don't unique expressions, it isn't possible to unique VLA's
1511 // that have an expression provided for their size.
1512
John McCall6b304a02009-09-24 23:30:46 +00001513 VariableArrayType *New = new(*this, TypeAlignment)
1514 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001515
1516 VariableArrayTypes.push_back(New);
1517 Types.push_back(New);
1518 return QualType(New, 0);
1519}
1520
Douglas Gregor898574e2008-12-05 23:32:09 +00001521/// getDependentSizedArrayType - Returns a non-unique reference to
1522/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001523/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001524QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1525 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001526 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001527 unsigned EltTypeQuals,
1528 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001529 assert((!NumElts || NumElts->isTypeDependent() ||
1530 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001531 "Size must be type- or value-dependent!");
1532
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001533 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001534 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001535 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001536
1537 if (NumElts) {
1538 // Dependently-sized array types that do not have a specified
1539 // number of elements will have their sizes deduced from an
1540 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001541 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1542 EltTypeQuals, NumElts);
1543
1544 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1545 }
1546
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001547 DependentSizedArrayType *New;
1548 if (Canon) {
1549 // We already have a canonical version of this array type; use it as
1550 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001551 New = new (*this, TypeAlignment)
1552 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1553 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001554 } else {
1555 QualType CanonEltTy = getCanonicalType(EltTy);
1556 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001557 New = new (*this, TypeAlignment)
1558 DependentSizedArrayType(*this, EltTy, QualType(),
1559 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001560
Douglas Gregor789b1f62010-02-04 18:10:26 +00001561 if (NumElts) {
1562 DependentSizedArrayType *CanonCheck
1563 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1564 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1565 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001566 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001567 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001568 } else {
1569 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1570 ASM, EltTypeQuals,
1571 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001572 New = new (*this, TypeAlignment)
1573 DependentSizedArrayType(*this, EltTy, Canon,
1574 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001575 }
1576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Douglas Gregor898574e2008-12-05 23:32:09 +00001578 Types.push_back(New);
1579 return QualType(New, 0);
1580}
1581
Eli Friedmanc5773c42008-02-15 18:16:39 +00001582QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1583 ArrayType::ArraySizeModifier ASM,
1584 unsigned EltTypeQuals) {
1585 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001586 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001587
1588 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001589 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001590 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1591 return QualType(ATP, 0);
1592
1593 // If the element type isn't canonical, this won't be a canonical type
1594 // either, so fill in the canonical type field.
1595 QualType Canonical;
1596
John McCall467b27b2009-10-22 20:10:53 +00001597 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001598 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001599 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001600
1601 // Get the new insert position for the node we care about.
1602 IncompleteArrayType *NewIP =
1603 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001604 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001605 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001606
John McCall6b304a02009-09-24 23:30:46 +00001607 IncompleteArrayType *New = new (*this, TypeAlignment)
1608 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001609
1610 IncompleteArrayTypes.InsertNode(New, InsertPos);
1611 Types.push_back(New);
1612 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001613}
1614
Steve Naroff73322922007-07-18 18:00:27 +00001615/// getVectorType - Return the unique reference to a vector type of
1616/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001617QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1618 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Chris Lattnerf52ab252008-04-06 22:59:24 +00001621 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001622 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 // Check if we've already instantiated a vector of this type.
1625 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001626 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1627 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 void *InsertPos = 0;
1629 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1630 return QualType(VTP, 0);
1631
1632 // If the element type isn't canonical, this won't be a canonical type either,
1633 // so fill in the canonical type field.
1634 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001635 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1636 Canonical = getVectorType(getCanonicalType(vecType),
1637 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 // Get the new insert position for the node we care about.
1640 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001641 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 }
John McCall6b304a02009-09-24 23:30:46 +00001643 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001644 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 VectorTypes.InsertNode(New, InsertPos);
1646 Types.push_back(New);
1647 return QualType(New, 0);
1648}
1649
Nate Begeman213541a2008-04-18 23:10:10 +00001650/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001651/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001652QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001653 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Chris Lattnerf52ab252008-04-06 22:59:24 +00001655 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001656 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Steve Naroff73322922007-07-18 18:00:27 +00001658 // Check if we've already instantiated a vector of this type.
1659 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001660 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001661 void *InsertPos = 0;
1662 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1663 return QualType(VTP, 0);
1664
1665 // If the element type isn't canonical, this won't be a canonical type either,
1666 // so fill in the canonical type field.
1667 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001668 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001669 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Steve Naroff73322922007-07-18 18:00:27 +00001671 // Get the new insert position for the node we care about.
1672 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001673 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001674 }
John McCall6b304a02009-09-24 23:30:46 +00001675 ExtVectorType *New = new (*this, TypeAlignment)
1676 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001677 VectorTypes.InsertNode(New, InsertPos);
1678 Types.push_back(New);
1679 return QualType(New, 0);
1680}
1681
Mike Stump1eb44332009-09-09 15:08:12 +00001682QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001683 Expr *SizeExpr,
1684 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001685 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001686 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001687 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001689 void *InsertPos = 0;
1690 DependentSizedExtVectorType *Canon
1691 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1692 DependentSizedExtVectorType *New;
1693 if (Canon) {
1694 // We already have a canonical version of this array type; use it as
1695 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001696 New = new (*this, TypeAlignment)
1697 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1698 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001699 } else {
1700 QualType CanonVecTy = getCanonicalType(vecType);
1701 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001702 New = new (*this, TypeAlignment)
1703 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1704 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001705
1706 DependentSizedExtVectorType *CanonCheck
1707 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1708 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1709 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001710 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1711 } else {
1712 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1713 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001714 New = new (*this, TypeAlignment)
1715 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001716 }
1717 }
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001719 Types.push_back(New);
1720 return QualType(New, 0);
1721}
1722
Douglas Gregor72564e72009-02-26 23:50:07 +00001723/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001724///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001725QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1726 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // Unique functions, to guarantee there is only one function of a particular
1728 // structure.
1729 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001730 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001733 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001734 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001738 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001739 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001740 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001741 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001744 FunctionNoProtoType *NewIP =
1745 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001746 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 }
Mike Stump1eb44332009-09-09 15:08:12 +00001748
John McCall6b304a02009-09-24 23:30:46 +00001749 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001750 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001752 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 return QualType(New, 0);
1754}
1755
1756/// getFunctionType - Return a normal function type with a typed argument
1757/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001758QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001759 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001760 unsigned TypeQuals, bool hasExceptionSpec,
1761 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001762 const QualType *ExArray, bool NoReturn,
1763 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 // Unique functions, to guarantee there is only one function of a particular
1765 // structure.
1766 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001767 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001768 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001769 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001770
1771 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001772 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001773 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001775
1776 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001777 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001779 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 isCanonical = false;
1781
1782 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001783 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001785 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 llvm::SmallVector<QualType, 16> CanonicalArgs;
1787 CanonicalArgs.reserve(NumArgs);
1788 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001789 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001790
Chris Lattnerf52ab252008-04-06 22:59:24 +00001791 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001792 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001793 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001794 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001795 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001796
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001798 FunctionProtoType *NewIP =
1799 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001800 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001802
Douglas Gregor72564e72009-02-26 23:50:07 +00001803 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001804 // for two variable size arrays (for parameter and exception types) at the
1805 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001806 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001807 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1808 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001809 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001810 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001811 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001812 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001814 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 return QualType(FTP, 0);
1816}
1817
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001818/// getTypeDeclType - Return the unique reference to the type for the
1819/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001820QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001821 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001822 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001824 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001825 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001826 else if (isa<TemplateTypeParmDecl>(Decl)) {
1827 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001828 } else if (ObjCInterfaceDecl *ObjCInterface
1829 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001830 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001831
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001832 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001833 if (PrevDecl)
1834 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001835 else
John McCall6b304a02009-09-24 23:30:46 +00001836 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001837 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001838 if (PrevDecl)
1839 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001840 else
John McCall6b304a02009-09-24 23:30:46 +00001841 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001842 } else if (UnresolvedUsingTypenameDecl *Using =
1843 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1844 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001845 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001846 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001847
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001848 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001849 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001850}
1851
Reid Spencer5f016e22007-07-11 17:01:13 +00001852/// getTypedefType - Return the unique reference to the type for the
1853/// specified typename decl.
1854QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1855 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Chris Lattnerf52ab252008-04-06 22:59:24 +00001857 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001858 Decl->TypeForDecl = new(*this, TypeAlignment)
1859 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 Types.push_back(Decl->TypeForDecl);
1861 return QualType(Decl->TypeForDecl, 0);
1862}
1863
John McCall49a832b2009-10-18 09:09:24 +00001864/// \brief Retrieve a substitution-result type.
1865QualType
1866ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1867 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001868 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001869 && "replacement types must always be canonical");
1870
1871 llvm::FoldingSetNodeID ID;
1872 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1873 void *InsertPos = 0;
1874 SubstTemplateTypeParmType *SubstParm
1875 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1876
1877 if (!SubstParm) {
1878 SubstParm = new (*this, TypeAlignment)
1879 SubstTemplateTypeParmType(Parm, Replacement);
1880 Types.push_back(SubstParm);
1881 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1882 }
1883
1884 return QualType(SubstParm, 0);
1885}
1886
Douglas Gregorfab9d672009-02-05 23:33:38 +00001887/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001888/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001889/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001890QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001891 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001892 IdentifierInfo *Name) {
1893 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001894 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001895 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001896 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001897 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1898
1899 if (TypeParm)
1900 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001902 if (Name) {
1903 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001904 TypeParm = new (*this, TypeAlignment)
1905 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001906
1907 TemplateTypeParmType *TypeCheck
1908 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1909 assert(!TypeCheck && "Template type parameter canonical type broken");
1910 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001911 } else
John McCall6b304a02009-09-24 23:30:46 +00001912 TypeParm = new (*this, TypeAlignment)
1913 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001914
1915 Types.push_back(TypeParm);
1916 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1917
1918 return QualType(TypeParm, 0);
1919}
1920
Mike Stump1eb44332009-09-09 15:08:12 +00001921QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001922ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001923 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001924 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001925 unsigned NumArgs = Args.size();
1926
John McCall833ca992009-10-29 08:12:44 +00001927 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1928 ArgVec.reserve(NumArgs);
1929 for (unsigned i = 0; i != NumArgs; ++i)
1930 ArgVec.push_back(Args[i].getArgument());
1931
1932 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1933}
1934
1935QualType
1936ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001937 const TemplateArgument *Args,
1938 unsigned NumArgs,
1939 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001940 if (!Canon.isNull())
1941 Canon = getCanonicalType(Canon);
1942 else {
1943 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001944 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1945 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1946 CanonArgs.reserve(NumArgs);
1947 for (unsigned I = 0; I != NumArgs; ++I)
1948 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1949
1950 // Determine whether this canonical template specialization type already
1951 // exists.
1952 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001953 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001954 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001955
1956 void *InsertPos = 0;
1957 TemplateSpecializationType *Spec
1958 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregor1275ae02009-07-28 23:00:59 +00001960 if (!Spec) {
1961 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001962 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001963 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001964 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001965 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001966 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001967 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001968 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001969 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Douglas Gregorb88e8882009-07-30 17:40:51 +00001972 if (Canon.isNull())
1973 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001974 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001975 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001976 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001977
Douglas Gregor1275ae02009-07-28 23:00:59 +00001978 // Allocate the (non-canonical) template specialization type, but don't
1979 // try to unique it: these types typically have location information that
1980 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001981 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001982 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001983 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001984 TemplateSpecializationType *Spec
1985 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001986 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Douglas Gregor55f6b142009-02-09 18:46:07 +00001988 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001989 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001990}
1991
Mike Stump1eb44332009-09-09 15:08:12 +00001992QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001993ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001994 QualType NamedType) {
1995 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001996 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001997
1998 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001999 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00002000 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2001 if (T)
2002 return QualType(T, 0);
2003
Douglas Gregor789b1f62010-02-04 18:10:26 +00002004 QualType Canon = NamedType;
2005 if (!Canon.isCanonical()) {
2006 Canon = getCanonicalType(NamedType);
2007 QualifiedNameType *CheckT
2008 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2009 assert(!CheckT && "Qualified name canonical type broken");
2010 (void)CheckT;
2011 }
2012
2013 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002014 Types.push_back(T);
2015 QualifiedNameTypes.InsertNode(T, InsertPos);
2016 return QualType(T, 0);
2017}
2018
Mike Stump1eb44332009-09-09 15:08:12 +00002019QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002020 const IdentifierInfo *Name,
2021 QualType Canon) {
2022 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2023
2024 if (Canon.isNull()) {
2025 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2026 if (CanonNNS != NNS)
2027 Canon = getTypenameType(CanonNNS, Name);
2028 }
2029
2030 llvm::FoldingSetNodeID ID;
2031 TypenameType::Profile(ID, NNS, Name);
2032
2033 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002034 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002035 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2036 if (T)
2037 return QualType(T, 0);
2038
2039 T = new (*this) TypenameType(NNS, Name, Canon);
2040 Types.push_back(T);
2041 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002042 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002043}
2044
Mike Stump1eb44332009-09-09 15:08:12 +00002045QualType
2046ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002047 const TemplateSpecializationType *TemplateId,
2048 QualType Canon) {
2049 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2050
Douglas Gregor789b1f62010-02-04 18:10:26 +00002051 llvm::FoldingSetNodeID ID;
2052 TypenameType::Profile(ID, NNS, TemplateId);
2053
2054 void *InsertPos = 0;
2055 TypenameType *T
2056 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2057 if (T)
2058 return QualType(T, 0);
2059
Douglas Gregor17343172009-04-01 00:28:59 +00002060 if (Canon.isNull()) {
2061 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2062 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2063 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2064 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002065 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002066 assert(CanonTemplateId &&
2067 "Canonical type must also be a template specialization type");
2068 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2069 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002070
2071 TypenameType *CheckT
2072 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2073 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002074 }
2075
Douglas Gregor17343172009-04-01 00:28:59 +00002076 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2077 Types.push_back(T);
2078 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002079 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002080}
2081
John McCall7da24312009-09-05 00:15:47 +00002082QualType
2083ASTContext::getElaboratedType(QualType UnderlyingType,
2084 ElaboratedType::TagKind Tag) {
2085 llvm::FoldingSetNodeID ID;
2086 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
John McCall7da24312009-09-05 00:15:47 +00002088 void *InsertPos = 0;
2089 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2090 if (T)
2091 return QualType(T, 0);
2092
Douglas Gregor789b1f62010-02-04 18:10:26 +00002093 QualType Canon = UnderlyingType;
2094 if (!Canon.isCanonical()) {
2095 Canon = getCanonicalType(Canon);
2096 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2097 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2098 }
John McCall7da24312009-09-05 00:15:47 +00002099
2100 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2101 Types.push_back(T);
2102 ElaboratedTypes.InsertNode(T, InsertPos);
2103 return QualType(T, 0);
2104}
2105
Chris Lattner88cb27a2008-04-07 04:56:42 +00002106/// CmpProtocolNames - Comparison predicate for sorting protocols
2107/// alphabetically.
2108static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2109 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002110 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002111}
2112
John McCall54e14c42009-10-22 22:37:11 +00002113static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2114 unsigned NumProtocols) {
2115 if (NumProtocols == 0) return true;
2116
2117 for (unsigned i = 1; i != NumProtocols; ++i)
2118 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2119 return false;
2120 return true;
2121}
2122
2123static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002124 unsigned &NumProtocols) {
2125 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Chris Lattner88cb27a2008-04-07 04:56:42 +00002127 // Sort protocols, keyed by name.
2128 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2129
2130 // Remove duplicates.
2131 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2132 NumProtocols = ProtocolsEnd-Protocols;
2133}
2134
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002135/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2136/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002137QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002138 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002139 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002140 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002141 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002142
2143 void *InsertPos = 0;
2144 if (ObjCObjectPointerType *QT =
2145 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2146 return QualType(QT, 0);
2147
John McCall54e14c42009-10-22 22:37:11 +00002148 // Sort the protocol list alphabetically to canonicalize it.
2149 QualType Canonical;
2150 if (!InterfaceT.isCanonical() ||
2151 !areSortedAndUniqued(Protocols, NumProtocols)) {
2152 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2153 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2154 unsigned UniqueCount = NumProtocols;
2155
2156 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2157 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2158
2159 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2160 &Sorted[0], UniqueCount);
2161 } else {
2162 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2163 Protocols, NumProtocols);
2164 }
2165
2166 // Regenerate InsertPos.
2167 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2168 }
2169
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002170 // No match.
2171 unsigned Size = sizeof(ObjCObjectPointerType)
2172 + NumProtocols * sizeof(ObjCProtocolDecl *);
2173 void *Mem = Allocate(Size, TypeAlignment);
2174 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2175 InterfaceT,
2176 Protocols,
2177 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002179 Types.push_back(QType);
2180 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2181 return QualType(QType, 0);
2182}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002183
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002184/// getObjCInterfaceType - Return the unique reference to the type for the
2185/// specified ObjC interface decl. The list of protocols is optional.
2186QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002187 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002188 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002189 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002191 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002192 if (ObjCInterfaceType *QT =
2193 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002194 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002195
John McCall54e14c42009-10-22 22:37:11 +00002196 // Sort the protocol list alphabetically to canonicalize it.
2197 QualType Canonical;
2198 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2199 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2200 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2201
2202 unsigned UniqueCount = NumProtocols;
2203 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2204
2205 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2206
2207 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2208 }
2209
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002210 unsigned Size = sizeof(ObjCInterfaceType)
2211 + NumProtocols * sizeof(ObjCProtocolDecl *);
2212 void *Mem = Allocate(Size, TypeAlignment);
2213 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2214 const_cast<ObjCInterfaceDecl*>(Decl),
2215 Protocols,
2216 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002217
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002218 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002219 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002220 return QualType(QType, 0);
2221}
2222
Douglas Gregor72564e72009-02-26 23:50:07 +00002223/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2224/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002225/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002226/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002227/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002228QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002229 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002230 if (tofExpr->isTypeDependent()) {
2231 llvm::FoldingSetNodeID ID;
2232 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Douglas Gregorb1975722009-07-30 23:18:24 +00002234 void *InsertPos = 0;
2235 DependentTypeOfExprType *Canon
2236 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2237 if (Canon) {
2238 // We already have a "canonical" version of an identical, dependent
2239 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002240 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002241 QualType((TypeOfExprType*)Canon, 0));
2242 }
2243 else {
2244 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002245 Canon
2246 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002247 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2248 toe = Canon;
2249 }
2250 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002251 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002252 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002253 }
Steve Naroff9752f252007-08-01 18:02:17 +00002254 Types.push_back(toe);
2255 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002256}
2257
Steve Naroff9752f252007-08-01 18:02:17 +00002258/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2259/// TypeOfType AST's. The only motivation to unique these nodes would be
2260/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002261/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002262/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002263QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002264 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002265 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002266 Types.push_back(tot);
2267 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002268}
2269
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002270/// getDecltypeForExpr - Given an expr, will return the decltype for that
2271/// expression, according to the rules in C++0x [dcl.type.simple]p4
2272static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002273 if (e->isTypeDependent())
2274 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002276 // If e is an id expression or a class member access, decltype(e) is defined
2277 // as the type of the entity named by e.
2278 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2279 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2280 return VD->getType();
2281 }
2282 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2283 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2284 return FD->getType();
2285 }
2286 // If e is a function call or an invocation of an overloaded operator,
2287 // (parentheses around e are ignored), decltype(e) is defined as the
2288 // return type of that function.
2289 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2290 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002292 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002293
2294 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002295 // defined as T&, otherwise decltype(e) is defined as T.
2296 if (e->isLvalue(Context) == Expr::LV_Valid)
2297 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002299 return T;
2300}
2301
Anders Carlsson395b4752009-06-24 19:06:50 +00002302/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2303/// DecltypeType AST's. The only motivation to unique these nodes would be
2304/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002305/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002306/// on canonical type's (which are always unique).
2307QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002308 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002309 if (e->isTypeDependent()) {
2310 llvm::FoldingSetNodeID ID;
2311 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002313 void *InsertPos = 0;
2314 DependentDecltypeType *Canon
2315 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2316 if (Canon) {
2317 // We already have a "canonical" version of an equivalent, dependent
2318 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002319 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002320 QualType((DecltypeType*)Canon, 0));
2321 }
2322 else {
2323 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002324 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002325 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2326 dt = Canon;
2327 }
2328 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002329 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002330 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002331 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002332 Types.push_back(dt);
2333 return QualType(dt, 0);
2334}
2335
Reid Spencer5f016e22007-07-11 17:01:13 +00002336/// getTagDeclType - Return the unique reference to the type for the
2337/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002338QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002339 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002340 // FIXME: What is the design on getTagDeclType when it requires casting
2341 // away const? mutable?
2342 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002343}
2344
Mike Stump1eb44332009-09-09 15:08:12 +00002345/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2346/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2347/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002348CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002349 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002350}
2351
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002352/// getSignedWCharType - Return the type of "signed wchar_t".
2353/// Used when in C++, as a GCC extension.
2354QualType ASTContext::getSignedWCharType() const {
2355 // FIXME: derive from "Target" ?
2356 return WCharTy;
2357}
2358
2359/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2360/// Used when in C++, as a GCC extension.
2361QualType ASTContext::getUnsignedWCharType() const {
2362 // FIXME: derive from "Target" ?
2363 return UnsignedIntTy;
2364}
2365
Chris Lattner8b9023b2007-07-13 03:05:23 +00002366/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2367/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2368QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002369 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002370}
2371
Chris Lattnere6327742008-04-02 05:18:44 +00002372//===----------------------------------------------------------------------===//
2373// Type Operators
2374//===----------------------------------------------------------------------===//
2375
John McCall54e14c42009-10-22 22:37:11 +00002376CanQualType ASTContext::getCanonicalParamType(QualType T) {
2377 // Push qualifiers into arrays, and then discard any remaining
2378 // qualifiers.
2379 T = getCanonicalType(T);
2380 const Type *Ty = T.getTypePtr();
2381
2382 QualType Result;
2383 if (isa<ArrayType>(Ty)) {
2384 Result = getArrayDecayedType(QualType(Ty,0));
2385 } else if (isa<FunctionType>(Ty)) {
2386 Result = getPointerType(QualType(Ty, 0));
2387 } else {
2388 Result = QualType(Ty, 0);
2389 }
2390
2391 return CanQualType::CreateUnsafe(Result);
2392}
2393
Chris Lattner77c96472008-04-06 22:41:35 +00002394/// getCanonicalType - Return the canonical (structural) type corresponding to
2395/// the specified potentially non-canonical type. The non-canonical version
2396/// of a type may have many "decorated" versions of types. Decorators can
2397/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2398/// to be free of any of these, allowing two canonical types to be compared
2399/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002400CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002401 QualifierCollector Quals;
2402 const Type *Ptr = Quals.strip(T);
2403 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002404
John McCall0953e762009-09-24 19:53:00 +00002405 // The canonical internal type will be the canonical type *except*
2406 // that we push type qualifiers down through array types.
2407
2408 // If there are no new qualifiers to push down, stop here.
2409 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002410 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002411
John McCall0953e762009-09-24 19:53:00 +00002412 // If the type qualifiers are on an array type, get the canonical
2413 // type of the array with the qualifiers applied to the element
2414 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002415 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2416 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002417 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002419 // Get the canonical version of the element with the extra qualifiers on it.
2420 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002421 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002422 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002423
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002424 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002425 return CanQualType::CreateUnsafe(
2426 getConstantArrayType(NewEltTy, CAT->getSize(),
2427 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002428 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002429 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002430 return CanQualType::CreateUnsafe(
2431 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002432 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Douglas Gregor898574e2008-12-05 23:32:09 +00002434 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002435 return CanQualType::CreateUnsafe(
2436 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002437 DSAT->getSizeExpr() ?
2438 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002439 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002440 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002441 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002442
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002443 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002444 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002445 VAT->getSizeExpr() ?
2446 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002447 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002448 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002449 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002450}
2451
Chandler Carruth28e318c2009-12-29 07:16:59 +00002452QualType ASTContext::getUnqualifiedArrayType(QualType T,
2453 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002454 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002455 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002456 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002457 }
2458
Chandler Carruth28e318c2009-12-29 07:16:59 +00002459 const ArrayType *AT = cast<ArrayType>(T);
2460 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002461 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002462 if (Elt == UnqualElt)
2463 return T;
2464
2465 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2466 return getConstantArrayType(UnqualElt, CAT->getSize(),
2467 CAT->getSizeModifier(), 0);
2468 }
2469
2470 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2471 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2472 }
2473
2474 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2475 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2476 DSAT->getSizeModifier(), 0,
2477 SourceRange());
2478}
2479
John McCall80ad16f2009-11-24 18:42:40 +00002480DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2481 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2482 return TD->getDeclName();
2483
2484 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2485 if (DTN->isIdentifier()) {
2486 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2487 } else {
2488 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2489 }
2490 }
2491
John McCall0bd6feb2009-12-02 08:04:21 +00002492 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2493 assert(Storage);
2494 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002495}
2496
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002497TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2498 // If this template name refers to a template, the canonical
2499 // template name merely stores the template itself.
2500 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002501 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002502
John McCall0bd6feb2009-12-02 08:04:21 +00002503 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002505 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2506 assert(DTN && "Non-dependent template names must refer to template decls.");
2507 return DTN->CanonicalTemplateName;
2508}
2509
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002510bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2511 X = getCanonicalTemplateName(X);
2512 Y = getCanonicalTemplateName(Y);
2513 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2514}
2515
Mike Stump1eb44332009-09-09 15:08:12 +00002516TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002517ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2518 switch (Arg.getKind()) {
2519 case TemplateArgument::Null:
2520 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Douglas Gregor1275ae02009-07-28 23:00:59 +00002522 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002523 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Douglas Gregor1275ae02009-07-28 23:00:59 +00002525 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002526 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Douglas Gregor788cd062009-11-11 01:00:40 +00002528 case TemplateArgument::Template:
2529 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2530
Douglas Gregor1275ae02009-07-28 23:00:59 +00002531 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002532 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002533 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Douglas Gregor1275ae02009-07-28 23:00:59 +00002535 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002536 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregor1275ae02009-07-28 23:00:59 +00002538 case TemplateArgument::Pack: {
2539 // FIXME: Allocate in ASTContext
2540 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2541 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002542 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002543 AEnd = Arg.pack_end();
2544 A != AEnd; (void)++A, ++Idx)
2545 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Douglas Gregor1275ae02009-07-28 23:00:59 +00002547 TemplateArgument Result;
2548 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2549 return Result;
2550 }
2551 }
2552
2553 // Silence GCC warning
2554 assert(false && "Unhandled template argument kind");
2555 return TemplateArgument();
2556}
2557
Douglas Gregord57959a2009-03-27 23:10:48 +00002558NestedNameSpecifier *
2559ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002560 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002561 return 0;
2562
2563 switch (NNS->getKind()) {
2564 case NestedNameSpecifier::Identifier:
2565 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002566 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002567 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2568 NNS->getAsIdentifier());
2569
2570 case NestedNameSpecifier::Namespace:
2571 // A namespace is canonical; build a nested-name-specifier with
2572 // this namespace and no prefix.
2573 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2574
2575 case NestedNameSpecifier::TypeSpec:
2576 case NestedNameSpecifier::TypeSpecWithTemplate: {
2577 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002578 return NestedNameSpecifier::Create(*this, 0,
2579 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002580 T.getTypePtr());
2581 }
2582
2583 case NestedNameSpecifier::Global:
2584 // The global specifier is canonical and unique.
2585 return NNS;
2586 }
2587
2588 // Required to silence a GCC warning
2589 return 0;
2590}
2591
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002592
2593const ArrayType *ASTContext::getAsArrayType(QualType T) {
2594 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002595 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002596 // Handle the common positive case fast.
2597 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2598 return AT;
2599 }
Mike Stump1eb44332009-09-09 15:08:12 +00002600
John McCall0953e762009-09-24 19:53:00 +00002601 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002602 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002603 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002604 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002605
John McCall0953e762009-09-24 19:53:00 +00002606 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002607 // implements C99 6.7.3p8: "If the specification of an array type includes
2608 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002610 // If we get here, we either have type qualifiers on the type, or we have
2611 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002612 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002613
John McCall0953e762009-09-24 19:53:00 +00002614 QualifierCollector Qs;
2615 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002617 // If we have a simple case, just return now.
2618 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002619 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002620 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002621
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002622 // Otherwise, we have an array and we have qualifiers on it. Push the
2623 // qualifiers into the array element type and return a new array type.
2624 // Get the canonical version of the element with the extra qualifiers on it.
2625 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002626 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002628 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2629 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2630 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002631 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002632 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2633 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2634 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002635 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002636
Mike Stump1eb44332009-09-09 15:08:12 +00002637 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002638 = dyn_cast<DependentSizedArrayType>(ATy))
2639 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002640 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002641 DSAT->getSizeExpr() ?
2642 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002643 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002644 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002645 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002647 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002648 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002649 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002650 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002651 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002652 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002653 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002654}
2655
2656
Chris Lattnere6327742008-04-02 05:18:44 +00002657/// getArrayDecayedType - Return the properly qualified result of decaying the
2658/// specified array type to a pointer. This operation is non-trivial when
2659/// handling typedefs etc. The canonical type of "T" must be an array type,
2660/// this returns a pointer to a properly qualified element of the array.
2661///
2662/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2663QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002664 // Get the element type with 'getAsArrayType' so that we don't lose any
2665 // typedefs in the element type of the array. This also handles propagation
2666 // of type qualifiers from the array type into the element type if present
2667 // (C99 6.7.3p8).
2668 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2669 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002671 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002672
2673 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002674 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002675}
2676
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002677QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002678 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002679 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002680 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002681 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2682 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002683 } else {
John McCall0953e762009-09-24 19:53:00 +00002684 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002685 }
2686 }
2687}
2688
Anders Carlssonfbbce492009-09-25 01:23:32 +00002689QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2690 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Anders Carlssonfbbce492009-09-25 01:23:32 +00002692 if (const ArrayType *AT = getAsArrayType(ElemTy))
2693 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Anders Carlsson6183a992008-12-21 03:44:36 +00002695 return ElemTy;
2696}
2697
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002698/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002699uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002700ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2701 uint64_t ElementCount = 1;
2702 do {
2703 ElementCount *= CA->getSize().getZExtValue();
2704 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2705 } while (CA);
2706 return ElementCount;
2707}
2708
Reid Spencer5f016e22007-07-11 17:01:13 +00002709/// getFloatingRank - Return a relative rank for floating point types.
2710/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002711static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002712 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002714
John McCall183700f2009-09-21 23:43:11 +00002715 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2716 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002717 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 case BuiltinType::Float: return FloatRank;
2719 case BuiltinType::Double: return DoubleRank;
2720 case BuiltinType::LongDouble: return LongDoubleRank;
2721 }
2722}
2723
Mike Stump1eb44332009-09-09 15:08:12 +00002724/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2725/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002726/// 'typeDomain' is a real floating point or complex type.
2727/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002728QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2729 QualType Domain) const {
2730 FloatingRank EltRank = getFloatingRank(Size);
2731 if (Domain->isComplexType()) {
2732 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002733 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002734 case FloatRank: return FloatComplexTy;
2735 case DoubleRank: return DoubleComplexTy;
2736 case LongDoubleRank: return LongDoubleComplexTy;
2737 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 }
Chris Lattner1361b112008-04-06 23:58:54 +00002739
2740 assert(Domain->isRealFloatingType() && "Unknown domain!");
2741 switch (EltRank) {
2742 default: assert(0 && "getFloatingRank(): illegal value for rank");
2743 case FloatRank: return FloatTy;
2744 case DoubleRank: return DoubleTy;
2745 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002746 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002747}
2748
Chris Lattner7cfeb082008-04-06 23:55:33 +00002749/// getFloatingTypeOrder - Compare the rank of the two specified floating
2750/// point types, ignoring the domain of the type (i.e. 'double' ==
2751/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002752/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002753int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2754 FloatingRank LHSR = getFloatingRank(LHS);
2755 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Chris Lattnera75cea32008-04-06 23:38:49 +00002757 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002758 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002759 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002760 return 1;
2761 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002762}
2763
Chris Lattnerf52ab252008-04-06 22:59:24 +00002764/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2765/// routine will assert if passed a built-in type that isn't an integer or enum,
2766/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002767unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002768 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002769 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002770 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002771
Eli Friedmana3426752009-07-05 23:44:27 +00002772 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2773 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2774
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002775 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2776 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2777
2778 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2779 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2780
Chris Lattnerf52ab252008-04-06 22:59:24 +00002781 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002782 default: assert(0 && "getIntegerRank(): not a built-in integer");
2783 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002784 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002785 case BuiltinType::Char_S:
2786 case BuiltinType::Char_U:
2787 case BuiltinType::SChar:
2788 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002789 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002790 case BuiltinType::Short:
2791 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002792 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002793 case BuiltinType::Int:
2794 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002795 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002796 case BuiltinType::Long:
2797 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002798 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002799 case BuiltinType::LongLong:
2800 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002801 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002802 case BuiltinType::Int128:
2803 case BuiltinType::UInt128:
2804 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002805 }
2806}
2807
Eli Friedman04e83572009-08-20 04:21:42 +00002808/// \brief Whether this is a promotable bitfield reference according
2809/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2810///
2811/// \returns the type this bit-field will promote to, or NULL if no
2812/// promotion occurs.
2813QualType ASTContext::isPromotableBitField(Expr *E) {
2814 FieldDecl *Field = E->getBitField();
2815 if (!Field)
2816 return QualType();
2817
2818 QualType FT = Field->getType();
2819
2820 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2821 uint64_t BitWidth = BitWidthAP.getZExtValue();
2822 uint64_t IntSize = getTypeSize(IntTy);
2823 // GCC extension compatibility: if the bit-field size is less than or equal
2824 // to the size of int, it gets promoted no matter what its type is.
2825 // For instance, unsigned long bf : 4 gets promoted to signed int.
2826 if (BitWidth < IntSize)
2827 return IntTy;
2828
2829 if (BitWidth == IntSize)
2830 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2831
2832 // Types bigger than int are not subject to promotions, and therefore act
2833 // like the base type.
2834 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2835 // is ridiculous.
2836 return QualType();
2837}
2838
Eli Friedmana95d7572009-08-19 07:44:53 +00002839/// getPromotedIntegerType - Returns the type that Promotable will
2840/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2841/// integer type.
2842QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2843 assert(!Promotable.isNull());
2844 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002845 if (const EnumType *ET = Promotable->getAs<EnumType>())
2846 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002847 if (Promotable->isSignedIntegerType())
2848 return IntTy;
2849 uint64_t PromotableSize = getTypeSize(Promotable);
2850 uint64_t IntSize = getTypeSize(IntTy);
2851 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2852 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2853}
2854
Mike Stump1eb44332009-09-09 15:08:12 +00002855/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002856/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002857/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002858int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002859 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2860 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002861 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Chris Lattnerf52ab252008-04-06 22:59:24 +00002863 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2864 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Chris Lattner7cfeb082008-04-06 23:55:33 +00002866 unsigned LHSRank = getIntegerRank(LHSC);
2867 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Chris Lattner7cfeb082008-04-06 23:55:33 +00002869 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2870 if (LHSRank == RHSRank) return 0;
2871 return LHSRank > RHSRank ? 1 : -1;
2872 }
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Chris Lattner7cfeb082008-04-06 23:55:33 +00002874 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2875 if (LHSUnsigned) {
2876 // If the unsigned [LHS] type is larger, return it.
2877 if (LHSRank >= RHSRank)
2878 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Chris Lattner7cfeb082008-04-06 23:55:33 +00002880 // If the signed type can represent all values of the unsigned type, it
2881 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002882 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002883 return -1;
2884 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002885
Chris Lattner7cfeb082008-04-06 23:55:33 +00002886 // If the unsigned [RHS] type is larger, return it.
2887 if (RHSRank >= LHSRank)
2888 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Chris Lattner7cfeb082008-04-06 23:55:33 +00002890 // If the signed type can represent all values of the unsigned type, it
2891 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002892 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002893 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002894}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002895
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002896static RecordDecl *
2897CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2898 SourceLocation L, IdentifierInfo *Id) {
2899 if (Ctx.getLangOptions().CPlusPlus)
2900 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2901 else
2902 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2903}
2904
Mike Stump1eb44332009-09-09 15:08:12 +00002905// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002906QualType ASTContext::getCFConstantStringType() {
2907 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002908 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002909 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2910 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002911 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002912
Anders Carlssonf06273f2007-11-19 00:25:30 +00002913 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002914
Anders Carlsson71993dd2007-08-17 05:31:46 +00002915 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002916 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002917 // int flags;
2918 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002919 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002920 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002921 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002922 FieldTypes[3] = LongTy;
2923
Anders Carlsson71993dd2007-08-17 05:31:46 +00002924 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002925 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002926 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002927 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002928 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002929 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002930 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002931 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002932 }
2933
Douglas Gregor838db382010-02-11 01:19:42 +00002934 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002935 }
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Anders Carlsson71993dd2007-08-17 05:31:46 +00002937 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002938}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002939
Douglas Gregor319ac892009-04-23 22:29:11 +00002940void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002941 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002942 assert(Rec && "Invalid CFConstantStringType");
2943 CFConstantStringTypeDecl = Rec->getDecl();
2944}
2945
Mike Stump1eb44332009-09-09 15:08:12 +00002946QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002947 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002948 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002949 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2950 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002951 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002953 QualType FieldTypes[] = {
2954 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002955 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002956 getPointerType(UnsignedLongTy),
2957 getConstantArrayType(UnsignedLongTy,
2958 llvm::APInt(32, 5), ArrayType::Normal, 0)
2959 };
Mike Stump1eb44332009-09-09 15:08:12 +00002960
Douglas Gregor44b43212008-12-11 16:49:14 +00002961 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002962 FieldDecl *Field = FieldDecl::Create(*this,
2963 ObjCFastEnumerationStateTypeDecl,
2964 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002965 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002966 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002967 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002968 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002969 }
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Douglas Gregor838db382010-02-11 01:19:42 +00002971 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002972 }
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002974 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2975}
2976
Mike Stumpadaaad32009-10-20 02:12:22 +00002977QualType ASTContext::getBlockDescriptorType() {
2978 if (BlockDescriptorType)
2979 return getTagDeclType(BlockDescriptorType);
2980
2981 RecordDecl *T;
2982 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002983 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2984 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00002985 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002986
2987 QualType FieldTypes[] = {
2988 UnsignedLongTy,
2989 UnsignedLongTy,
2990 };
2991
2992 const char *FieldNames[] = {
2993 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002994 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002995 };
2996
2997 for (size_t i = 0; i < 2; ++i) {
2998 FieldDecl *Field = FieldDecl::Create(*this,
2999 T,
3000 SourceLocation(),
3001 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003002 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003003 /*BitWidth=*/0,
3004 /*Mutable=*/false);
3005 T->addDecl(Field);
3006 }
3007
Douglas Gregor838db382010-02-11 01:19:42 +00003008 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003009
3010 BlockDescriptorType = T;
3011
3012 return getTagDeclType(BlockDescriptorType);
3013}
3014
3015void ASTContext::setBlockDescriptorType(QualType T) {
3016 const RecordType *Rec = T->getAs<RecordType>();
3017 assert(Rec && "Invalid BlockDescriptorType");
3018 BlockDescriptorType = Rec->getDecl();
3019}
3020
Mike Stump083c25e2009-10-22 00:49:09 +00003021QualType ASTContext::getBlockDescriptorExtendedType() {
3022 if (BlockDescriptorExtendedType)
3023 return getTagDeclType(BlockDescriptorExtendedType);
3024
3025 RecordDecl *T;
3026 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003027 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3028 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003029 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003030
3031 QualType FieldTypes[] = {
3032 UnsignedLongTy,
3033 UnsignedLongTy,
3034 getPointerType(VoidPtrTy),
3035 getPointerType(VoidPtrTy)
3036 };
3037
3038 const char *FieldNames[] = {
3039 "reserved",
3040 "Size",
3041 "CopyFuncPtr",
3042 "DestroyFuncPtr"
3043 };
3044
3045 for (size_t i = 0; i < 4; ++i) {
3046 FieldDecl *Field = FieldDecl::Create(*this,
3047 T,
3048 SourceLocation(),
3049 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003050 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003051 /*BitWidth=*/0,
3052 /*Mutable=*/false);
3053 T->addDecl(Field);
3054 }
3055
Douglas Gregor838db382010-02-11 01:19:42 +00003056 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003057
3058 BlockDescriptorExtendedType = T;
3059
3060 return getTagDeclType(BlockDescriptorExtendedType);
3061}
3062
3063void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3064 const RecordType *Rec = T->getAs<RecordType>();
3065 assert(Rec && "Invalid BlockDescriptorType");
3066 BlockDescriptorExtendedType = Rec->getDecl();
3067}
3068
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003069bool ASTContext::BlockRequiresCopying(QualType Ty) {
3070 if (Ty->isBlockPointerType())
3071 return true;
3072 if (isObjCNSObjectType(Ty))
3073 return true;
3074 if (Ty->isObjCObjectPointerType())
3075 return true;
3076 return false;
3077}
3078
3079QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3080 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003081 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003082 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003083 // unsigned int __flags;
3084 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003085 // void *__copy_helper; // as needed
3086 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003087 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003088 // } *
3089
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003090 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3091
3092 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003093 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003094 llvm::SmallString<36> Name;
3095 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3096 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003097 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003098 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3099 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003100 T->startDefinition();
3101 QualType Int32Ty = IntTy;
3102 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3103 QualType FieldTypes[] = {
3104 getPointerType(VoidPtrTy),
3105 getPointerType(getTagDeclType(T)),
3106 Int32Ty,
3107 Int32Ty,
3108 getPointerType(VoidPtrTy),
3109 getPointerType(VoidPtrTy),
3110 Ty
3111 };
3112
3113 const char *FieldNames[] = {
3114 "__isa",
3115 "__forwarding",
3116 "__flags",
3117 "__size",
3118 "__copy_helper",
3119 "__destroy_helper",
3120 DeclName,
3121 };
3122
3123 for (size_t i = 0; i < 7; ++i) {
3124 if (!HasCopyAndDispose && i >=4 && i <= 5)
3125 continue;
3126 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3127 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003128 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003129 /*BitWidth=*/0, /*Mutable=*/false);
3130 T->addDecl(Field);
3131 }
3132
Douglas Gregor838db382010-02-11 01:19:42 +00003133 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003134
3135 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003136}
3137
3138
3139QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003140 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003141 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003142 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003143 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003144 llvm::SmallString<36> Name;
3145 llvm::raw_svector_ostream(Name) << "__block_literal_"
3146 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003147 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003148 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3149 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003150 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003151 QualType FieldTypes[] = {
3152 getPointerType(VoidPtrTy),
3153 IntTy,
3154 IntTy,
3155 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003156 (BlockHasCopyDispose ?
3157 getPointerType(getBlockDescriptorExtendedType()) :
3158 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003159 };
3160
3161 const char *FieldNames[] = {
3162 "__isa",
3163 "__flags",
3164 "__reserved",
3165 "__FuncPtr",
3166 "__descriptor"
3167 };
3168
3169 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003170 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003171 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003172 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003173 /*BitWidth=*/0, /*Mutable=*/false);
3174 T->addDecl(Field);
3175 }
3176
3177 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3178 const Expr *E = BlockDeclRefDecls[i];
3179 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3180 clang::IdentifierInfo *Name = 0;
3181 if (BDRE) {
3182 const ValueDecl *D = BDRE->getDecl();
3183 Name = &Idents.get(D->getName());
3184 }
3185 QualType FieldType = E->getType();
3186
3187 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003188 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3189 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003190
3191 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003192 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003193 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003194 T->addDecl(Field);
3195 }
3196
Douglas Gregor838db382010-02-11 01:19:42 +00003197 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003198
3199 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003200}
3201
Douglas Gregor319ac892009-04-23 22:29:11 +00003202void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003203 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003204 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3205 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3206}
3207
Anders Carlssone8c49532007-10-29 06:33:42 +00003208// This returns true if a type has been typedefed to BOOL:
3209// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003210static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003211 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003212 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3213 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003214
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003215 return false;
3216}
3217
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003218/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003219/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003220CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003221 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003223 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003224 if (sz.isPositive() && type->isIntegralType())
3225 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003226 // Treat arrays as pointers, since that's how they're passed in.
3227 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003228 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003229 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003230}
3231
3232static inline
3233std::string charUnitsToString(const CharUnits &CU) {
3234 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003235}
3236
David Chisnall5e530af2009-11-17 19:33:30 +00003237/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3238/// declaration.
3239void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3240 std::string& S) {
3241 const BlockDecl *Decl = Expr->getBlockDecl();
3242 QualType BlockTy =
3243 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3244 // Encode result type.
3245 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3246 // Compute size of all parameters.
3247 // Start with computing size of a pointer in number of bytes.
3248 // FIXME: There might(should) be a better way of doing this computation!
3249 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003250 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3251 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003252 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3253 E = Decl->param_end(); PI != E; ++PI) {
3254 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003255 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003256 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003257 ParmOffset += sz;
3258 }
3259 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003260 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003261 // Block pointer and offset.
3262 S += "@?0";
3263 ParmOffset = PtrSize;
3264
3265 // Argument types.
3266 ParmOffset = PtrSize;
3267 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3268 Decl->param_end(); PI != E; ++PI) {
3269 ParmVarDecl *PVDecl = *PI;
3270 QualType PType = PVDecl->getOriginalType();
3271 if (const ArrayType *AT =
3272 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3273 // Use array's original type only if it has known number of
3274 // elements.
3275 if (!isa<ConstantArrayType>(AT))
3276 PType = PVDecl->getType();
3277 } else if (PType->isFunctionType())
3278 PType = PVDecl->getType();
3279 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003280 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003281 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003282 }
3283}
3284
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003285/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003286/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003287void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003288 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003289 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003290 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003291 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003292 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003293 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003294 // Compute size of all parameters.
3295 // Start with computing size of a pointer in number of bytes.
3296 // FIXME: There might(should) be a better way of doing this computation!
3297 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003298 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003299 // The first two arguments (self and _cmd) are pointers; account for
3300 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003301 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003302 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3303 E = Decl->param_end(); PI != E; ++PI) {
3304 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003305 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003306 assert (sz.isPositive() &&
3307 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003308 ParmOffset += sz;
3309 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003310 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003311 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003312 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003314 // Argument types.
3315 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003316 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3317 E = Decl->param_end(); PI != E; ++PI) {
3318 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003319 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003320 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003321 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3322 // Use array's original type only if it has known number of
3323 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003324 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003325 PType = PVDecl->getType();
3326 } else if (PType->isFunctionType())
3327 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003328 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003329 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003330 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003331 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003332 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003333 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003334 }
3335}
3336
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003337/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003338/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003339/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3340/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003341/// Property attributes are stored as a comma-delimited C string. The simple
3342/// attributes readonly and bycopy are encoded as single characters. The
3343/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3344/// encoded as single characters, followed by an identifier. Property types
3345/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003346/// these attributes are defined by the following enumeration:
3347/// @code
3348/// enum PropertyAttributes {
3349/// kPropertyReadOnly = 'R', // property is read-only.
3350/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3351/// kPropertyByref = '&', // property is a reference to the value last assigned
3352/// kPropertyDynamic = 'D', // property is dynamic
3353/// kPropertyGetter = 'G', // followed by getter selector name
3354/// kPropertySetter = 'S', // followed by setter selector name
3355/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3356/// kPropertyType = 't' // followed by old-style type encoding.
3357/// kPropertyWeak = 'W' // 'weak' property
3358/// kPropertyStrong = 'P' // property GC'able
3359/// kPropertyNonAtomic = 'N' // property non-atomic
3360/// };
3361/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003362void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003363 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003364 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003365 // Collect information from the property implementation decl(s).
3366 bool Dynamic = false;
3367 ObjCPropertyImplDecl *SynthesizePID = 0;
3368
3369 // FIXME: Duplicated code due to poor abstraction.
3370 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003371 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003372 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3373 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003374 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003375 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003376 ObjCPropertyImplDecl *PID = *i;
3377 if (PID->getPropertyDecl() == PD) {
3378 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3379 Dynamic = true;
3380 } else {
3381 SynthesizePID = PID;
3382 }
3383 }
3384 }
3385 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003386 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003387 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003388 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003389 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003390 ObjCPropertyImplDecl *PID = *i;
3391 if (PID->getPropertyDecl() == PD) {
3392 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3393 Dynamic = true;
3394 } else {
3395 SynthesizePID = PID;
3396 }
3397 }
Mike Stump1eb44332009-09-09 15:08:12 +00003398 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003399 }
3400 }
3401
3402 // FIXME: This is not very efficient.
3403 S = "T";
3404
3405 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003406 // GCC has some special rules regarding encoding of properties which
3407 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003408 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003409 true /* outermost type */,
3410 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003411
3412 if (PD->isReadOnly()) {
3413 S += ",R";
3414 } else {
3415 switch (PD->getSetterKind()) {
3416 case ObjCPropertyDecl::Assign: break;
3417 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003418 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003419 }
3420 }
3421
3422 // It really isn't clear at all what this means, since properties
3423 // are "dynamic by default".
3424 if (Dynamic)
3425 S += ",D";
3426
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003427 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3428 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003430 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3431 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003432 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003433 }
3434
3435 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3436 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003437 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003438 }
3439
3440 if (SynthesizePID) {
3441 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3442 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003443 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003444 }
3445
3446 // FIXME: OBJCGC: weak & strong
3447}
3448
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003449/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003450/// Another legacy compatibility encoding: 32-bit longs are encoded as
3451/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003452/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3453///
3454void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003455 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003456 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003457 if (BT->getKind() == BuiltinType::ULong &&
3458 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003459 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003460 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003461 if (BT->getKind() == BuiltinType::Long &&
3462 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003463 PointeeTy = IntTy;
3464 }
3465 }
3466}
3467
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003468void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003469 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003470 // We follow the behavior of gcc, expanding structures which are
3471 // directly pointed to, and expanding embedded structures. Note that
3472 // these rules are sufficient to prevent recursive encoding of the
3473 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003474 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003475 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003476}
3477
Mike Stump1eb44332009-09-09 15:08:12 +00003478static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003479 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003480 const Expr *E = FD->getBitWidth();
3481 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3482 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003483 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003484 S += 'b';
3485 S += llvm::utostr(N);
3486}
3487
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003488// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003489void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3490 bool ExpandPointedToStructures,
3491 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003492 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003493 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003494 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003495 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003496 if (FD && FD->isBitField())
3497 return EncodeBitField(this, S, FD);
3498 char encoding;
3499 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003500 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003501 case BuiltinType::Void: encoding = 'v'; break;
3502 case BuiltinType::Bool: encoding = 'B'; break;
3503 case BuiltinType::Char_U:
3504 case BuiltinType::UChar: encoding = 'C'; break;
3505 case BuiltinType::UShort: encoding = 'S'; break;
3506 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003507 case BuiltinType::ULong:
3508 encoding =
3509 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003510 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003511 case BuiltinType::UInt128: encoding = 'T'; break;
3512 case BuiltinType::ULongLong: encoding = 'Q'; break;
3513 case BuiltinType::Char_S:
3514 case BuiltinType::SChar: encoding = 'c'; break;
3515 case BuiltinType::Short: encoding = 's'; break;
3516 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003517 case BuiltinType::Long:
3518 encoding =
3519 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003520 break;
3521 case BuiltinType::LongLong: encoding = 'q'; break;
3522 case BuiltinType::Int128: encoding = 't'; break;
3523 case BuiltinType::Float: encoding = 'f'; break;
3524 case BuiltinType::Double: encoding = 'd'; break;
3525 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003526 }
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003528 S += encoding;
3529 return;
3530 }
Mike Stump1eb44332009-09-09 15:08:12 +00003531
John McCall183700f2009-09-21 23:43:11 +00003532 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003533 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003534 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003535 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 return;
3537 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003538
Ted Kremenek6217b802009-07-29 21:53:49 +00003539 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003540 if (PT->isObjCSelType()) {
3541 S += ':';
3542 return;
3543 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003544 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003545
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003546 bool isReadOnly = false;
3547 // For historical/compatibility reasons, the read-only qualifier of the
3548 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3549 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003550 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003551 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003552 if (OutermostType && T.isConstQualified()) {
3553 isReadOnly = true;
3554 S += 'r';
3555 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003556 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003557 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003558 while (P->getAs<PointerType>())
3559 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003560 if (P.isConstQualified()) {
3561 isReadOnly = true;
3562 S += 'r';
3563 }
3564 }
3565 if (isReadOnly) {
3566 // Another legacy compatibility encoding. Some ObjC qualifier and type
3567 // combinations need to be rearranged.
3568 // Rewrite "in const" from "nr" to "rn"
3569 const char * s = S.c_str();
3570 int len = S.length();
3571 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3572 std::string replace = "rn";
3573 S.replace(S.end()-2, S.end(), replace);
3574 }
3575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003577 if (PointeeTy->isCharType()) {
3578 // char pointer types should be encoded as '*' unless it is a
3579 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003580 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003581 S += '*';
3582 return;
3583 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003584 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003585 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3586 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3587 S += '#';
3588 return;
3589 }
3590 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3591 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3592 S += '@';
3593 return;
3594 }
3595 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003596 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003597 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003598 getLegacyIntegralTypeEncoding(PointeeTy);
3599
Mike Stump1eb44332009-09-09 15:08:12 +00003600 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003601 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003602 return;
3603 }
Mike Stump1eb44332009-09-09 15:08:12 +00003604
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003605 if (const ArrayType *AT =
3606 // Ignore type qualifiers etc.
3607 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003608 if (isa<IncompleteArrayType>(AT)) {
3609 // Incomplete arrays are encoded as a pointer to the array element.
3610 S += '^';
3611
Mike Stump1eb44332009-09-09 15:08:12 +00003612 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003613 false, ExpandStructures, FD);
3614 } else {
3615 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Anders Carlsson559a8332009-02-22 01:38:57 +00003617 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3618 S += llvm::utostr(CAT->getSize().getZExtValue());
3619 else {
3620 //Variable length arrays are encoded as a regular array with 0 elements.
3621 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3622 S += '0';
3623 }
Mike Stump1eb44332009-09-09 15:08:12 +00003624
3625 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003626 false, ExpandStructures, FD);
3627 S += ']';
3628 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003629 return;
3630 }
Mike Stump1eb44332009-09-09 15:08:12 +00003631
John McCall183700f2009-09-21 23:43:11 +00003632 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003633 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003634 return;
3635 }
Mike Stump1eb44332009-09-09 15:08:12 +00003636
Ted Kremenek6217b802009-07-29 21:53:49 +00003637 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003638 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003639 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003640 // Anonymous structures print as '?'
3641 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3642 S += II->getName();
3643 } else {
3644 S += '?';
3645 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003646 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003647 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003648 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3649 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003650 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003651 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003652 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003653 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003654 S += '"';
3655 }
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003657 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003658 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003659 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003660 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003661 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003662 QualType qt = Field->getType();
3663 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003664 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003665 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003666 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003667 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003668 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003669 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003670 return;
3671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003673 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003674 if (FD && FD->isBitField())
3675 EncodeBitField(this, S, FD);
3676 else
3677 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003678 return;
3679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003681 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003682 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003683 return;
3684 }
Mike Stump1eb44332009-09-09 15:08:12 +00003685
John McCall0953e762009-09-24 19:53:00 +00003686 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003687 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003688 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003689 S += '{';
3690 const IdentifierInfo *II = OI->getIdentifier();
3691 S += II->getName();
3692 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003693 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003694 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003695 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003696 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003697 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003698 RecFields[i]);
3699 else
Mike Stump1eb44332009-09-09 15:08:12 +00003700 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003701 FD);
3702 }
3703 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003704 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003705 }
Mike Stump1eb44332009-09-09 15:08:12 +00003706
John McCall183700f2009-09-21 23:43:11 +00003707 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003708 if (OPT->isObjCIdType()) {
3709 S += '@';
3710 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003711 }
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Steve Naroff27d20a22009-10-28 22:03:49 +00003713 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3714 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3715 // Since this is a binary compatibility issue, need to consult with runtime
3716 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003717 S += '#';
3718 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003719 }
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003721 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003722 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003723 ExpandPointedToStructures,
3724 ExpandStructures, FD);
3725 if (FD || EncodingProperty) {
3726 // Note that we do extended encoding of protocol qualifer list
3727 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003728 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003729 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3730 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003731 S += '<';
3732 S += (*I)->getNameAsString();
3733 S += '>';
3734 }
3735 S += '"';
3736 }
3737 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003738 }
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003740 QualType PointeeTy = OPT->getPointeeType();
3741 if (!EncodingProperty &&
3742 isa<TypedefType>(PointeeTy.getTypePtr())) {
3743 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003744 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003745 // {...};
3746 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003747 getObjCEncodingForTypeImpl(PointeeTy, S,
3748 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003749 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003750 return;
3751 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003752
3753 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003754 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003755 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003756 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003757 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3758 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003759 S += '<';
3760 S += (*I)->getNameAsString();
3761 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003762 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003763 S += '"';
3764 }
3765 return;
3766 }
Mike Stump1eb44332009-09-09 15:08:12 +00003767
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003768 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003769}
3770
Mike Stump1eb44332009-09-09 15:08:12 +00003771void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003772 std::string& S) const {
3773 if (QT & Decl::OBJC_TQ_In)
3774 S += 'n';
3775 if (QT & Decl::OBJC_TQ_Inout)
3776 S += 'N';
3777 if (QT & Decl::OBJC_TQ_Out)
3778 S += 'o';
3779 if (QT & Decl::OBJC_TQ_Bycopy)
3780 S += 'O';
3781 if (QT & Decl::OBJC_TQ_Byref)
3782 S += 'R';
3783 if (QT & Decl::OBJC_TQ_Oneway)
3784 S += 'V';
3785}
3786
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003787void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003788 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003790 BuiltinVaListType = T;
3791}
3792
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003793void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003794 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003795}
3796
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003797void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003798 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003799}
3800
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003801void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003802 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003803}
3804
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003805void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003806 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003807}
3808
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003809void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003810 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003811 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003813 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003814}
3815
John McCall0bd6feb2009-12-02 08:04:21 +00003816/// \brief Retrieve the template name that corresponds to a non-empty
3817/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003818TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3819 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003820 unsigned size = End - Begin;
3821 assert(size > 1 && "set is not overloaded!");
3822
3823 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3824 size * sizeof(FunctionTemplateDecl*));
3825 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3826
3827 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003828 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003829 NamedDecl *D = *I;
3830 assert(isa<FunctionTemplateDecl>(D) ||
3831 (isa<UsingShadowDecl>(D) &&
3832 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3833 *Storage++ = D;
3834 }
3835
3836 return TemplateName(OT);
3837}
3838
Douglas Gregor7532dc62009-03-30 22:58:21 +00003839/// \brief Retrieve the template name that represents a qualified
3840/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003841TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003842 bool TemplateKeyword,
3843 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003844 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003845 llvm::FoldingSetNodeID ID;
3846 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3847
3848 void *InsertPos = 0;
3849 QualifiedTemplateName *QTN =
3850 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3851 if (!QTN) {
3852 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3853 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3854 }
3855
3856 return TemplateName(QTN);
3857}
3858
3859/// \brief Retrieve the template name that represents a dependent
3860/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003861TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003862 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003863 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003864 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003865
3866 llvm::FoldingSetNodeID ID;
3867 DependentTemplateName::Profile(ID, NNS, Name);
3868
3869 void *InsertPos = 0;
3870 DependentTemplateName *QTN =
3871 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3872
3873 if (QTN)
3874 return TemplateName(QTN);
3875
3876 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3877 if (CanonNNS == NNS) {
3878 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3879 } else {
3880 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3881 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003882 DependentTemplateName *CheckQTN =
3883 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3884 assert(!CheckQTN && "Dependent type name canonicalization broken");
3885 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003886 }
3887
3888 DependentTemplateNames.InsertNode(QTN, InsertPos);
3889 return TemplateName(QTN);
3890}
3891
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003892/// \brief Retrieve the template name that represents a dependent
3893/// template name such as \c MetaFun::template operator+.
3894TemplateName
3895ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3896 OverloadedOperatorKind Operator) {
3897 assert((!NNS || NNS->isDependent()) &&
3898 "Nested name specifier must be dependent");
3899
3900 llvm::FoldingSetNodeID ID;
3901 DependentTemplateName::Profile(ID, NNS, Operator);
3902
3903 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003904 DependentTemplateName *QTN
3905 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003906
3907 if (QTN)
3908 return TemplateName(QTN);
3909
3910 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3911 if (CanonNNS == NNS) {
3912 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3913 } else {
3914 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3915 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003916
3917 DependentTemplateName *CheckQTN
3918 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3919 assert(!CheckQTN && "Dependent template name canonicalization broken");
3920 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003921 }
3922
3923 DependentTemplateNames.InsertNode(QTN, InsertPos);
3924 return TemplateName(QTN);
3925}
3926
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003927/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003928/// TargetInfo, produce the corresponding type. The unsigned @p Type
3929/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003930CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003931 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003932 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003933 case TargetInfo::SignedShort: return ShortTy;
3934 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3935 case TargetInfo::SignedInt: return IntTy;
3936 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3937 case TargetInfo::SignedLong: return LongTy;
3938 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3939 case TargetInfo::SignedLongLong: return LongLongTy;
3940 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3941 }
3942
3943 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003944 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003945}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003946
3947//===----------------------------------------------------------------------===//
3948// Type Predicates.
3949//===----------------------------------------------------------------------===//
3950
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003951/// isObjCNSObjectType - Return true if this is an NSObject object using
3952/// NSObject attribute on a c-style pointer type.
3953/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003954/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003955///
3956bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3957 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3958 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003959 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003960 return true;
3961 }
Mike Stump1eb44332009-09-09 15:08:12 +00003962 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003963}
3964
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003965/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3966/// garbage collection attribute.
3967///
John McCall0953e762009-09-24 19:53:00 +00003968Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3969 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003970 if (getLangOptions().ObjC1 &&
3971 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003972 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003973 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003974 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003975 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003976 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003977 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003978 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003979 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003980 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003981 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003982 // Non-pointers have none gc'able attribute regardless of the attribute
3983 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003984 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003985 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003986 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003987 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003988}
3989
Chris Lattner6ac46a42008-04-07 06:51:04 +00003990//===----------------------------------------------------------------------===//
3991// Type Compatibility Testing
3992//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003993
Mike Stump1eb44332009-09-09 15:08:12 +00003994/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003995/// compatible.
3996static bool areCompatVectorTypes(const VectorType *LHS,
3997 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003998 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003999 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004000 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004001}
4002
Steve Naroff4084c302009-07-23 01:01:38 +00004003//===----------------------------------------------------------------------===//
4004// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4005//===----------------------------------------------------------------------===//
4006
4007/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4008/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004009bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4010 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004011 if (lProto == rProto)
4012 return true;
4013 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4014 E = rProto->protocol_end(); PI != E; ++PI)
4015 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4016 return true;
4017 return false;
4018}
4019
Steve Naroff4084c302009-07-23 01:01:38 +00004020/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4021/// return true if lhs's protocols conform to rhs's protocol; false
4022/// otherwise.
4023bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4024 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4025 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4026 return false;
4027}
4028
4029/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4030/// ObjCQualifiedIDType.
4031bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4032 bool compare) {
4033 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004034 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004035 lhs->isObjCIdType() || lhs->isObjCClassType())
4036 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004037 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004038 rhs->isObjCIdType() || rhs->isObjCClassType())
4039 return true;
4040
4041 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004042 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Steve Naroff4084c302009-07-23 01:01:38 +00004044 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Steve Naroff4084c302009-07-23 01:01:38 +00004046 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004047 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004048 // make sure we check the class hierarchy.
4049 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4050 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4051 E = lhsQID->qual_end(); I != E; ++I) {
4052 // when comparing an id<P> on lhs with a static type on rhs,
4053 // see if static class implements all of id's protocols, directly or
4054 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004055 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004056 return false;
4057 }
4058 }
4059 // If there are no qualifiers and no interface, we have an 'id'.
4060 return true;
4061 }
Mike Stump1eb44332009-09-09 15:08:12 +00004062 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004063 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4064 E = lhsQID->qual_end(); I != E; ++I) {
4065 ObjCProtocolDecl *lhsProto = *I;
4066 bool match = false;
4067
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.
4071 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4072 E = rhsOPT->qual_end(); J != E; ++J) {
4073 ObjCProtocolDecl *rhsProto = *J;
4074 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4075 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4076 match = true;
4077 break;
4078 }
4079 }
Mike Stump1eb44332009-09-09 15:08:12 +00004080 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004081 // make sure we check the class hierarchy.
4082 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4083 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4084 E = lhsQID->qual_end(); I != E; ++I) {
4085 // when comparing an id<P> on lhs with a static type on rhs,
4086 // see if static class implements all of id's protocols, directly or
4087 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004088 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004089 match = true;
4090 break;
4091 }
4092 }
4093 }
4094 if (!match)
4095 return false;
4096 }
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Steve Naroff4084c302009-07-23 01:01:38 +00004098 return true;
4099 }
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Steve Naroff4084c302009-07-23 01:01:38 +00004101 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4102 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4103
Mike Stump1eb44332009-09-09 15:08:12 +00004104 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004105 lhs->getAsObjCInterfacePointerType()) {
4106 if (lhsOPT->qual_empty()) {
4107 bool match = false;
4108 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4109 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4110 E = rhsQID->qual_end(); I != E; ++I) {
4111 // when comparing an id<P> on lhs with a static type on rhs,
4112 // see if static class implements all of id's protocols, directly or
4113 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004114 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004115 match = true;
4116 break;
4117 }
4118 }
4119 if (!match)
4120 return false;
4121 }
4122 return true;
4123 }
Mike Stump1eb44332009-09-09 15:08:12 +00004124 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004125 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4126 E = lhsOPT->qual_end(); I != E; ++I) {
4127 ObjCProtocolDecl *lhsProto = *I;
4128 bool match = false;
4129
4130 // when comparing an id<P> on lhs with a static type on rhs,
4131 // see if static class implements all of id's protocols, directly or
4132 // through its super class and categories.
4133 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4134 E = rhsQID->qual_end(); J != E; ++J) {
4135 ObjCProtocolDecl *rhsProto = *J;
4136 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4137 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4138 match = true;
4139 break;
4140 }
4141 }
4142 if (!match)
4143 return false;
4144 }
4145 return true;
4146 }
4147 return false;
4148}
4149
Eli Friedman3d815e72008-08-22 00:56:42 +00004150/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004151/// compatible for assignment from RHS to LHS. This handles validation of any
4152/// protocol qualifiers on the LHS or RHS.
4153///
Steve Naroff14108da2009-07-10 23:34:53 +00004154bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4155 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004156 // If either type represents the built-in 'id' or 'Class' types, return true.
4157 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004158 return true;
4159
Steve Naroff4084c302009-07-23 01:01:38 +00004160 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004161 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4162 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004163 false);
4164
Steve Naroff14108da2009-07-10 23:34:53 +00004165 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4166 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004167 if (LHS && RHS) // We have 2 user-defined types.
4168 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Steve Naroff4084c302009-07-23 01:01:38 +00004170 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004171}
4172
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004173/// getIntersectionOfProtocols - This routine finds the intersection of set
4174/// of protocols inherited from two distinct objective-c pointer objects.
4175/// It is used to build composite qualifier list of the composite type of
4176/// the conditional expression involving two objective-c pointer objects.
4177static
4178void getIntersectionOfProtocols(ASTContext &Context,
4179 const ObjCObjectPointerType *LHSOPT,
4180 const ObjCObjectPointerType *RHSOPT,
4181 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4182
4183 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4184 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4185
4186 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4187 unsigned LHSNumProtocols = LHS->getNumProtocols();
4188 if (LHSNumProtocols > 0)
4189 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4190 else {
4191 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4192 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4193 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4194 LHSInheritedProtocols.end());
4195 }
4196
4197 unsigned RHSNumProtocols = RHS->getNumProtocols();
4198 if (RHSNumProtocols > 0) {
4199 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4200 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4201 if (InheritedProtocolSet.count(RHSProtocols[i]))
4202 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4203 }
4204 else {
4205 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4206 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4207 // FIXME. This may cause duplication of protocols in the list, but should
4208 // be harmless.
4209 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4210 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4211 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4212 }
4213}
4214
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004215/// areCommonBaseCompatible - Returns common base class of the two classes if
4216/// one found. Note that this is O'2 algorithm. But it will be called as the
4217/// last type comparison in a ?-exp of ObjC pointer types before a
4218/// warning is issued. So, its invokation is extremely rare.
4219QualType ASTContext::areCommonBaseCompatible(
4220 const ObjCObjectPointerType *LHSOPT,
4221 const ObjCObjectPointerType *RHSOPT) {
4222 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4223 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4224 if (!LHS || !RHS)
4225 return QualType();
4226
4227 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4228 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4229 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004230 if (canAssignObjCInterfaces(LHS, RHS)) {
4231 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4232 getIntersectionOfProtocols(*this,
4233 LHSOPT, RHSOPT, IntersectionOfProtocols);
4234 if (IntersectionOfProtocols.empty())
4235 LHSTy = getObjCObjectPointerType(LHSTy);
4236 else
4237 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4238 IntersectionOfProtocols.size());
4239 return LHSTy;
4240 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004241 }
4242
4243 return QualType();
4244}
4245
Eli Friedman3d815e72008-08-22 00:56:42 +00004246bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4247 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004248 // Verify that the base decls are compatible: the RHS must be a subclass of
4249 // the LHS.
4250 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4251 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Chris Lattner6ac46a42008-04-07 06:51:04 +00004253 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4254 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004255 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004256 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Chris Lattner6ac46a42008-04-07 06:51:04 +00004258 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4259 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004260 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004261 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004262
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004263 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4264 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004265 LHSPI != LHSPE; LHSPI++) {
4266 bool RHSImplementsProtocol = false;
4267
4268 // If the RHS doesn't implement the protocol on the left, the types
4269 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004270 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004271 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004272 RHSPI != RHSPE; RHSPI++) {
4273 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004274 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004275 break;
4276 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004277 }
4278 // FIXME: For better diagnostics, consider passing back the protocol name.
4279 if (!RHSImplementsProtocol)
4280 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004281 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004282 // The RHS implements all protocols listed on the LHS.
4283 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004284}
4285
Steve Naroff389bf462009-02-12 17:52:19 +00004286bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4287 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004288 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4289 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004290
Steve Naroff14108da2009-07-10 23:34:53 +00004291 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004292 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004293
4294 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4295 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004296}
4297
Mike Stump1eb44332009-09-09 15:08:12 +00004298/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004299/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004300/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004301/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004302bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004303 if (getLangOptions().CPlusPlus)
4304 return hasSameType(LHS, RHS);
4305
Eli Friedman3d815e72008-08-22 00:56:42 +00004306 return !mergeTypes(LHS, RHS).isNull();
4307}
4308
4309QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004310 const FunctionType *lbase = lhs->getAs<FunctionType>();
4311 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004312 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4313 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004314 bool allLTypes = true;
4315 bool allRTypes = true;
4316
4317 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004318 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004319 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004320 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004321 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004322 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004323 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004324 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004325 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4326 if (NoReturn != lbase->getNoReturnAttr())
4327 allLTypes = false;
4328 if (NoReturn != rbase->getNoReturnAttr())
4329 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004330 CallingConv lcc = lbase->getCallConv();
4331 CallingConv rcc = rbase->getCallConv();
4332 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004333 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004334 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Eli Friedman3d815e72008-08-22 00:56:42 +00004336 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004337 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4338 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004339 unsigned lproto_nargs = lproto->getNumArgs();
4340 unsigned rproto_nargs = rproto->getNumArgs();
4341
4342 // Compatible functions must have the same number of arguments
4343 if (lproto_nargs != rproto_nargs)
4344 return QualType();
4345
4346 // Variadic and non-variadic functions aren't compatible
4347 if (lproto->isVariadic() != rproto->isVariadic())
4348 return QualType();
4349
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004350 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4351 return QualType();
4352
Eli Friedman3d815e72008-08-22 00:56:42 +00004353 // Check argument compatibility
4354 llvm::SmallVector<QualType, 10> types;
4355 for (unsigned i = 0; i < lproto_nargs; i++) {
4356 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4357 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4358 QualType argtype = mergeTypes(largtype, rargtype);
4359 if (argtype.isNull()) return QualType();
4360 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004361 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4362 allLTypes = false;
4363 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4364 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004365 }
4366 if (allLTypes) return lhs;
4367 if (allRTypes) return rhs;
4368 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004369 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004370 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004371 }
4372
4373 if (lproto) allRTypes = false;
4374 if (rproto) allLTypes = false;
4375
Douglas Gregor72564e72009-02-26 23:50:07 +00004376 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004377 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004378 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004379 if (proto->isVariadic()) return QualType();
4380 // Check that the types are compatible with the types that
4381 // would result from default argument promotions (C99 6.7.5.3p15).
4382 // The only types actually affected are promotable integer
4383 // types and floats, which would be passed as a different
4384 // type depending on whether the prototype is visible.
4385 unsigned proto_nargs = proto->getNumArgs();
4386 for (unsigned i = 0; i < proto_nargs; ++i) {
4387 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004388
4389 // Look at the promotion type of enum types, since that is the type used
4390 // to pass enum values.
4391 if (const EnumType *Enum = argTy->getAs<EnumType>())
4392 argTy = Enum->getDecl()->getPromotionType();
4393
Eli Friedman3d815e72008-08-22 00:56:42 +00004394 if (argTy->isPromotableIntegerType() ||
4395 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4396 return QualType();
4397 }
4398
4399 if (allLTypes) return lhs;
4400 if (allRTypes) return rhs;
4401 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004402 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004403 proto->getTypeQuals(), NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004404 }
4405
4406 if (allLTypes) return lhs;
4407 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004408 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004409}
4410
4411QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004412 // C++ [expr]: If an expression initially has the type "reference to T", the
4413 // type is adjusted to "T" prior to any further analysis, the expression
4414 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004415 // expression is an lvalue unless the reference is an rvalue reference and
4416 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004417 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4418 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4419
Eli Friedman3d815e72008-08-22 00:56:42 +00004420 QualType LHSCan = getCanonicalType(LHS),
4421 RHSCan = getCanonicalType(RHS);
4422
4423 // If two types are identical, they are compatible.
4424 if (LHSCan == RHSCan)
4425 return LHS;
4426
John McCall0953e762009-09-24 19:53:00 +00004427 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004428 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4429 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004430 if (LQuals != RQuals) {
4431 // If any of these qualifiers are different, we have a type
4432 // mismatch.
4433 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4434 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4435 return QualType();
4436
4437 // Exactly one GC qualifier difference is allowed: __strong is
4438 // okay if the other type has no GC qualifier but is an Objective
4439 // C object pointer (i.e. implicitly strong by default). We fix
4440 // this by pretending that the unqualified type was actually
4441 // qualified __strong.
4442 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4443 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4444 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4445
4446 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4447 return QualType();
4448
4449 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4450 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4451 }
4452 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4453 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4454 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004455 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004456 }
4457
4458 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004459
Eli Friedman852d63b2009-06-01 01:22:52 +00004460 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4461 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004462
Chris Lattner1adb8832008-01-14 05:45:46 +00004463 // We want to consider the two function types to be the same for these
4464 // comparisons, just force one to the other.
4465 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4466 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004467
4468 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004469 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4470 LHSClass = Type::ConstantArray;
4471 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4472 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Nate Begeman213541a2008-04-18 23:10:10 +00004474 // Canonicalize ExtVector -> Vector.
4475 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4476 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Chris Lattnera36a61f2008-04-07 05:43:21 +00004478 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004479 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004480 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004481 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004482 // Compatibility is based on the underlying type, not the promotion
4483 // type.
John McCall183700f2009-09-21 23:43:11 +00004484 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004485 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4486 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004487 }
John McCall183700f2009-09-21 23:43:11 +00004488 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004489 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4490 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004491 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004492
Eli Friedman3d815e72008-08-22 00:56:42 +00004493 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004494 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004495
Steve Naroff4a746782008-01-09 22:43:08 +00004496 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004497 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004498#define TYPE(Class, Base)
4499#define ABSTRACT_TYPE(Class, Base)
4500#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4501#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4502#include "clang/AST/TypeNodes.def"
4503 assert(false && "Non-canonical and dependent types shouldn't get here");
4504 return QualType();
4505
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004506 case Type::LValueReference:
4507 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004508 case Type::MemberPointer:
4509 assert(false && "C++ should never be in mergeTypes");
4510 return QualType();
4511
4512 case Type::IncompleteArray:
4513 case Type::VariableArray:
4514 case Type::FunctionProto:
4515 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004516 assert(false && "Types are eliminated above");
4517 return QualType();
4518
Chris Lattner1adb8832008-01-14 05:45:46 +00004519 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004520 {
4521 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004522 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4523 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004524 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4525 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004526 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004527 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004528 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004529 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004530 return getPointerType(ResultType);
4531 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004532 case Type::BlockPointer:
4533 {
4534 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004535 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4536 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004537 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4538 if (ResultType.isNull()) return QualType();
4539 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4540 return LHS;
4541 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4542 return RHS;
4543 return getBlockPointerType(ResultType);
4544 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004545 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004546 {
4547 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4548 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4549 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4550 return QualType();
4551
4552 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4553 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4554 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4555 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004556 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4557 return LHS;
4558 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4559 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004560 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4561 ArrayType::ArraySizeModifier(), 0);
4562 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4563 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004564 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4565 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004566 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4567 return LHS;
4568 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4569 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004570 if (LVAT) {
4571 // FIXME: This isn't correct! But tricky to implement because
4572 // the array's size has to be the size of LHS, but the type
4573 // has to be different.
4574 return LHS;
4575 }
4576 if (RVAT) {
4577 // FIXME: This isn't correct! But tricky to implement because
4578 // the array's size has to be the size of RHS, but the type
4579 // has to be different.
4580 return RHS;
4581 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004582 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4583 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004584 return getIncompleteArrayType(ResultType,
4585 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004586 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004587 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004588 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004589 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004590 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004591 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004592 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004593 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004594 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004595 case Type::Complex:
4596 // Distinct complex types are incompatible.
4597 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004598 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004599 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004600 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004601 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004602 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004603 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004604 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004605 // FIXME: This should be type compatibility, e.g. whether
4606 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004607 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4608 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004609 if (LHSIface && RHSIface &&
4610 canAssignObjCInterfaces(LHSIface, RHSIface))
4611 return LHS;
4612
Eli Friedman3d815e72008-08-22 00:56:42 +00004613 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004614 }
Steve Naroff14108da2009-07-10 23:34:53 +00004615 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004616 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4617 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004618 return LHS;
4619
Steve Naroffbc76dd02008-12-10 22:14:21 +00004620 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004621 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00004622 case Type::TemplateSpecialization:
4623 assert(false && "Dependent types have no size");
4624 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004625 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004626
4627 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004628}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004629
Chris Lattner5426bf62008-04-07 07:01:58 +00004630//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004631// Integer Predicates
4632//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004633
Eli Friedmanad74a752008-06-28 06:23:08 +00004634unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004635 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004636 return 1;
John McCall842aef82009-12-09 09:09:27 +00004637 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004638 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004639 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004640 return (unsigned)getTypeSize(T);
4641}
4642
4643QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4644 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004645
4646 // Turn <4 x signed int> -> <4 x unsigned int>
4647 if (const VectorType *VTy = T->getAs<VectorType>())
4648 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004649 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004650
4651 // For enums, we return the unsigned version of the base type.
4652 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004653 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004654
4655 const BuiltinType *BTy = T->getAs<BuiltinType>();
4656 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004657 switch (BTy->getKind()) {
4658 case BuiltinType::Char_S:
4659 case BuiltinType::SChar:
4660 return UnsignedCharTy;
4661 case BuiltinType::Short:
4662 return UnsignedShortTy;
4663 case BuiltinType::Int:
4664 return UnsignedIntTy;
4665 case BuiltinType::Long:
4666 return UnsignedLongTy;
4667 case BuiltinType::LongLong:
4668 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004669 case BuiltinType::Int128:
4670 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004671 default:
4672 assert(0 && "Unexpected signed integer type");
4673 return QualType();
4674 }
4675}
4676
Douglas Gregor2cf26342009-04-09 22:27:44 +00004677ExternalASTSource::~ExternalASTSource() { }
4678
4679void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004680
4681
4682//===----------------------------------------------------------------------===//
4683// Builtin Type Computation
4684//===----------------------------------------------------------------------===//
4685
4686/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4687/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004688static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004689 ASTContext::GetBuiltinTypeError &Error,
4690 bool AllowTypeModifiers = true) {
4691 // Modifiers.
4692 int HowLong = 0;
4693 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Chris Lattner86df27b2009-06-14 00:45:47 +00004695 // Read the modifiers first.
4696 bool Done = false;
4697 while (!Done) {
4698 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004699 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004700 case 'S':
4701 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4702 assert(!Signed && "Can't use 'S' modifier multiple times!");
4703 Signed = true;
4704 break;
4705 case 'U':
4706 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4707 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4708 Unsigned = true;
4709 break;
4710 case 'L':
4711 assert(HowLong <= 2 && "Can't have LLLL modifier");
4712 ++HowLong;
4713 break;
4714 }
4715 }
4716
4717 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Chris Lattner86df27b2009-06-14 00:45:47 +00004719 // Read the base type.
4720 switch (*Str++) {
4721 default: assert(0 && "Unknown builtin type letter!");
4722 case 'v':
4723 assert(HowLong == 0 && !Signed && !Unsigned &&
4724 "Bad modifiers used with 'v'!");
4725 Type = Context.VoidTy;
4726 break;
4727 case 'f':
4728 assert(HowLong == 0 && !Signed && !Unsigned &&
4729 "Bad modifiers used with 'f'!");
4730 Type = Context.FloatTy;
4731 break;
4732 case 'd':
4733 assert(HowLong < 2 && !Signed && !Unsigned &&
4734 "Bad modifiers used with 'd'!");
4735 if (HowLong)
4736 Type = Context.LongDoubleTy;
4737 else
4738 Type = Context.DoubleTy;
4739 break;
4740 case 's':
4741 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4742 if (Unsigned)
4743 Type = Context.UnsignedShortTy;
4744 else
4745 Type = Context.ShortTy;
4746 break;
4747 case 'i':
4748 if (HowLong == 3)
4749 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4750 else if (HowLong == 2)
4751 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4752 else if (HowLong == 1)
4753 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4754 else
4755 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4756 break;
4757 case 'c':
4758 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4759 if (Signed)
4760 Type = Context.SignedCharTy;
4761 else if (Unsigned)
4762 Type = Context.UnsignedCharTy;
4763 else
4764 Type = Context.CharTy;
4765 break;
4766 case 'b': // boolean
4767 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4768 Type = Context.BoolTy;
4769 break;
4770 case 'z': // size_t.
4771 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4772 Type = Context.getSizeType();
4773 break;
4774 case 'F':
4775 Type = Context.getCFConstantStringType();
4776 break;
4777 case 'a':
4778 Type = Context.getBuiltinVaListType();
4779 assert(!Type.isNull() && "builtin va list type not initialized!");
4780 break;
4781 case 'A':
4782 // This is a "reference" to a va_list; however, what exactly
4783 // this means depends on how va_list is defined. There are two
4784 // different kinds of va_list: ones passed by value, and ones
4785 // passed by reference. An example of a by-value va_list is
4786 // x86, where va_list is a char*. An example of by-ref va_list
4787 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4788 // we want this argument to be a char*&; for x86-64, we want
4789 // it to be a __va_list_tag*.
4790 Type = Context.getBuiltinVaListType();
4791 assert(!Type.isNull() && "builtin va list type not initialized!");
4792 if (Type->isArrayType()) {
4793 Type = Context.getArrayDecayedType(Type);
4794 } else {
4795 Type = Context.getLValueReferenceType(Type);
4796 }
4797 break;
4798 case 'V': {
4799 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004800 unsigned NumElements = strtoul(Str, &End, 10);
4801 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Chris Lattner86df27b2009-06-14 00:45:47 +00004803 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004804
Chris Lattner86df27b2009-06-14 00:45:47 +00004805 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004806 // FIXME: Don't know what to do about AltiVec.
4807 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004808 break;
4809 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004810 case 'X': {
4811 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4812 Type = Context.getComplexType(ElementType);
4813 break;
4814 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004815 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004816 Type = Context.getFILEType();
4817 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004818 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004819 return QualType();
4820 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004821 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004822 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004823 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004824 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004825 else
4826 Type = Context.getjmp_bufType();
4827
Mike Stumpfd612db2009-07-28 23:47:15 +00004828 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004829 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004830 return QualType();
4831 }
4832 break;
Mike Stump782fa302009-07-28 02:25:19 +00004833 }
Mike Stump1eb44332009-09-09 15:08:12 +00004834
Chris Lattner86df27b2009-06-14 00:45:47 +00004835 if (!AllowTypeModifiers)
4836 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004837
Chris Lattner86df27b2009-06-14 00:45:47 +00004838 Done = false;
4839 while (!Done) {
4840 switch (*Str++) {
4841 default: Done = true; --Str; break;
4842 case '*':
4843 Type = Context.getPointerType(Type);
4844 break;
4845 case '&':
4846 Type = Context.getLValueReferenceType(Type);
4847 break;
4848 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4849 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004850 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004851 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004852 case 'D':
4853 Type = Context.getVolatileType(Type);
4854 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004855 }
4856 }
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Chris Lattner86df27b2009-06-14 00:45:47 +00004858 return Type;
4859}
4860
4861/// GetBuiltinType - Return the type for the specified builtin.
4862QualType ASTContext::GetBuiltinType(unsigned id,
4863 GetBuiltinTypeError &Error) {
4864 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Chris Lattner86df27b2009-06-14 00:45:47 +00004866 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Chris Lattner86df27b2009-06-14 00:45:47 +00004868 Error = GE_None;
4869 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4870 if (Error != GE_None)
4871 return QualType();
4872 while (TypeStr[0] && TypeStr[0] != '.') {
4873 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4874 if (Error != GE_None)
4875 return QualType();
4876
4877 // Do array -> pointer decay. The builtin should use the decayed type.
4878 if (Ty->isArrayType())
4879 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Chris Lattner86df27b2009-06-14 00:45:47 +00004881 ArgTypes.push_back(Ty);
4882 }
4883
4884 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4885 "'.' should only occur at end of builtin type list!");
4886
4887 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4888 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4889 return getFunctionNoProtoType(ResType);
4890 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4891 TypeStr[0] == '.', 0);
4892}
Eli Friedmana95d7572009-08-19 07:44:53 +00004893
4894QualType
4895ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4896 // Perform the usual unary conversions. We do this early so that
4897 // integral promotions to "int" can allow us to exit early, in the
4898 // lhs == rhs check. Also, for conversion purposes, we ignore any
4899 // qualifiers. For example, "const float" and "float" are
4900 // equivalent.
4901 if (lhs->isPromotableIntegerType())
4902 lhs = getPromotedIntegerType(lhs);
4903 else
4904 lhs = lhs.getUnqualifiedType();
4905 if (rhs->isPromotableIntegerType())
4906 rhs = getPromotedIntegerType(rhs);
4907 else
4908 rhs = rhs.getUnqualifiedType();
4909
4910 // If both types are identical, no conversion is needed.
4911 if (lhs == rhs)
4912 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004913
Eli Friedmana95d7572009-08-19 07:44:53 +00004914 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4915 // The caller can deal with this (e.g. pointer + int).
4916 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4917 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004918
4919 // At this point, we have two different arithmetic types.
4920
Eli Friedmana95d7572009-08-19 07:44:53 +00004921 // Handle complex types first (C99 6.3.1.8p1).
4922 if (lhs->isComplexType() || rhs->isComplexType()) {
4923 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004924 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004925 // convert the rhs to the lhs complex type.
4926 return lhs;
4927 }
Mike Stump1eb44332009-09-09 15:08:12 +00004928 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004929 // convert the lhs to the rhs complex type.
4930 return rhs;
4931 }
4932 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004933 // When both operands are complex, the shorter operand is converted to the
4934 // type of the longer, and that is the type of the result. This corresponds
4935 // to what is done when combining two real floating-point operands.
4936 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004937 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004938 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004939 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004940 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004941 // "double _Complex" is promoted to "long double _Complex".
4942 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004943
4944 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004945 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004946 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004947 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004948 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004949 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4950 // domains match. This is a requirement for our implementation, C99
4951 // does not require this promotion.
4952 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4953 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4954 return rhs;
4955 } else { // handle "_Complex double, double".
4956 return lhs;
4957 }
4958 }
4959 return lhs; // The domain/size match exactly.
4960 }
4961 // Now handle "real" floating types (i.e. float, double, long double).
4962 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4963 // if we have an integer operand, the result is the real floating type.
4964 if (rhs->isIntegerType()) {
4965 // convert rhs to the lhs floating point type.
4966 return lhs;
4967 }
4968 if (rhs->isComplexIntegerType()) {
4969 // convert rhs to the complex floating point type.
4970 return getComplexType(lhs);
4971 }
4972 if (lhs->isIntegerType()) {
4973 // convert lhs to the rhs floating point type.
4974 return rhs;
4975 }
Mike Stump1eb44332009-09-09 15:08:12 +00004976 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004977 // convert lhs to the complex floating point type.
4978 return getComplexType(rhs);
4979 }
4980 // We have two real floating types, float/complex combos were handled above.
4981 // Convert the smaller operand to the bigger result.
4982 int result = getFloatingTypeOrder(lhs, rhs);
4983 if (result > 0) // convert the rhs
4984 return lhs;
4985 assert(result < 0 && "illegal float comparison");
4986 return rhs; // convert the lhs
4987 }
4988 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4989 // Handle GCC complex int extension.
4990 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4991 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4992
4993 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004994 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004995 rhsComplexInt->getElementType()) >= 0)
4996 return lhs; // convert the rhs
4997 return rhs;
4998 } else if (lhsComplexInt && rhs->isIntegerType()) {
4999 // convert the rhs to the lhs complex type.
5000 return lhs;
5001 } else if (rhsComplexInt && lhs->isIntegerType()) {
5002 // convert the lhs to the rhs complex type.
5003 return rhs;
5004 }
5005 }
5006 // Finally, we have two differing integer types.
5007 // The rules for this case are in C99 6.3.1.8
5008 int compare = getIntegerTypeOrder(lhs, rhs);
5009 bool lhsSigned = lhs->isSignedIntegerType(),
5010 rhsSigned = rhs->isSignedIntegerType();
5011 QualType destType;
5012 if (lhsSigned == rhsSigned) {
5013 // Same signedness; use the higher-ranked type
5014 destType = compare >= 0 ? lhs : rhs;
5015 } else if (compare != (lhsSigned ? 1 : -1)) {
5016 // The unsigned type has greater than or equal rank to the
5017 // signed type, so use the unsigned type
5018 destType = lhsSigned ? rhs : lhs;
5019 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5020 // The two types are different widths; if we are here, that
5021 // means the signed type is larger than the unsigned type, so
5022 // use the signed type.
5023 destType = lhsSigned ? lhs : rhs;
5024 } else {
5025 // The signed type is higher-ranked than the unsigned type,
5026 // but isn't actually any bigger (like unsigned int and long
5027 // on most 32-bit systems). Use the unsigned type corresponding
5028 // to the signed type.
5029 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5030 }
5031 return destType;
5032}