blob: c9d85c84f964665a001695e23d0843ad6f20fcc1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000059 if (FreeMemory) {
60 // Deallocate all the types.
61 while (!Types.empty()) {
62 Types.back()->Destroy(*this);
63 Types.pop_back();
64 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000065
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000066 for (llvm::FoldingSet<ExtQuals>::iterator
67 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
68 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000069 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 }
71 }
72
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000073 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
74 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
75 // Increment in loop to prevent using deallocated memory.
76 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
77 delete R;
78 }
79
80 for (llvm::DenseMap<const ObjCContainerDecl*,
81 const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
83 // Increment in loop to prevent using deallocated memory.
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
Nuno Lopesb74668e2008-12-17 22:30:25 +000086 }
87
Douglas Gregorab452ba2009-03-26 23:50:42 +000088 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000089 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000091 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000092 NNS != NNSEnd; ) {
93 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000095 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000263ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000265 = InstantiatedFromUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
John McCalled976492009-12-04 22:46:56 +0000273ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
274 assert((isa<UsingDecl>(Pattern) ||
275 isa<UnresolvedUsingValueDecl>(Pattern) ||
276 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277 "pattern decl is not a using decl");
278 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279 InstantiatedFromUsingDecl[Inst] = Pattern;
280}
281
282UsingShadowDecl *
283ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
284 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
285 = InstantiatedFromUsingShadowDecl.find(Inst);
286 if (Pos == InstantiatedFromUsingShadowDecl.end())
287 return 0;
288
289 return Pos->second;
290}
291
292void
293ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294 UsingShadowDecl *Pattern) {
295 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
296 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000297}
298
Anders Carlssond8b285f2009-09-01 04:26:58 +0000299FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301 = InstantiatedFromUnnamedFieldDecl.find(Field);
302 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Anders Carlssond8b285f2009-09-01 04:26:58 +0000305 return Pos->second;
306}
307
308void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309 FieldDecl *Tmpl) {
310 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
311 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316}
317
Douglas Gregor2e222532009-07-02 17:08:52 +0000318namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 : std::binary_function<SourceRange, SourceRange, bool> {
321 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Douglas Gregor2e222532009-07-02 17:08:52 +0000323 public:
324 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 bool operator()(SourceRange X, SourceRange Y) {
327 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328 }
329 };
330}
331
332/// \brief Determine whether the given comment is a Doxygen-style comment.
333///
334/// \param Start the start of the comment text.
335///
336/// \param End the end of the comment text.
337///
338/// \param Member whether we want to check whether this is a member comment
339/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
340/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000341static bool
342isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000343 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000345 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
346 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
347 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 if (End - Start < 4)
350 return false;
351
352 assert(Start[0] == '/' && "Not a comment?");
353 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
354 return false;
355 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
356 return false;
357
358 return (Start[3] == '<') == Member;
359}
360
361/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000362/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000363const char *ASTContext::getCommentForDecl(const Decl *D) {
364 if (!D)
365 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Douglas Gregor2e222532009-07-02 17:08:52 +0000367 // Check whether we have cached a comment string for this declaration
368 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000369 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000370 = DeclComments.find(D);
371 if (Pos != DeclComments.end())
372 return Pos->second.c_str();
373
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000375 // that source, do so now.
376 if (ExternalSource && !LoadedExternalComments) {
377 std::vector<SourceRange> LoadedComments;
378 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 if (!LoadedComments.empty())
381 Comments.insert(Comments.begin(), LoadedComments.begin(),
382 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 LoadedExternalComments = true;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
387 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 if (Comments.empty())
389 return 0;
390
391 // If the declaration doesn't map directly to a location in a file, we
392 // can't find the comment.
393 SourceLocation DeclStartLoc = D->getLocStart();
394 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
395 return 0;
396
397 // Find the comment that occurs just before this declaration.
398 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000399 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000400 SourceRange(DeclStartLoc),
401 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 // Decompose the location for the start of the declaration and find the
404 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000406 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000407 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 // First check whether we have a comment for a member.
411 if (LastComment != Comments.end() &&
412 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
413 isDoxygenComment(SourceMgr, *LastComment, true)) {
414 std::pair<FileID, unsigned> LastCommentEndDecomp
415 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
416 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000418 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000419 LastCommentEndDecomp.second)) {
420 // The Doxygen member comment comes after the declaration starts and
421 // is on the same line and in the same file as the declaration. This
422 // is the comment we want.
423 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000424 Result.append(FileBufferStart +
425 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000426 FileBufferStart + LastCommentEndDecomp.second + 1);
427 return Result.c_str();
428 }
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Douglas Gregor2e222532009-07-02 17:08:52 +0000431 if (LastComment == Comments.begin())
432 return 0;
433 --LastComment;
434
435 // Decompose the end of the comment.
436 std::pair<FileID, unsigned> LastCommentEndDecomp
437 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor2e222532009-07-02 17:08:52 +0000439 // If the comment and the declaration aren't in the same file, then they
440 // aren't related.
441 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
442 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor2e222532009-07-02 17:08:52 +0000444 // Check that we actually have a Doxygen comment.
445 if (!isDoxygenComment(SourceMgr, *LastComment))
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-07-02 17:08:52 +0000448 // Compute the starting line for the declaration and for the end of the
449 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000450 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000453 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-07-02 17:08:52 +0000456 // If the comment does not end on the line prior to the declaration, then
457 // the comment is not associated with the declaration at all.
458 if (CommentEndLine + 1 != DeclStartLine)
459 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Douglas Gregor2e222532009-07-02 17:08:52 +0000461 // We have a comment, but there may be more comments on the previous lines.
462 // Keep looking so long as the comments are still Doxygen comments and are
463 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000464 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000465 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
466 std::vector<SourceRange>::iterator FirstComment = LastComment;
467 while (FirstComment != Comments.begin()) {
468 // Look at the previous comment
469 --FirstComment;
470 std::pair<FileID, unsigned> Decomp
471 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor2e222532009-07-02 17:08:52 +0000473 // If this previous comment is in a different file, we're done.
474 if (Decomp.first != DeclStartDecomp.first) {
475 ++FirstComment;
476 break;
477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregor2e222532009-07-02 17:08:52 +0000479 // If this comment is not a Doxygen comment, we're done.
480 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
481 ++FirstComment;
482 break;
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor2e222532009-07-02 17:08:52 +0000485 // If the line number is not what we expected, we're done.
486 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
487 if (Line != ExpectedLine) {
488 ++FirstComment;
489 break;
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000493 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Douglas Gregor2e222532009-07-02 17:08:52 +0000497 // The iterator range [FirstComment, LastComment] contains all of the
498 // BCPL comments that, together, are associated with this declaration.
499 // Form a single comment block string for this declaration that concatenates
500 // all of these comments.
501 std::string &Result = DeclComments[D];
502 while (FirstComment != LastComment) {
503 std::pair<FileID, unsigned> DecompStart
504 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
505 std::pair<FileID, unsigned> DecompEnd
506 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
507 Result.append(FileBufferStart + DecompStart.second,
508 FileBufferStart + DecompEnd.second + 1);
509 ++FirstComment;
510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor2e222532009-07-02 17:08:52 +0000512 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 Result.append(FileBufferStart +
514 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 FileBufferStart + LastCommentEndDecomp.second + 1);
516 return Result.c_str();
517}
518
Chris Lattner464175b2007-07-18 17:52:12 +0000519//===----------------------------------------------------------------------===//
520// Type Sizing and Analysis
521//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000522
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000523/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
524/// scalar floating point type.
525const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000526 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527 assert(BT && "Not a floating point type!");
528 switch (BT->getKind()) {
529 default: assert(0 && "Not a floating point type!");
530 case BuiltinType::Float: return Target.getFloatFormat();
531 case BuiltinType::Double: return Target.getDoubleFormat();
532 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
533 }
534}
535
Ken Dyck8b752f12010-01-27 17:10:57 +0000536/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537/// specified decl. Note that bitfields do not have a valid alignment, so
538/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000539/// If @p RefAsPointee, references are treated like their underlying type
540/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000541CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000542 unsigned Align = Target.getCharWidth();
543
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000544 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000545 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546
Chris Lattneraf707ab2009-01-24 21:53:27 +0000547 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000549 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000550 if (RefAsPointee)
551 T = RT->getPointeeType();
552 else
553 T = getPointerType(RT->getPointeeType());
554 }
555 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000557 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558 T = cast<ArrayType>(T)->getElementType();
559
560 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000562 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000563
Ken Dyck8b752f12010-01-27 17:10:57 +0000564 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000565}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000566
Chris Lattnera7674d82007-07-13 22:13:22 +0000567/// getTypeSize - Return the size of the specified type, in bits. This method
568/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000569///
570/// FIXME: Pointers into different addr spaces could have different sizes and
571/// alignment requirements: getPointerInfo should take an AddrSpace, this
572/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000573std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000574ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000575 uint64_t Width=0;
576 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000577 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000578#define TYPE(Class, Base)
579#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000580#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000583 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000584 break;
585
Chris Lattner692233e2007-07-13 22:27:08 +0000586 case Type::FunctionNoProto:
587 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000588 // GCC extension: alignof(function) = 32 bits
589 Width = 0;
590 Align = 32;
591 break;
592
Douglas Gregor72564e72009-02-26 23:50:07 +0000593 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000594 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000595 Width = 0;
596 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597 break;
598
Steve Narofffb22d962007-08-30 01:06:46 +0000599 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000600 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner98be4942008-03-05 18:54:05 +0000602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000603 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000604 Align = EltInfo.second;
605 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000606 }
Nate Begeman213541a2008-04-18 23:10:10 +0000607 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000608 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000609 const VectorType *VT = cast<VectorType>(T);
610 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
611 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000612 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000613 // If the alignment is not a power of 2, round up to the next power of 2.
614 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000615 if (VT->getNumElements() & (VT->getNumElements()-1)) {
616 Align = llvm::NextPowerOf2(Align);
617 Width = llvm::RoundUpToAlignment(Width, Align);
618 }
Chris Lattner030d8842007-07-19 22:06:24 +0000619 break;
620 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000621
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000623 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000624 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000625 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000626 // GCC extension: alignof(void) = 8 bits.
627 Width = 0;
628 Align = 8;
629 break;
630
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getBoolWidth();
633 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::Char_S:
636 case BuiltinType::Char_U:
637 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getCharWidth();
640 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000642 case BuiltinType::WChar:
643 Width = Target.getWCharWidth();
644 Align = Target.getWCharAlign();
645 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000646 case BuiltinType::Char16:
647 Width = Target.getChar16Width();
648 Align = Target.getChar16Align();
649 break;
650 case BuiltinType::Char32:
651 Width = Target.getChar32Width();
652 Align = Target.getChar32Align();
653 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000654 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getShortWidth();
657 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000659 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000660 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000661 Width = Target.getIntWidth();
662 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000664 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000666 Width = Target.getLongWidth();
667 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000669 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000671 Width = Target.getLongLongWidth();
672 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000674 case BuiltinType::Int128:
675 case BuiltinType::UInt128:
676 Width = 128;
677 Align = 128; // int128_t is 128-bit aligned on all targets.
678 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000680 Width = Target.getFloatWidth();
681 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 break;
683 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000684 Width = Target.getDoubleWidth();
685 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 Width = Target.getLongDoubleWidth();
689 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000691 case BuiltinType::NullPtr:
692 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
693 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000694 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000695 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000696 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000697 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000698 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000699 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000700 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000701 case Type::BlockPointer: {
702 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
703 Width = Target.getPointerWidth(AS);
704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000707 case Type::LValueReference:
708 case Type::RValueReference: {
709 // alignof and sizeof should never enter this code path here, so we go
710 // the pointer route.
711 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
712 Width = Target.getPointerWidth(AS);
713 Align = Target.getPointerAlign(AS);
714 break;
715 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000716 case Type::Pointer: {
717 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000718 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000719 Align = Target.getPointerAlign(AS);
720 break;
721 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000722 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000723 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000724 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000725 getTypeInfo(getPointerDiffType());
726 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000727 if (Pointee->isFunctionType())
728 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000729 Align = PtrDiffInfo.second;
730 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000731 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000732 case Type::Complex: {
733 // Complex types have the same alignment as their elements, but twice the
734 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000735 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000736 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000737 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000738 Align = EltInfo.second;
739 break;
740 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000741 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000742 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000743 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
744 Width = Layout.getSize();
745 Align = Layout.getAlignment();
746 break;
747 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000748 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000749 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000750 const TagType *TT = cast<TagType>(T);
751
752 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000753 Width = 1;
754 Align = 1;
755 break;
756 }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Daniel Dunbar1d751182008-11-08 05:48:37 +0000758 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000759 return getTypeInfo(ET->getDecl()->getIntegerType());
760
Daniel Dunbar1d751182008-11-08 05:48:37 +0000761 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000762 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
763 Width = Layout.getSize();
764 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000765 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000766 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000767
Chris Lattner9fcfe922009-10-22 05:17:15 +0000768 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000769 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
770 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000771
Chris Lattner9fcfe922009-10-22 05:17:15 +0000772 case Type::Elaborated:
773 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
774 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000775
Douglas Gregor18857642009-04-30 17:32:17 +0000776 case Type::Typedef: {
777 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000778 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000779 Align = std::max(Aligned->getMaxAlignment(),
780 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000781 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
782 } else
783 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000784 break;
Chris Lattner71763312008-04-06 22:05:18 +0000785 }
Douglas Gregor18857642009-04-30 17:32:17 +0000786
787 case Type::TypeOfExpr:
788 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
789 .getTypePtr());
790
791 case Type::TypeOf:
792 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
793
Anders Carlsson395b4752009-06-24 19:06:50 +0000794 case Type::Decltype:
795 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
796 .getTypePtr());
797
Douglas Gregor18857642009-04-30 17:32:17 +0000798 case Type::QualifiedName:
799 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Douglas Gregor18857642009-04-30 17:32:17 +0000801 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000802 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000803 "Cannot request the size of a dependent type");
804 // FIXME: this is likely to be wrong once we support template
805 // aliases, since a template alias could refer to a typedef that
806 // has an __aligned__ attribute on it.
807 return getTypeInfo(getCanonicalType(T));
808 }
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Chris Lattner464175b2007-07-18 17:52:12 +0000810 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000811 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000812}
813
Ken Dyckbdc601b2009-12-22 14:23:30 +0000814/// getTypeSizeInChars - Return the size of the specified type, in characters.
815/// This method does not work on incomplete types.
816CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000817 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000818}
819CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000820 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000821}
822
Ken Dyck16e20cc2010-01-26 17:25:18 +0000823/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000824/// characters. This method does not work on incomplete types.
825CharUnits ASTContext::getTypeAlignInChars(QualType T) {
826 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
827}
828CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
829 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
830}
831
Chris Lattner34ebde42009-01-27 18:08:34 +0000832/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
833/// type for the current target in bits. This can be different than the ABI
834/// alignment in cases where it is beneficial for performance to overalign
835/// a data type.
836unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
837 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000838
839 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000840 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000841 T = CT->getElementType().getTypePtr();
842 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
843 T->isSpecificBuiltinType(BuiltinType::LongLong))
844 return std::max(ABIAlign, (unsigned)getTypeSize(T));
845
Chris Lattner34ebde42009-01-27 18:08:34 +0000846 return ABIAlign;
847}
848
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000849static void CollectLocalObjCIvars(ASTContext *Ctx,
850 const ObjCInterfaceDecl *OI,
851 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000852 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
853 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000854 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000855 if (!IVDecl->isInvalidDecl())
856 Fields.push_back(cast<FieldDecl>(IVDecl));
857 }
858}
859
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000860void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
861 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
862 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
863 CollectObjCIvars(SuperClass, Fields);
864 CollectLocalObjCIvars(this, OI, Fields);
865}
866
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000867/// ShallowCollectObjCIvars -
868/// Collect all ivars, including those synthesized, in the current class.
869///
870void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
871 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
872 bool CollectSynthesized) {
873 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
874 E = OI->ivar_end(); I != E; ++I) {
875 Ivars.push_back(*I);
876 }
877 if (CollectSynthesized)
878 CollectSynthesizedIvars(OI, Ivars);
879}
880
Fariborz Jahanian98200742009-05-12 18:14:29 +0000881void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
882 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000883 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
884 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000885 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
886 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Fariborz Jahanian98200742009-05-12 18:14:29 +0000888 // Also look into nested protocols.
889 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
890 E = PD->protocol_end(); P != E; ++P)
891 CollectProtocolSynthesizedIvars(*P, Ivars);
892}
893
894/// CollectSynthesizedIvars -
895/// This routine collect synthesized ivars for the designated class.
896///
897void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
898 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000899 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
900 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000901 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
902 Ivars.push_back(Ivar);
903 }
904 // Also look into interface's protocol list for properties declared
905 // in the protocol and whose ivars are synthesized.
906 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
907 PE = OI->protocol_end(); P != PE; ++P) {
908 ObjCProtocolDecl *PD = (*P);
909 CollectProtocolSynthesizedIvars(PD, Ivars);
910 }
911}
912
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000913/// CollectInheritedProtocols - Collect all protocols in current class and
914/// those inherited by it.
915void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
916 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
917 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
918 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
919 PE = OI->protocol_end(); P != PE; ++P) {
920 ObjCProtocolDecl *Proto = (*P);
921 Protocols.push_back(Proto);
922 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
923 PE = Proto->protocol_end(); P != PE; ++P)
924 CollectInheritedProtocols(*P, Protocols);
925 }
926
927 // Categories of this Interface.
928 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
929 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
930 CollectInheritedProtocols(CDeclChain, Protocols);
931 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
932 while (SD) {
933 CollectInheritedProtocols(SD, Protocols);
934 SD = SD->getSuperClass();
935 }
936 return;
937 }
938 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
939 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
940 PE = OC->protocol_end(); P != PE; ++P) {
941 ObjCProtocolDecl *Proto = (*P);
942 Protocols.push_back(Proto);
943 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
944 PE = Proto->protocol_end(); P != PE; ++P)
945 CollectInheritedProtocols(*P, Protocols);
946 }
947 return;
948 }
949 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
950 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
951 PE = OP->protocol_end(); P != PE; ++P) {
952 ObjCProtocolDecl *Proto = (*P);
953 Protocols.push_back(Proto);
954 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
955 PE = Proto->protocol_end(); P != PE; ++P)
956 CollectInheritedProtocols(*P, Protocols);
957 }
958 return;
959 }
960}
961
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000962unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
963 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000964 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
965 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000966 if ((*I)->getPropertyIvarDecl())
967 ++count;
968
969 // Also look into nested protocols.
970 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
971 E = PD->protocol_end(); P != E; ++P)
972 count += CountProtocolSynthesizedIvars(*P);
973 return count;
974}
975
Mike Stump1eb44332009-09-09 15:08:12 +0000976unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000977 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000978 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
979 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000980 if ((*I)->getPropertyIvarDecl())
981 ++count;
982 }
983 // Also look into interface's protocol list for properties declared
984 // in the protocol and whose ivars are synthesized.
985 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
986 PE = OI->protocol_end(); P != PE; ++P) {
987 ObjCProtocolDecl *PD = (*P);
988 count += CountProtocolSynthesizedIvars(PD);
989 }
990 return count;
991}
992
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000993/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
994ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
995 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
996 I = ObjCImpls.find(D);
997 if (I != ObjCImpls.end())
998 return cast<ObjCImplementationDecl>(I->second);
999 return 0;
1000}
1001/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1002ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1003 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1004 I = ObjCImpls.find(D);
1005 if (I != ObjCImpls.end())
1006 return cast<ObjCCategoryImplDecl>(I->second);
1007 return 0;
1008}
1009
1010/// \brief Set the implementation of ObjCInterfaceDecl.
1011void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1012 ObjCImplementationDecl *ImplD) {
1013 assert(IFaceD && ImplD && "Passed null params");
1014 ObjCImpls[IFaceD] = ImplD;
1015}
1016/// \brief Set the implementation of ObjCCategoryDecl.
1017void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1018 ObjCCategoryImplDecl *ImplD) {
1019 assert(CatD && ImplD && "Passed null params");
1020 ObjCImpls[CatD] = ImplD;
1021}
1022
John McCalla93c9342009-12-07 02:54:59 +00001023/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001024///
John McCalla93c9342009-12-07 02:54:59 +00001025/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001026/// the TypeLoc wrappers.
1027///
1028/// \param T the type that will be the basis for type source info. This type
1029/// should refer to how the declarator was written in source code, not to
1030/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001031TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001032 unsigned DataSize) {
1033 if (!DataSize)
1034 DataSize = TypeLoc::getFullDataSizeForType(T);
1035 else
1036 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001037 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001038
John McCalla93c9342009-12-07 02:54:59 +00001039 TypeSourceInfo *TInfo =
1040 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1041 new (TInfo) TypeSourceInfo(T);
1042 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001043}
1044
John McCalla93c9342009-12-07 02:54:59 +00001045TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001046 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001047 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001048 DI->getTypeLoc().initialize(L);
1049 return DI;
1050}
1051
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001052/// getInterfaceLayoutImpl - Get or compute information about the
1053/// layout of the given interface.
1054///
1055/// \param Impl - If given, also include the layout of the interface's
1056/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001057const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001058ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1059 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001060 assert(!D->isForwardDecl() && "Invalid interface decl!");
1061
Devang Patel44a3dde2008-06-04 21:54:36 +00001062 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001063 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001064 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1065 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1066 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001067
Daniel Dunbar453addb2009-05-03 11:16:44 +00001068 // Add in synthesized ivar count if laying out an implementation.
1069 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001070 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001071 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001072 // entry. Note we can't cache this because we simply free all
1073 // entries later; however we shouldn't look up implementations
1074 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001075 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001076 return getObjCLayout(D, 0);
1077 }
1078
Mike Stump1eb44332009-09-09 15:08:12 +00001079 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001080 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1081 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Devang Patel44a3dde2008-06-04 21:54:36 +00001083 return *NewEntry;
1084}
1085
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001086const ASTRecordLayout &
1087ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1088 return getObjCLayout(D, 0);
1089}
1090
1091const ASTRecordLayout &
1092ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1093 return getObjCLayout(D->getClassInterface(), D);
1094}
1095
Devang Patel88a981b2007-11-01 19:11:01 +00001096/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001097/// specified record (struct/union/class), which indicates its size and field
1098/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001099const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001100 D = D->getDefinition(*this);
1101 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001102
Chris Lattner464175b2007-07-18 17:52:12 +00001103 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001104 // Note that we can't save a reference to the entry because this function
1105 // is recursive.
1106 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001107 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001108
Mike Stump1eb44332009-09-09 15:08:12 +00001109 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001110 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001111 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Chris Lattner5d2a6302007-07-18 18:26:58 +00001113 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001114}
1115
Anders Carlssonf53df232009-12-07 04:35:11 +00001116const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1117 RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1118 assert(RD && "Cannot get key function for forward declarations!");
1119
1120 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1121 if (!Entry)
1122 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1123 else
1124 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1125 "Key function changed!");
1126
1127 return Entry;
1128}
1129
Chris Lattnera7674d82007-07-13 22:13:22 +00001130//===----------------------------------------------------------------------===//
1131// Type creation/memoization methods
1132//===----------------------------------------------------------------------===//
1133
John McCall0953e762009-09-24 19:53:00 +00001134QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1135 unsigned Fast = Quals.getFastQualifiers();
1136 Quals.removeFastQualifiers();
1137
1138 // Check if we've already instantiated this type.
1139 llvm::FoldingSetNodeID ID;
1140 ExtQuals::Profile(ID, TypeNode, Quals);
1141 void *InsertPos = 0;
1142 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1143 assert(EQ->getQualifiers() == Quals);
1144 QualType T = QualType(EQ, Fast);
1145 return T;
1146 }
1147
John McCall6b304a02009-09-24 23:30:46 +00001148 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001149 ExtQualNodes.InsertNode(New, InsertPos);
1150 QualType T = QualType(New, Fast);
1151 return T;
1152}
1153
1154QualType ASTContext::getVolatileType(QualType T) {
1155 QualType CanT = getCanonicalType(T);
1156 if (CanT.isVolatileQualified()) return T;
1157
1158 QualifierCollector Quals;
1159 const Type *TypeNode = Quals.strip(T);
1160 Quals.addVolatile();
1161
1162 return getExtQualType(TypeNode, Quals);
1163}
1164
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001165QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001166 QualType CanT = getCanonicalType(T);
1167 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001168 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001169
John McCall0953e762009-09-24 19:53:00 +00001170 // If we are composing extended qualifiers together, merge together
1171 // into one ExtQuals node.
1172 QualifierCollector Quals;
1173 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
John McCall0953e762009-09-24 19:53:00 +00001175 // If this type already has an address space specified, it cannot get
1176 // another one.
1177 assert(!Quals.hasAddressSpace() &&
1178 "Type cannot be in multiple addr spaces!");
1179 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001180
John McCall0953e762009-09-24 19:53:00 +00001181 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001182}
1183
Chris Lattnerb7d25532009-02-18 22:53:11 +00001184QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001185 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001186 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001187 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001188 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001190 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001191 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001192 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001193 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1194 return getPointerType(ResultType);
1195 }
1196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
John McCall0953e762009-09-24 19:53:00 +00001198 // If we are composing extended qualifiers together, merge together
1199 // into one ExtQuals node.
1200 QualifierCollector Quals;
1201 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
John McCall0953e762009-09-24 19:53:00 +00001203 // If this type already has an ObjCGC specified, it cannot get
1204 // another one.
1205 assert(!Quals.hasObjCGCAttr() &&
1206 "Type cannot have multiple ObjCGCs!");
1207 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001208
John McCall0953e762009-09-24 19:53:00 +00001209 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001210}
Chris Lattnera7674d82007-07-13 22:13:22 +00001211
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001212static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1213 bool AddNoReturn,
1214 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001215 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001216 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1217 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001218 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1219 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001220 if (ResultType == Pointee)
1221 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001222
1223 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001224 } else if (const BlockPointerType *BlockPointer
1225 = T->getAs<BlockPointerType>()) {
1226 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001227 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1228 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001229 if (ResultType == Pointee)
1230 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001231
1232 ResultType = Context.getBlockPointerType(ResultType);
1233 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1234 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001235 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001236
Douglas Gregor43c79c22009-12-09 00:47:37 +00001237 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001238 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1239 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001240 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001241 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001242 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001243 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1244 FPT->getNumArgs(), FPT->isVariadic(),
1245 FPT->getTypeQuals(),
1246 FPT->hasExceptionSpec(),
1247 FPT->hasAnyExceptionSpec(),
1248 FPT->getNumExceptions(),
1249 FPT->exception_begin(),
1250 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001251 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001252 } else
1253 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001254
1255 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1256}
1257
1258QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1259 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1260}
1261
1262QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1263 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001264}
1265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266/// getComplexType - Return the uniqued reference to the type for a complex
1267/// number with the specified element type.
1268QualType ASTContext::getComplexType(QualType T) {
1269 // Unique pointers, to guarantee there is only one pointer of a particular
1270 // structure.
1271 llvm::FoldingSetNodeID ID;
1272 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 void *InsertPos = 0;
1275 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1276 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 // If the pointee type isn't canonical, this won't be a canonical type either,
1279 // so fill in the canonical type field.
1280 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001281 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001282 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // Get the new insert position for the node we care about.
1285 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001286 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 }
John McCall6b304a02009-09-24 23:30:46 +00001288 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 Types.push_back(New);
1290 ComplexTypes.InsertNode(New, InsertPos);
1291 return QualType(New, 0);
1292}
1293
Reid Spencer5f016e22007-07-11 17:01:13 +00001294/// getPointerType - Return the uniqued reference to the type for a pointer to
1295/// the specified type.
1296QualType ASTContext::getPointerType(QualType T) {
1297 // Unique pointers, to guarantee there is only one pointer of a particular
1298 // structure.
1299 llvm::FoldingSetNodeID ID;
1300 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 void *InsertPos = 0;
1303 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1304 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // If the pointee type isn't canonical, this won't be a canonical type either,
1307 // so fill in the canonical type field.
1308 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001309 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001310 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 // Get the new insert position for the node we care about.
1313 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001314 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 }
John McCall6b304a02009-09-24 23:30:46 +00001316 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 Types.push_back(New);
1318 PointerTypes.InsertNode(New, InsertPos);
1319 return QualType(New, 0);
1320}
1321
Mike Stump1eb44332009-09-09 15:08:12 +00001322/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001323/// a pointer to the specified block.
1324QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001325 assert(T->isFunctionType() && "block of function types only");
1326 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001327 // structure.
1328 llvm::FoldingSetNodeID ID;
1329 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Steve Naroff5618bd42008-08-27 16:04:49 +00001331 void *InsertPos = 0;
1332 if (BlockPointerType *PT =
1333 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1334 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001335
1336 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001337 // type either so fill in the canonical type field.
1338 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001339 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001340 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Steve Naroff5618bd42008-08-27 16:04:49 +00001342 // Get the new insert position for the node we care about.
1343 BlockPointerType *NewIP =
1344 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001345 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001346 }
John McCall6b304a02009-09-24 23:30:46 +00001347 BlockPointerType *New
1348 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001349 Types.push_back(New);
1350 BlockPointerTypes.InsertNode(New, InsertPos);
1351 return QualType(New, 0);
1352}
1353
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001354/// getLValueReferenceType - Return the uniqued reference to the type for an
1355/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001356QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 // Unique pointers, to guarantee there is only one pointer of a particular
1358 // structure.
1359 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001360 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361
1362 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001363 if (LValueReferenceType *RT =
1364 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001366
John McCall54e14c42009-10-22 22:37:11 +00001367 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // If the referencee type isn't canonical, this won't be a canonical type
1370 // either, so fill in the canonical type field.
1371 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001372 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1373 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1374 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001375
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001377 LValueReferenceType *NewIP =
1378 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001379 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 }
1381
John McCall6b304a02009-09-24 23:30:46 +00001382 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001383 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1384 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001386 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001387
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001388 return QualType(New, 0);
1389}
1390
1391/// getRValueReferenceType - Return the uniqued reference to the type for an
1392/// rvalue reference to the specified type.
1393QualType ASTContext::getRValueReferenceType(QualType T) {
1394 // Unique pointers, to guarantee there is only one pointer of a particular
1395 // structure.
1396 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001397 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001398
1399 void *InsertPos = 0;
1400 if (RValueReferenceType *RT =
1401 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1402 return QualType(RT, 0);
1403
John McCall54e14c42009-10-22 22:37:11 +00001404 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1405
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001406 // If the referencee type isn't canonical, this won't be a canonical type
1407 // either, so fill in the canonical type field.
1408 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001409 if (InnerRef || !T.isCanonical()) {
1410 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1411 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001412
1413 // Get the new insert position for the node we care about.
1414 RValueReferenceType *NewIP =
1415 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1416 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1417 }
1418
John McCall6b304a02009-09-24 23:30:46 +00001419 RValueReferenceType *New
1420 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001421 Types.push_back(New);
1422 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 return QualType(New, 0);
1424}
1425
Sebastian Redlf30208a2009-01-24 21:16:55 +00001426/// getMemberPointerType - Return the uniqued reference to the type for a
1427/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001428QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001429 // Unique pointers, to guarantee there is only one pointer of a particular
1430 // structure.
1431 llvm::FoldingSetNodeID ID;
1432 MemberPointerType::Profile(ID, T, Cls);
1433
1434 void *InsertPos = 0;
1435 if (MemberPointerType *PT =
1436 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1437 return QualType(PT, 0);
1438
1439 // If the pointee or class type isn't canonical, this won't be a canonical
1440 // type either, so fill in the canonical type field.
1441 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001442 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001443 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1444
1445 // Get the new insert position for the node we care about.
1446 MemberPointerType *NewIP =
1447 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1448 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1449 }
John McCall6b304a02009-09-24 23:30:46 +00001450 MemberPointerType *New
1451 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001452 Types.push_back(New);
1453 MemberPointerTypes.InsertNode(New, InsertPos);
1454 return QualType(New, 0);
1455}
1456
Mike Stump1eb44332009-09-09 15:08:12 +00001457/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001458/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001459QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001460 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001461 ArrayType::ArraySizeModifier ASM,
1462 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001463 assert((EltTy->isDependentType() ||
1464 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001465 "Constant array of VLAs is illegal!");
1466
Chris Lattner38aeec72009-05-13 04:12:56 +00001467 // Convert the array size into a canonical width matching the pointer size for
1468 // the target.
1469 llvm::APInt ArySize(ArySizeIn);
1470 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001473 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001476 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001477 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // If the element type isn't canonical, this won't be a canonical type either,
1481 // so fill in the canonical type field.
1482 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001483 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001484 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001485 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001487 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001488 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCall6b304a02009-09-24 23:30:46 +00001492 ConstantArrayType *New = new(*this,TypeAlignment)
1493 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001494 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 Types.push_back(New);
1496 return QualType(New, 0);
1497}
1498
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001499/// getVariableArrayType - Returns a non-unique reference to the type for a
1500/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001501QualType ASTContext::getVariableArrayType(QualType EltTy,
1502 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001503 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001504 unsigned EltTypeQuals,
1505 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001506 // Since we don't unique expressions, it isn't possible to unique VLA's
1507 // that have an expression provided for their size.
1508
John McCall6b304a02009-09-24 23:30:46 +00001509 VariableArrayType *New = new(*this, TypeAlignment)
1510 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001511
1512 VariableArrayTypes.push_back(New);
1513 Types.push_back(New);
1514 return QualType(New, 0);
1515}
1516
Douglas Gregor898574e2008-12-05 23:32:09 +00001517/// getDependentSizedArrayType - Returns a non-unique reference to
1518/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001519/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001520QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1521 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001522 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001523 unsigned EltTypeQuals,
1524 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001525 assert((!NumElts || NumElts->isTypeDependent() ||
1526 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001527 "Size must be type- or value-dependent!");
1528
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001529 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001530 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001531 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001532
1533 if (NumElts) {
1534 // Dependently-sized array types that do not have a specified
1535 // number of elements will have their sizes deduced from an
1536 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001537 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1538 EltTypeQuals, NumElts);
1539
1540 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1541 }
1542
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001543 DependentSizedArrayType *New;
1544 if (Canon) {
1545 // We already have a canonical version of this array type; use it as
1546 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001547 New = new (*this, TypeAlignment)
1548 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1549 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001550 } else {
1551 QualType CanonEltTy = getCanonicalType(EltTy);
1552 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001553 New = new (*this, TypeAlignment)
1554 DependentSizedArrayType(*this, EltTy, QualType(),
1555 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001556
Douglas Gregor789b1f62010-02-04 18:10:26 +00001557 if (NumElts) {
1558 DependentSizedArrayType *CanonCheck
1559 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1560 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1561 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001562 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001563 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001564 } else {
1565 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1566 ASM, EltTypeQuals,
1567 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001568 New = new (*this, TypeAlignment)
1569 DependentSizedArrayType(*this, EltTy, Canon,
1570 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001571 }
1572 }
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Douglas Gregor898574e2008-12-05 23:32:09 +00001574 Types.push_back(New);
1575 return QualType(New, 0);
1576}
1577
Eli Friedmanc5773c42008-02-15 18:16:39 +00001578QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1579 ArrayType::ArraySizeModifier ASM,
1580 unsigned EltTypeQuals) {
1581 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001582 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001583
1584 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001585 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001586 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1587 return QualType(ATP, 0);
1588
1589 // If the element type isn't canonical, this won't be a canonical type
1590 // either, so fill in the canonical type field.
1591 QualType Canonical;
1592
John McCall467b27b2009-10-22 20:10:53 +00001593 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001594 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001595 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001596
1597 // Get the new insert position for the node we care about.
1598 IncompleteArrayType *NewIP =
1599 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001601 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001602
John McCall6b304a02009-09-24 23:30:46 +00001603 IncompleteArrayType *New = new (*this, TypeAlignment)
1604 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001605
1606 IncompleteArrayTypes.InsertNode(New, InsertPos);
1607 Types.push_back(New);
1608 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001609}
1610
Steve Naroff73322922007-07-18 18:00:27 +00001611/// getVectorType - Return the unique reference to a vector type of
1612/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001613QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1614 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattnerf52ab252008-04-06 22:59:24 +00001617 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001618 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 // Check if we've already instantiated a vector of this type.
1621 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001622 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1623 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 void *InsertPos = 0;
1625 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1626 return QualType(VTP, 0);
1627
1628 // If the element type isn't canonical, this won't be a canonical type either,
1629 // so fill in the canonical type field.
1630 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001631 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1632 Canonical = getVectorType(getCanonicalType(vecType),
1633 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 // Get the new insert position for the node we care about.
1636 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001637 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 }
John McCall6b304a02009-09-24 23:30:46 +00001639 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001640 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 VectorTypes.InsertNode(New, InsertPos);
1642 Types.push_back(New);
1643 return QualType(New, 0);
1644}
1645
Nate Begeman213541a2008-04-18 23:10:10 +00001646/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001647/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001648QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001649 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Chris Lattnerf52ab252008-04-06 22:59:24 +00001651 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001652 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Steve Naroff73322922007-07-18 18:00:27 +00001654 // Check if we've already instantiated a vector of this type.
1655 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001656 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001657 void *InsertPos = 0;
1658 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1659 return QualType(VTP, 0);
1660
1661 // If the element type isn't canonical, this won't be a canonical type either,
1662 // so fill in the canonical type field.
1663 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001664 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001665 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Steve Naroff73322922007-07-18 18:00:27 +00001667 // Get the new insert position for the node we care about.
1668 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001669 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001670 }
John McCall6b304a02009-09-24 23:30:46 +00001671 ExtVectorType *New = new (*this, TypeAlignment)
1672 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001673 VectorTypes.InsertNode(New, InsertPos);
1674 Types.push_back(New);
1675 return QualType(New, 0);
1676}
1677
Mike Stump1eb44332009-09-09 15:08:12 +00001678QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001679 Expr *SizeExpr,
1680 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001681 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001682 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001683 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001685 void *InsertPos = 0;
1686 DependentSizedExtVectorType *Canon
1687 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1688 DependentSizedExtVectorType *New;
1689 if (Canon) {
1690 // We already have a canonical version of this array type; use it as
1691 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001692 New = new (*this, TypeAlignment)
1693 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1694 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001695 } else {
1696 QualType CanonVecTy = getCanonicalType(vecType);
1697 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001698 New = new (*this, TypeAlignment)
1699 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1700 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001701
1702 DependentSizedExtVectorType *CanonCheck
1703 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1704 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1705 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001706 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1707 } else {
1708 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1709 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001710 New = new (*this, TypeAlignment)
1711 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001712 }
1713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001715 Types.push_back(New);
1716 return QualType(New, 0);
1717}
1718
Douglas Gregor72564e72009-02-26 23:50:07 +00001719/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001720///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001721QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1722 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 // Unique functions, to guarantee there is only one function of a particular
1724 // structure.
1725 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001726 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001729 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001730 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001734 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001735 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001736 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001737 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001740 FunctionNoProtoType *NewIP =
1741 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001742 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 }
Mike Stump1eb44332009-09-09 15:08:12 +00001744
John McCall6b304a02009-09-24 23:30:46 +00001745 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001746 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001748 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 return QualType(New, 0);
1750}
1751
1752/// getFunctionType - Return a normal function type with a typed argument
1753/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001754QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001755 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001756 unsigned TypeQuals, bool hasExceptionSpec,
1757 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001758 const QualType *ExArray, bool NoReturn,
1759 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 // Unique functions, to guarantee there is only one function of a particular
1761 // structure.
1762 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001763 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001764 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001765 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001766
1767 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001768 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001769 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001771
1772 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001773 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001775 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 isCanonical = false;
1777
1778 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001779 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001781 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 llvm::SmallVector<QualType, 16> CanonicalArgs;
1783 CanonicalArgs.reserve(NumArgs);
1784 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001785 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001786
Chris Lattnerf52ab252008-04-06 22:59:24 +00001787 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001788 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001789 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001790 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001791 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001792
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001794 FunctionProtoType *NewIP =
1795 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001796 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001798
Douglas Gregor72564e72009-02-26 23:50:07 +00001799 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001800 // for two variable size arrays (for parameter and exception types) at the
1801 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001802 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001803 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1804 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001805 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001806 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001807 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001808 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001810 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 return QualType(FTP, 0);
1812}
1813
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001814/// getTypeDeclType - Return the unique reference to the type for the
1815/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001816QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001817 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001818 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001820 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001821 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001822 else if (isa<TemplateTypeParmDecl>(Decl)) {
1823 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001824 } else if (ObjCInterfaceDecl *ObjCInterface
1825 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001826 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001827
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001828 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001829 if (PrevDecl)
1830 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001831 else
John McCall6b304a02009-09-24 23:30:46 +00001832 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001833 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001834 if (PrevDecl)
1835 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001836 else
John McCall6b304a02009-09-24 23:30:46 +00001837 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001838 } else if (UnresolvedUsingTypenameDecl *Using =
1839 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1840 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001841 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001842 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001843
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001844 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001845 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001846}
1847
Reid Spencer5f016e22007-07-11 17:01:13 +00001848/// getTypedefType - Return the unique reference to the type for the
1849/// specified typename decl.
1850QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1851 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Chris Lattnerf52ab252008-04-06 22:59:24 +00001853 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001854 Decl->TypeForDecl = new(*this, TypeAlignment)
1855 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 Types.push_back(Decl->TypeForDecl);
1857 return QualType(Decl->TypeForDecl, 0);
1858}
1859
John McCall49a832b2009-10-18 09:09:24 +00001860/// \brief Retrieve a substitution-result type.
1861QualType
1862ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1863 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001864 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001865 && "replacement types must always be canonical");
1866
1867 llvm::FoldingSetNodeID ID;
1868 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1869 void *InsertPos = 0;
1870 SubstTemplateTypeParmType *SubstParm
1871 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1872
1873 if (!SubstParm) {
1874 SubstParm = new (*this, TypeAlignment)
1875 SubstTemplateTypeParmType(Parm, Replacement);
1876 Types.push_back(SubstParm);
1877 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1878 }
1879
1880 return QualType(SubstParm, 0);
1881}
1882
Douglas Gregorfab9d672009-02-05 23:33:38 +00001883/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001884/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001885/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001886QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001887 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001888 IdentifierInfo *Name) {
1889 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001890 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001891 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001892 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001893 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1894
1895 if (TypeParm)
1896 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001898 if (Name) {
1899 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001900 TypeParm = new (*this, TypeAlignment)
1901 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001902
1903 TemplateTypeParmType *TypeCheck
1904 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1905 assert(!TypeCheck && "Template type parameter canonical type broken");
1906 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001907 } else
John McCall6b304a02009-09-24 23:30:46 +00001908 TypeParm = new (*this, TypeAlignment)
1909 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001910
1911 Types.push_back(TypeParm);
1912 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1913
1914 return QualType(TypeParm, 0);
1915}
1916
Mike Stump1eb44332009-09-09 15:08:12 +00001917QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001918ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001919 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001920 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001921 unsigned NumArgs = Args.size();
1922
John McCall833ca992009-10-29 08:12:44 +00001923 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1924 ArgVec.reserve(NumArgs);
1925 for (unsigned i = 0; i != NumArgs; ++i)
1926 ArgVec.push_back(Args[i].getArgument());
1927
1928 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1929}
1930
1931QualType
1932ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001933 const TemplateArgument *Args,
1934 unsigned NumArgs,
1935 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001936 if (!Canon.isNull())
1937 Canon = getCanonicalType(Canon);
1938 else {
1939 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001940 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1941 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1942 CanonArgs.reserve(NumArgs);
1943 for (unsigned I = 0; I != NumArgs; ++I)
1944 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1945
1946 // Determine whether this canonical template specialization type already
1947 // exists.
1948 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001949 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001950 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001951
1952 void *InsertPos = 0;
1953 TemplateSpecializationType *Spec
1954 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Douglas Gregor1275ae02009-07-28 23:00:59 +00001956 if (!Spec) {
1957 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001958 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001959 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001960 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001961 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001962 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001963 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001964 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001965 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Douglas Gregorb88e8882009-07-30 17:40:51 +00001968 if (Canon.isNull())
1969 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001970 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001971 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001972 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001973
Douglas Gregor1275ae02009-07-28 23:00:59 +00001974 // Allocate the (non-canonical) template specialization type, but don't
1975 // try to unique it: these types typically have location information that
1976 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001977 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001978 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001979 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001980 TemplateSpecializationType *Spec
1981 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001982 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Douglas Gregor55f6b142009-02-09 18:46:07 +00001984 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001985 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001986}
1987
Mike Stump1eb44332009-09-09 15:08:12 +00001988QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001989ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001990 QualType NamedType) {
1991 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001992 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001993
1994 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001995 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001996 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 if (T)
1998 return QualType(T, 0);
1999
Douglas Gregor789b1f62010-02-04 18:10:26 +00002000 QualType Canon = NamedType;
2001 if (!Canon.isCanonical()) {
2002 Canon = getCanonicalType(NamedType);
2003 QualifiedNameType *CheckT
2004 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2005 assert(!CheckT && "Qualified name canonical type broken");
2006 (void)CheckT;
2007 }
2008
2009 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002010 Types.push_back(T);
2011 QualifiedNameTypes.InsertNode(T, InsertPos);
2012 return QualType(T, 0);
2013}
2014
Mike Stump1eb44332009-09-09 15:08:12 +00002015QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002016 const IdentifierInfo *Name,
2017 QualType Canon) {
2018 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2019
2020 if (Canon.isNull()) {
2021 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2022 if (CanonNNS != NNS)
2023 Canon = getTypenameType(CanonNNS, Name);
2024 }
2025
2026 llvm::FoldingSetNodeID ID;
2027 TypenameType::Profile(ID, NNS, Name);
2028
2029 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002030 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002031 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2032 if (T)
2033 return QualType(T, 0);
2034
2035 T = new (*this) TypenameType(NNS, Name, Canon);
2036 Types.push_back(T);
2037 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002038 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002039}
2040
Mike Stump1eb44332009-09-09 15:08:12 +00002041QualType
2042ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002043 const TemplateSpecializationType *TemplateId,
2044 QualType Canon) {
2045 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2046
Douglas Gregor789b1f62010-02-04 18:10:26 +00002047 llvm::FoldingSetNodeID ID;
2048 TypenameType::Profile(ID, NNS, TemplateId);
2049
2050 void *InsertPos = 0;
2051 TypenameType *T
2052 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2053 if (T)
2054 return QualType(T, 0);
2055
Douglas Gregor17343172009-04-01 00:28:59 +00002056 if (Canon.isNull()) {
2057 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2058 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2059 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2060 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002061 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002062 assert(CanonTemplateId &&
2063 "Canonical type must also be a template specialization type");
2064 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2065 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002066
2067 TypenameType *CheckT
2068 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2069 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002070 }
2071
Douglas Gregor17343172009-04-01 00:28:59 +00002072 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2073 Types.push_back(T);
2074 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002075 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002076}
2077
John McCall7da24312009-09-05 00:15:47 +00002078QualType
2079ASTContext::getElaboratedType(QualType UnderlyingType,
2080 ElaboratedType::TagKind Tag) {
2081 llvm::FoldingSetNodeID ID;
2082 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002083
John McCall7da24312009-09-05 00:15:47 +00002084 void *InsertPos = 0;
2085 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2086 if (T)
2087 return QualType(T, 0);
2088
Douglas Gregor789b1f62010-02-04 18:10:26 +00002089 QualType Canon = UnderlyingType;
2090 if (!Canon.isCanonical()) {
2091 Canon = getCanonicalType(Canon);
2092 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2093 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2094 }
John McCall7da24312009-09-05 00:15:47 +00002095
2096 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2097 Types.push_back(T);
2098 ElaboratedTypes.InsertNode(T, InsertPos);
2099 return QualType(T, 0);
2100}
2101
Chris Lattner88cb27a2008-04-07 04:56:42 +00002102/// CmpProtocolNames - Comparison predicate for sorting protocols
2103/// alphabetically.
2104static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2105 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002106 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002107}
2108
John McCall54e14c42009-10-22 22:37:11 +00002109static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2110 unsigned NumProtocols) {
2111 if (NumProtocols == 0) return true;
2112
2113 for (unsigned i = 1; i != NumProtocols; ++i)
2114 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2115 return false;
2116 return true;
2117}
2118
2119static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002120 unsigned &NumProtocols) {
2121 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Chris Lattner88cb27a2008-04-07 04:56:42 +00002123 // Sort protocols, keyed by name.
2124 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2125
2126 // Remove duplicates.
2127 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2128 NumProtocols = ProtocolsEnd-Protocols;
2129}
2130
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002131/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2132/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002133QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002134 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002135 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002136 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002137 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002138
2139 void *InsertPos = 0;
2140 if (ObjCObjectPointerType *QT =
2141 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2142 return QualType(QT, 0);
2143
John McCall54e14c42009-10-22 22:37:11 +00002144 // Sort the protocol list alphabetically to canonicalize it.
2145 QualType Canonical;
2146 if (!InterfaceT.isCanonical() ||
2147 !areSortedAndUniqued(Protocols, NumProtocols)) {
2148 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2149 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2150 unsigned UniqueCount = NumProtocols;
2151
2152 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2153 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2154
2155 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2156 &Sorted[0], UniqueCount);
2157 } else {
2158 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2159 Protocols, NumProtocols);
2160 }
2161
2162 // Regenerate InsertPos.
2163 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2164 }
2165
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002166 // No match.
2167 unsigned Size = sizeof(ObjCObjectPointerType)
2168 + NumProtocols * sizeof(ObjCProtocolDecl *);
2169 void *Mem = Allocate(Size, TypeAlignment);
2170 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2171 InterfaceT,
2172 Protocols,
2173 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002175 Types.push_back(QType);
2176 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2177 return QualType(QType, 0);
2178}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002179
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002180/// getObjCInterfaceType - Return the unique reference to the type for the
2181/// specified ObjC interface decl. The list of protocols is optional.
2182QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002183 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002184 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002185 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002187 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002188 if (ObjCInterfaceType *QT =
2189 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002190 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002191
John McCall54e14c42009-10-22 22:37:11 +00002192 // Sort the protocol list alphabetically to canonicalize it.
2193 QualType Canonical;
2194 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2195 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2196 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2197
2198 unsigned UniqueCount = NumProtocols;
2199 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2200
2201 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2202
2203 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2204 }
2205
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002206 unsigned Size = sizeof(ObjCInterfaceType)
2207 + NumProtocols * sizeof(ObjCProtocolDecl *);
2208 void *Mem = Allocate(Size, TypeAlignment);
2209 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2210 const_cast<ObjCInterfaceDecl*>(Decl),
2211 Protocols,
2212 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002213
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002214 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002215 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002216 return QualType(QType, 0);
2217}
2218
Douglas Gregor72564e72009-02-26 23:50:07 +00002219/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2220/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002221/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002222/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002223/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002224QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002225 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002226 if (tofExpr->isTypeDependent()) {
2227 llvm::FoldingSetNodeID ID;
2228 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregorb1975722009-07-30 23:18:24 +00002230 void *InsertPos = 0;
2231 DependentTypeOfExprType *Canon
2232 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2233 if (Canon) {
2234 // We already have a "canonical" version of an identical, dependent
2235 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002236 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002237 QualType((TypeOfExprType*)Canon, 0));
2238 }
2239 else {
2240 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002241 Canon
2242 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002243 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2244 toe = Canon;
2245 }
2246 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002247 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002248 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002249 }
Steve Naroff9752f252007-08-01 18:02:17 +00002250 Types.push_back(toe);
2251 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002252}
2253
Steve Naroff9752f252007-08-01 18:02:17 +00002254/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2255/// TypeOfType AST's. The only motivation to unique these nodes would be
2256/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002257/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002258/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002259QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002260 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002261 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002262 Types.push_back(tot);
2263 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002264}
2265
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002266/// getDecltypeForExpr - Given an expr, will return the decltype for that
2267/// expression, according to the rules in C++0x [dcl.type.simple]p4
2268static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002269 if (e->isTypeDependent())
2270 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002272 // If e is an id expression or a class member access, decltype(e) is defined
2273 // as the type of the entity named by e.
2274 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2275 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2276 return VD->getType();
2277 }
2278 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2279 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2280 return FD->getType();
2281 }
2282 // If e is a function call or an invocation of an overloaded operator,
2283 // (parentheses around e are ignored), decltype(e) is defined as the
2284 // return type of that function.
2285 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2286 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002288 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002289
2290 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002291 // defined as T&, otherwise decltype(e) is defined as T.
2292 if (e->isLvalue(Context) == Expr::LV_Valid)
2293 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002295 return T;
2296}
2297
Anders Carlsson395b4752009-06-24 19:06:50 +00002298/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2299/// DecltypeType AST's. The only motivation to unique these nodes would be
2300/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002301/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002302/// on canonical type's (which are always unique).
2303QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002304 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002305 if (e->isTypeDependent()) {
2306 llvm::FoldingSetNodeID ID;
2307 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002309 void *InsertPos = 0;
2310 DependentDecltypeType *Canon
2311 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2312 if (Canon) {
2313 // We already have a "canonical" version of an equivalent, dependent
2314 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002315 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002316 QualType((DecltypeType*)Canon, 0));
2317 }
2318 else {
2319 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002320 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002321 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2322 dt = Canon;
2323 }
2324 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002325 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002326 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002327 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002328 Types.push_back(dt);
2329 return QualType(dt, 0);
2330}
2331
Reid Spencer5f016e22007-07-11 17:01:13 +00002332/// getTagDeclType - Return the unique reference to the type for the
2333/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002334QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002335 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002336 // FIXME: What is the design on getTagDeclType when it requires casting
2337 // away const? mutable?
2338 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002339}
2340
Mike Stump1eb44332009-09-09 15:08:12 +00002341/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2342/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2343/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002344CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002345 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002346}
2347
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002348/// getSignedWCharType - Return the type of "signed wchar_t".
2349/// Used when in C++, as a GCC extension.
2350QualType ASTContext::getSignedWCharType() const {
2351 // FIXME: derive from "Target" ?
2352 return WCharTy;
2353}
2354
2355/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2356/// Used when in C++, as a GCC extension.
2357QualType ASTContext::getUnsignedWCharType() const {
2358 // FIXME: derive from "Target" ?
2359 return UnsignedIntTy;
2360}
2361
Chris Lattner8b9023b2007-07-13 03:05:23 +00002362/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2363/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2364QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002365 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002366}
2367
Chris Lattnere6327742008-04-02 05:18:44 +00002368//===----------------------------------------------------------------------===//
2369// Type Operators
2370//===----------------------------------------------------------------------===//
2371
John McCall54e14c42009-10-22 22:37:11 +00002372CanQualType ASTContext::getCanonicalParamType(QualType T) {
2373 // Push qualifiers into arrays, and then discard any remaining
2374 // qualifiers.
2375 T = getCanonicalType(T);
2376 const Type *Ty = T.getTypePtr();
2377
2378 QualType Result;
2379 if (isa<ArrayType>(Ty)) {
2380 Result = getArrayDecayedType(QualType(Ty,0));
2381 } else if (isa<FunctionType>(Ty)) {
2382 Result = getPointerType(QualType(Ty, 0));
2383 } else {
2384 Result = QualType(Ty, 0);
2385 }
2386
2387 return CanQualType::CreateUnsafe(Result);
2388}
2389
Chris Lattner77c96472008-04-06 22:41:35 +00002390/// getCanonicalType - Return the canonical (structural) type corresponding to
2391/// the specified potentially non-canonical type. The non-canonical version
2392/// of a type may have many "decorated" versions of types. Decorators can
2393/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2394/// to be free of any of these, allowing two canonical types to be compared
2395/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002396CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002397 QualifierCollector Quals;
2398 const Type *Ptr = Quals.strip(T);
2399 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002400
John McCall0953e762009-09-24 19:53:00 +00002401 // The canonical internal type will be the canonical type *except*
2402 // that we push type qualifiers down through array types.
2403
2404 // If there are no new qualifiers to push down, stop here.
2405 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002406 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002407
John McCall0953e762009-09-24 19:53:00 +00002408 // If the type qualifiers are on an array type, get the canonical
2409 // type of the array with the qualifiers applied to the element
2410 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002411 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2412 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002413 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002415 // Get the canonical version of the element with the extra qualifiers on it.
2416 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002417 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002418 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002420 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002421 return CanQualType::CreateUnsafe(
2422 getConstantArrayType(NewEltTy, CAT->getSize(),
2423 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002424 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002425 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002426 return CanQualType::CreateUnsafe(
2427 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002428 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Douglas Gregor898574e2008-12-05 23:32:09 +00002430 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002431 return CanQualType::CreateUnsafe(
2432 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002433 DSAT->getSizeExpr() ?
2434 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002435 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002436 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002437 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002438
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002439 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002440 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002441 VAT->getSizeExpr() ?
2442 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002443 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002444 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002445 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002446}
2447
Chandler Carruth28e318c2009-12-29 07:16:59 +00002448QualType ASTContext::getUnqualifiedArrayType(QualType T,
2449 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002450 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002451 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002452 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002453 }
2454
Chandler Carruth28e318c2009-12-29 07:16:59 +00002455 const ArrayType *AT = cast<ArrayType>(T);
2456 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002457 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002458 if (Elt == UnqualElt)
2459 return T;
2460
2461 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2462 return getConstantArrayType(UnqualElt, CAT->getSize(),
2463 CAT->getSizeModifier(), 0);
2464 }
2465
2466 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2467 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2468 }
2469
2470 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2471 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2472 DSAT->getSizeModifier(), 0,
2473 SourceRange());
2474}
2475
John McCall80ad16f2009-11-24 18:42:40 +00002476DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2477 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2478 return TD->getDeclName();
2479
2480 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2481 if (DTN->isIdentifier()) {
2482 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2483 } else {
2484 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2485 }
2486 }
2487
John McCall0bd6feb2009-12-02 08:04:21 +00002488 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2489 assert(Storage);
2490 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002491}
2492
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002493TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2494 // If this template name refers to a template, the canonical
2495 // template name merely stores the template itself.
2496 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002497 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002498
John McCall0bd6feb2009-12-02 08:04:21 +00002499 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002501 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2502 assert(DTN && "Non-dependent template names must refer to template decls.");
2503 return DTN->CanonicalTemplateName;
2504}
2505
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002506bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2507 X = getCanonicalTemplateName(X);
2508 Y = getCanonicalTemplateName(Y);
2509 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2510}
2511
Mike Stump1eb44332009-09-09 15:08:12 +00002512TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002513ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2514 switch (Arg.getKind()) {
2515 case TemplateArgument::Null:
2516 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002517
Douglas Gregor1275ae02009-07-28 23:00:59 +00002518 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002519 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Douglas Gregor1275ae02009-07-28 23:00:59 +00002521 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002522 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002523
Douglas Gregor788cd062009-11-11 01:00:40 +00002524 case TemplateArgument::Template:
2525 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2526
Douglas Gregor1275ae02009-07-28 23:00:59 +00002527 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002528 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002529 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Douglas Gregor1275ae02009-07-28 23:00:59 +00002531 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002532 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Douglas Gregor1275ae02009-07-28 23:00:59 +00002534 case TemplateArgument::Pack: {
2535 // FIXME: Allocate in ASTContext
2536 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2537 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002538 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002539 AEnd = Arg.pack_end();
2540 A != AEnd; (void)++A, ++Idx)
2541 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Douglas Gregor1275ae02009-07-28 23:00:59 +00002543 TemplateArgument Result;
2544 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2545 return Result;
2546 }
2547 }
2548
2549 // Silence GCC warning
2550 assert(false && "Unhandled template argument kind");
2551 return TemplateArgument();
2552}
2553
Douglas Gregord57959a2009-03-27 23:10:48 +00002554NestedNameSpecifier *
2555ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002556 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002557 return 0;
2558
2559 switch (NNS->getKind()) {
2560 case NestedNameSpecifier::Identifier:
2561 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002562 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002563 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2564 NNS->getAsIdentifier());
2565
2566 case NestedNameSpecifier::Namespace:
2567 // A namespace is canonical; build a nested-name-specifier with
2568 // this namespace and no prefix.
2569 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2570
2571 case NestedNameSpecifier::TypeSpec:
2572 case NestedNameSpecifier::TypeSpecWithTemplate: {
2573 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002574 return NestedNameSpecifier::Create(*this, 0,
2575 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002576 T.getTypePtr());
2577 }
2578
2579 case NestedNameSpecifier::Global:
2580 // The global specifier is canonical and unique.
2581 return NNS;
2582 }
2583
2584 // Required to silence a GCC warning
2585 return 0;
2586}
2587
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002588
2589const ArrayType *ASTContext::getAsArrayType(QualType T) {
2590 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002591 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002592 // Handle the common positive case fast.
2593 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2594 return AT;
2595 }
Mike Stump1eb44332009-09-09 15:08:12 +00002596
John McCall0953e762009-09-24 19:53:00 +00002597 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002598 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002599 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002600 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002601
John McCall0953e762009-09-24 19:53:00 +00002602 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002603 // implements C99 6.7.3p8: "If the specification of an array type includes
2604 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002606 // If we get here, we either have type qualifiers on the type, or we have
2607 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002608 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002609
John McCall0953e762009-09-24 19:53:00 +00002610 QualifierCollector Qs;
2611 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002613 // If we have a simple case, just return now.
2614 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002615 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002616 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002618 // Otherwise, we have an array and we have qualifiers on it. Push the
2619 // qualifiers into the array element type and return a new array type.
2620 // Get the canonical version of the element with the extra qualifiers on it.
2621 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002622 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002623
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002624 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2625 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2626 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002627 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002628 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2629 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2630 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002631 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002632
Mike Stump1eb44332009-09-09 15:08:12 +00002633 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002634 = dyn_cast<DependentSizedArrayType>(ATy))
2635 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002636 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002637 DSAT->getSizeExpr() ?
2638 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002639 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002640 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002641 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002643 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002644 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002645 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002646 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002647 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002648 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002649 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002650}
2651
2652
Chris Lattnere6327742008-04-02 05:18:44 +00002653/// getArrayDecayedType - Return the properly qualified result of decaying the
2654/// specified array type to a pointer. This operation is non-trivial when
2655/// handling typedefs etc. The canonical type of "T" must be an array type,
2656/// this returns a pointer to a properly qualified element of the array.
2657///
2658/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2659QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002660 // Get the element type with 'getAsArrayType' so that we don't lose any
2661 // typedefs in the element type of the array. This also handles propagation
2662 // of type qualifiers from the array type into the element type if present
2663 // (C99 6.7.3p8).
2664 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2665 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002667 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002668
2669 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002670 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002671}
2672
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002673QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002674 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002675 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002676 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002677 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2678 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002679 } else {
John McCall0953e762009-09-24 19:53:00 +00002680 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002681 }
2682 }
2683}
2684
Anders Carlssonfbbce492009-09-25 01:23:32 +00002685QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2686 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Anders Carlssonfbbce492009-09-25 01:23:32 +00002688 if (const ArrayType *AT = getAsArrayType(ElemTy))
2689 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Anders Carlsson6183a992008-12-21 03:44:36 +00002691 return ElemTy;
2692}
2693
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002694/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002695uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002696ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2697 uint64_t ElementCount = 1;
2698 do {
2699 ElementCount *= CA->getSize().getZExtValue();
2700 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2701 } while (CA);
2702 return ElementCount;
2703}
2704
Reid Spencer5f016e22007-07-11 17:01:13 +00002705/// getFloatingRank - Return a relative rank for floating point types.
2706/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002707static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002708 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002709 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002710
John McCall183700f2009-09-21 23:43:11 +00002711 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2712 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002713 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 case BuiltinType::Float: return FloatRank;
2715 case BuiltinType::Double: return DoubleRank;
2716 case BuiltinType::LongDouble: return LongDoubleRank;
2717 }
2718}
2719
Mike Stump1eb44332009-09-09 15:08:12 +00002720/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2721/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002722/// 'typeDomain' is a real floating point or complex type.
2723/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002724QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2725 QualType Domain) const {
2726 FloatingRank EltRank = getFloatingRank(Size);
2727 if (Domain->isComplexType()) {
2728 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002729 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002730 case FloatRank: return FloatComplexTy;
2731 case DoubleRank: return DoubleComplexTy;
2732 case LongDoubleRank: return LongDoubleComplexTy;
2733 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 }
Chris Lattner1361b112008-04-06 23:58:54 +00002735
2736 assert(Domain->isRealFloatingType() && "Unknown domain!");
2737 switch (EltRank) {
2738 default: assert(0 && "getFloatingRank(): illegal value for rank");
2739 case FloatRank: return FloatTy;
2740 case DoubleRank: return DoubleTy;
2741 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002742 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002743}
2744
Chris Lattner7cfeb082008-04-06 23:55:33 +00002745/// getFloatingTypeOrder - Compare the rank of the two specified floating
2746/// point types, ignoring the domain of the type (i.e. 'double' ==
2747/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002748/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002749int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2750 FloatingRank LHSR = getFloatingRank(LHS);
2751 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Chris Lattnera75cea32008-04-06 23:38:49 +00002753 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002754 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002755 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002756 return 1;
2757 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002758}
2759
Chris Lattnerf52ab252008-04-06 22:59:24 +00002760/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2761/// routine will assert if passed a built-in type that isn't an integer or enum,
2762/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002763unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002764 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002765 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002766 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002767
Eli Friedmana3426752009-07-05 23:44:27 +00002768 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2769 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2770
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002771 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2772 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2773
2774 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2775 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2776
Chris Lattnerf52ab252008-04-06 22:59:24 +00002777 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002778 default: assert(0 && "getIntegerRank(): not a built-in integer");
2779 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002780 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002781 case BuiltinType::Char_S:
2782 case BuiltinType::Char_U:
2783 case BuiltinType::SChar:
2784 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002785 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002786 case BuiltinType::Short:
2787 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002788 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002789 case BuiltinType::Int:
2790 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002791 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002792 case BuiltinType::Long:
2793 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002794 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002795 case BuiltinType::LongLong:
2796 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002797 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002798 case BuiltinType::Int128:
2799 case BuiltinType::UInt128:
2800 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002801 }
2802}
2803
Eli Friedman04e83572009-08-20 04:21:42 +00002804/// \brief Whether this is a promotable bitfield reference according
2805/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2806///
2807/// \returns the type this bit-field will promote to, or NULL if no
2808/// promotion occurs.
2809QualType ASTContext::isPromotableBitField(Expr *E) {
2810 FieldDecl *Field = E->getBitField();
2811 if (!Field)
2812 return QualType();
2813
2814 QualType FT = Field->getType();
2815
2816 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2817 uint64_t BitWidth = BitWidthAP.getZExtValue();
2818 uint64_t IntSize = getTypeSize(IntTy);
2819 // GCC extension compatibility: if the bit-field size is less than or equal
2820 // to the size of int, it gets promoted no matter what its type is.
2821 // For instance, unsigned long bf : 4 gets promoted to signed int.
2822 if (BitWidth < IntSize)
2823 return IntTy;
2824
2825 if (BitWidth == IntSize)
2826 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2827
2828 // Types bigger than int are not subject to promotions, and therefore act
2829 // like the base type.
2830 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2831 // is ridiculous.
2832 return QualType();
2833}
2834
Eli Friedmana95d7572009-08-19 07:44:53 +00002835/// getPromotedIntegerType - Returns the type that Promotable will
2836/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2837/// integer type.
2838QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2839 assert(!Promotable.isNull());
2840 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002841 if (const EnumType *ET = Promotable->getAs<EnumType>())
2842 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002843 if (Promotable->isSignedIntegerType())
2844 return IntTy;
2845 uint64_t PromotableSize = getTypeSize(Promotable);
2846 uint64_t IntSize = getTypeSize(IntTy);
2847 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2848 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2849}
2850
Mike Stump1eb44332009-09-09 15:08:12 +00002851/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002852/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002853/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002854int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002855 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2856 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002857 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002858
Chris Lattnerf52ab252008-04-06 22:59:24 +00002859 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2860 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Chris Lattner7cfeb082008-04-06 23:55:33 +00002862 unsigned LHSRank = getIntegerRank(LHSC);
2863 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Chris Lattner7cfeb082008-04-06 23:55:33 +00002865 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2866 if (LHSRank == RHSRank) return 0;
2867 return LHSRank > RHSRank ? 1 : -1;
2868 }
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Chris Lattner7cfeb082008-04-06 23:55:33 +00002870 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2871 if (LHSUnsigned) {
2872 // If the unsigned [LHS] type is larger, return it.
2873 if (LHSRank >= RHSRank)
2874 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Chris Lattner7cfeb082008-04-06 23:55:33 +00002876 // If the signed type can represent all values of the unsigned type, it
2877 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002878 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002879 return -1;
2880 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002881
Chris Lattner7cfeb082008-04-06 23:55:33 +00002882 // If the unsigned [RHS] type is larger, return it.
2883 if (RHSRank >= LHSRank)
2884 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Chris Lattner7cfeb082008-04-06 23:55:33 +00002886 // If the signed type can represent all values of the unsigned type, it
2887 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002888 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002889 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002890}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002891
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002892static RecordDecl *
2893CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2894 SourceLocation L, IdentifierInfo *Id) {
2895 if (Ctx.getLangOptions().CPlusPlus)
2896 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2897 else
2898 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2899}
2900
Mike Stump1eb44332009-09-09 15:08:12 +00002901// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002902QualType ASTContext::getCFConstantStringType() {
2903 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002904 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002905 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2906 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002907 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002908
Anders Carlssonf06273f2007-11-19 00:25:30 +00002909 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Anders Carlsson71993dd2007-08-17 05:31:46 +00002911 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002912 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002913 // int flags;
2914 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002915 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002916 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002917 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002918 FieldTypes[3] = LongTy;
2919
Anders Carlsson71993dd2007-08-17 05:31:46 +00002920 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002921 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002922 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002923 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002924 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002925 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002926 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002927 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002928 }
2929
2930 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002931 }
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Anders Carlsson71993dd2007-08-17 05:31:46 +00002933 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002934}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002935
Douglas Gregor319ac892009-04-23 22:29:11 +00002936void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002937 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002938 assert(Rec && "Invalid CFConstantStringType");
2939 CFConstantStringTypeDecl = Rec->getDecl();
2940}
2941
Mike Stump1eb44332009-09-09 15:08:12 +00002942QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002943 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002944 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002945 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2946 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002947 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002948
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002949 QualType FieldTypes[] = {
2950 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002951 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002952 getPointerType(UnsignedLongTy),
2953 getConstantArrayType(UnsignedLongTy,
2954 llvm::APInt(32, 5), ArrayType::Normal, 0)
2955 };
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Douglas Gregor44b43212008-12-11 16:49:14 +00002957 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002958 FieldDecl *Field = FieldDecl::Create(*this,
2959 ObjCFastEnumerationStateTypeDecl,
2960 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002961 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002962 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002963 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002964 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002965 }
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Douglas Gregor44b43212008-12-11 16:49:14 +00002967 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002968 }
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002970 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2971}
2972
Mike Stumpadaaad32009-10-20 02:12:22 +00002973QualType ASTContext::getBlockDescriptorType() {
2974 if (BlockDescriptorType)
2975 return getTagDeclType(BlockDescriptorType);
2976
2977 RecordDecl *T;
2978 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002979 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2980 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00002981 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002982
2983 QualType FieldTypes[] = {
2984 UnsignedLongTy,
2985 UnsignedLongTy,
2986 };
2987
2988 const char *FieldNames[] = {
2989 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002990 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002991 };
2992
2993 for (size_t i = 0; i < 2; ++i) {
2994 FieldDecl *Field = FieldDecl::Create(*this,
2995 T,
2996 SourceLocation(),
2997 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002998 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002999 /*BitWidth=*/0,
3000 /*Mutable=*/false);
3001 T->addDecl(Field);
3002 }
3003
3004 T->completeDefinition(*this);
3005
3006 BlockDescriptorType = T;
3007
3008 return getTagDeclType(BlockDescriptorType);
3009}
3010
3011void ASTContext::setBlockDescriptorType(QualType T) {
3012 const RecordType *Rec = T->getAs<RecordType>();
3013 assert(Rec && "Invalid BlockDescriptorType");
3014 BlockDescriptorType = Rec->getDecl();
3015}
3016
Mike Stump083c25e2009-10-22 00:49:09 +00003017QualType ASTContext::getBlockDescriptorExtendedType() {
3018 if (BlockDescriptorExtendedType)
3019 return getTagDeclType(BlockDescriptorExtendedType);
3020
3021 RecordDecl *T;
3022 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003023 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3024 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003025 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003026
3027 QualType FieldTypes[] = {
3028 UnsignedLongTy,
3029 UnsignedLongTy,
3030 getPointerType(VoidPtrTy),
3031 getPointerType(VoidPtrTy)
3032 };
3033
3034 const char *FieldNames[] = {
3035 "reserved",
3036 "Size",
3037 "CopyFuncPtr",
3038 "DestroyFuncPtr"
3039 };
3040
3041 for (size_t i = 0; i < 4; ++i) {
3042 FieldDecl *Field = FieldDecl::Create(*this,
3043 T,
3044 SourceLocation(),
3045 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003046 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003047 /*BitWidth=*/0,
3048 /*Mutable=*/false);
3049 T->addDecl(Field);
3050 }
3051
3052 T->completeDefinition(*this);
3053
3054 BlockDescriptorExtendedType = T;
3055
3056 return getTagDeclType(BlockDescriptorExtendedType);
3057}
3058
3059void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3060 const RecordType *Rec = T->getAs<RecordType>();
3061 assert(Rec && "Invalid BlockDescriptorType");
3062 BlockDescriptorExtendedType = Rec->getDecl();
3063}
3064
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003065bool ASTContext::BlockRequiresCopying(QualType Ty) {
3066 if (Ty->isBlockPointerType())
3067 return true;
3068 if (isObjCNSObjectType(Ty))
3069 return true;
3070 if (Ty->isObjCObjectPointerType())
3071 return true;
3072 return false;
3073}
3074
3075QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3076 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003077 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003078 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003079 // unsigned int __flags;
3080 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003081 // void *__copy_helper; // as needed
3082 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003083 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003084 // } *
3085
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003086 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3087
3088 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003089 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003090 llvm::SmallString<36> Name;
3091 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3092 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003093 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003094 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3095 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003096 T->startDefinition();
3097 QualType Int32Ty = IntTy;
3098 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3099 QualType FieldTypes[] = {
3100 getPointerType(VoidPtrTy),
3101 getPointerType(getTagDeclType(T)),
3102 Int32Ty,
3103 Int32Ty,
3104 getPointerType(VoidPtrTy),
3105 getPointerType(VoidPtrTy),
3106 Ty
3107 };
3108
3109 const char *FieldNames[] = {
3110 "__isa",
3111 "__forwarding",
3112 "__flags",
3113 "__size",
3114 "__copy_helper",
3115 "__destroy_helper",
3116 DeclName,
3117 };
3118
3119 for (size_t i = 0; i < 7; ++i) {
3120 if (!HasCopyAndDispose && i >=4 && i <= 5)
3121 continue;
3122 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3123 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003124 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003125 /*BitWidth=*/0, /*Mutable=*/false);
3126 T->addDecl(Field);
3127 }
3128
3129 T->completeDefinition(*this);
3130
3131 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003132}
3133
3134
3135QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003136 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003137 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003138 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003139 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003140 llvm::SmallString<36> Name;
3141 llvm::raw_svector_ostream(Name) << "__block_literal_"
3142 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003143 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003144 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3145 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003146 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003147 QualType FieldTypes[] = {
3148 getPointerType(VoidPtrTy),
3149 IntTy,
3150 IntTy,
3151 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003152 (BlockHasCopyDispose ?
3153 getPointerType(getBlockDescriptorExtendedType()) :
3154 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003155 };
3156
3157 const char *FieldNames[] = {
3158 "__isa",
3159 "__flags",
3160 "__reserved",
3161 "__FuncPtr",
3162 "__descriptor"
3163 };
3164
3165 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003166 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003167 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003168 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003169 /*BitWidth=*/0, /*Mutable=*/false);
3170 T->addDecl(Field);
3171 }
3172
3173 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3174 const Expr *E = BlockDeclRefDecls[i];
3175 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3176 clang::IdentifierInfo *Name = 0;
3177 if (BDRE) {
3178 const ValueDecl *D = BDRE->getDecl();
3179 Name = &Idents.get(D->getName());
3180 }
3181 QualType FieldType = E->getType();
3182
3183 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003184 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3185 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003186
3187 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003188 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003189 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003190 T->addDecl(Field);
3191 }
3192
3193 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003194
3195 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003196}
3197
Douglas Gregor319ac892009-04-23 22:29:11 +00003198void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003199 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003200 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3201 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3202}
3203
Anders Carlssone8c49532007-10-29 06:33:42 +00003204// This returns true if a type has been typedefed to BOOL:
3205// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003206static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003207 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003208 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3209 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003211 return false;
3212}
3213
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003214/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003215/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003216CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003217 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003218
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003219 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003220 if (sz.isPositive() && type->isIntegralType())
3221 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003222 // Treat arrays as pointers, since that's how they're passed in.
3223 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003224 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003225 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003226}
3227
3228static inline
3229std::string charUnitsToString(const CharUnits &CU) {
3230 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003231}
3232
David Chisnall5e530af2009-11-17 19:33:30 +00003233/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3234/// declaration.
3235void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3236 std::string& S) {
3237 const BlockDecl *Decl = Expr->getBlockDecl();
3238 QualType BlockTy =
3239 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3240 // Encode result type.
3241 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3242 // Compute size of all parameters.
3243 // Start with computing size of a pointer in number of bytes.
3244 // FIXME: There might(should) be a better way of doing this computation!
3245 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003246 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3247 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003248 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3249 E = Decl->param_end(); PI != E; ++PI) {
3250 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003251 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003252 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003253 ParmOffset += sz;
3254 }
3255 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003256 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003257 // Block pointer and offset.
3258 S += "@?0";
3259 ParmOffset = PtrSize;
3260
3261 // Argument types.
3262 ParmOffset = PtrSize;
3263 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3264 Decl->param_end(); PI != E; ++PI) {
3265 ParmVarDecl *PVDecl = *PI;
3266 QualType PType = PVDecl->getOriginalType();
3267 if (const ArrayType *AT =
3268 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3269 // Use array's original type only if it has known number of
3270 // elements.
3271 if (!isa<ConstantArrayType>(AT))
3272 PType = PVDecl->getType();
3273 } else if (PType->isFunctionType())
3274 PType = PVDecl->getType();
3275 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003276 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003277 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003278 }
3279}
3280
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003281/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003282/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003283void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003284 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003285 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003286 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003287 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003288 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003289 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003290 // Compute size of all parameters.
3291 // Start with computing size of a pointer in number of bytes.
3292 // FIXME: There might(should) be a better way of doing this computation!
3293 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003294 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003295 // The first two arguments (self and _cmd) are pointers; account for
3296 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003297 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003298 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3299 E = Decl->param_end(); PI != E; ++PI) {
3300 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003301 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003302 assert (sz.isPositive() &&
3303 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003304 ParmOffset += sz;
3305 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003306 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003307 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003308 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003310 // Argument types.
3311 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003312 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3313 E = Decl->param_end(); PI != E; ++PI) {
3314 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003315 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003316 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003317 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3318 // Use array's original type only if it has known number of
3319 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003320 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003321 PType = PVDecl->getType();
3322 } else if (PType->isFunctionType())
3323 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003324 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003325 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003326 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003327 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003328 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003329 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003330 }
3331}
3332
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003333/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003334/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003335/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3336/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003337/// Property attributes are stored as a comma-delimited C string. The simple
3338/// attributes readonly and bycopy are encoded as single characters. The
3339/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3340/// encoded as single characters, followed by an identifier. Property types
3341/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003342/// these attributes are defined by the following enumeration:
3343/// @code
3344/// enum PropertyAttributes {
3345/// kPropertyReadOnly = 'R', // property is read-only.
3346/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3347/// kPropertyByref = '&', // property is a reference to the value last assigned
3348/// kPropertyDynamic = 'D', // property is dynamic
3349/// kPropertyGetter = 'G', // followed by getter selector name
3350/// kPropertySetter = 'S', // followed by setter selector name
3351/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3352/// kPropertyType = 't' // followed by old-style type encoding.
3353/// kPropertyWeak = 'W' // 'weak' property
3354/// kPropertyStrong = 'P' // property GC'able
3355/// kPropertyNonAtomic = 'N' // property non-atomic
3356/// };
3357/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003358void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003359 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003360 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003361 // Collect information from the property implementation decl(s).
3362 bool Dynamic = false;
3363 ObjCPropertyImplDecl *SynthesizePID = 0;
3364
3365 // FIXME: Duplicated code due to poor abstraction.
3366 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003367 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003368 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3369 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003370 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003371 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003372 ObjCPropertyImplDecl *PID = *i;
3373 if (PID->getPropertyDecl() == PD) {
3374 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3375 Dynamic = true;
3376 } else {
3377 SynthesizePID = PID;
3378 }
3379 }
3380 }
3381 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003382 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003383 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003384 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003385 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003386 ObjCPropertyImplDecl *PID = *i;
3387 if (PID->getPropertyDecl() == PD) {
3388 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3389 Dynamic = true;
3390 } else {
3391 SynthesizePID = PID;
3392 }
3393 }
Mike Stump1eb44332009-09-09 15:08:12 +00003394 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003395 }
3396 }
3397
3398 // FIXME: This is not very efficient.
3399 S = "T";
3400
3401 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003402 // GCC has some special rules regarding encoding of properties which
3403 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003404 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003405 true /* outermost type */,
3406 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003407
3408 if (PD->isReadOnly()) {
3409 S += ",R";
3410 } else {
3411 switch (PD->getSetterKind()) {
3412 case ObjCPropertyDecl::Assign: break;
3413 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003414 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003415 }
3416 }
3417
3418 // It really isn't clear at all what this means, since properties
3419 // are "dynamic by default".
3420 if (Dynamic)
3421 S += ",D";
3422
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003423 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3424 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003426 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3427 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003428 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003429 }
3430
3431 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3432 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003433 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003434 }
3435
3436 if (SynthesizePID) {
3437 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3438 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003439 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003440 }
3441
3442 // FIXME: OBJCGC: weak & strong
3443}
3444
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003445/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003446/// Another legacy compatibility encoding: 32-bit longs are encoded as
3447/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003448/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3449///
3450void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003451 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003452 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003453 if (BT->getKind() == BuiltinType::ULong &&
3454 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003455 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003456 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003457 if (BT->getKind() == BuiltinType::Long &&
3458 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003459 PointeeTy = IntTy;
3460 }
3461 }
3462}
3463
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003464void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003465 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003466 // We follow the behavior of gcc, expanding structures which are
3467 // directly pointed to, and expanding embedded structures. Note that
3468 // these rules are sufficient to prevent recursive encoding of the
3469 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003470 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003471 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003472}
3473
Mike Stump1eb44332009-09-09 15:08:12 +00003474static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003475 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003476 const Expr *E = FD->getBitWidth();
3477 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3478 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003479 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003480 S += 'b';
3481 S += llvm::utostr(N);
3482}
3483
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003484// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003485void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3486 bool ExpandPointedToStructures,
3487 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003488 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003489 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003490 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003491 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003492 if (FD && FD->isBitField())
3493 return EncodeBitField(this, S, FD);
3494 char encoding;
3495 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003496 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003497 case BuiltinType::Void: encoding = 'v'; break;
3498 case BuiltinType::Bool: encoding = 'B'; break;
3499 case BuiltinType::Char_U:
3500 case BuiltinType::UChar: encoding = 'C'; break;
3501 case BuiltinType::UShort: encoding = 'S'; break;
3502 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003503 case BuiltinType::ULong:
3504 encoding =
3505 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003506 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003507 case BuiltinType::UInt128: encoding = 'T'; break;
3508 case BuiltinType::ULongLong: encoding = 'Q'; break;
3509 case BuiltinType::Char_S:
3510 case BuiltinType::SChar: encoding = 'c'; break;
3511 case BuiltinType::Short: encoding = 's'; break;
3512 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003513 case BuiltinType::Long:
3514 encoding =
3515 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003516 break;
3517 case BuiltinType::LongLong: encoding = 'q'; break;
3518 case BuiltinType::Int128: encoding = 't'; break;
3519 case BuiltinType::Float: encoding = 'f'; break;
3520 case BuiltinType::Double: encoding = 'd'; break;
3521 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003522 }
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003524 S += encoding;
3525 return;
3526 }
Mike Stump1eb44332009-09-09 15:08:12 +00003527
John McCall183700f2009-09-21 23:43:11 +00003528 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003529 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003530 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003531 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003532 return;
3533 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003534
Ted Kremenek6217b802009-07-29 21:53:49 +00003535 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003536 if (PT->isObjCSelType()) {
3537 S += ':';
3538 return;
3539 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003540 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003541
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003542 bool isReadOnly = false;
3543 // For historical/compatibility reasons, the read-only qualifier of the
3544 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3545 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003546 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003547 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003548 if (OutermostType && T.isConstQualified()) {
3549 isReadOnly = true;
3550 S += 'r';
3551 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003552 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003553 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003554 while (P->getAs<PointerType>())
3555 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003556 if (P.isConstQualified()) {
3557 isReadOnly = true;
3558 S += 'r';
3559 }
3560 }
3561 if (isReadOnly) {
3562 // Another legacy compatibility encoding. Some ObjC qualifier and type
3563 // combinations need to be rearranged.
3564 // Rewrite "in const" from "nr" to "rn"
3565 const char * s = S.c_str();
3566 int len = S.length();
3567 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3568 std::string replace = "rn";
3569 S.replace(S.end()-2, S.end(), replace);
3570 }
3571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003573 if (PointeeTy->isCharType()) {
3574 // char pointer types should be encoded as '*' unless it is a
3575 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003576 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003577 S += '*';
3578 return;
3579 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003580 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003581 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3582 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3583 S += '#';
3584 return;
3585 }
3586 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3587 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3588 S += '@';
3589 return;
3590 }
3591 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003592 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003593 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003594 getLegacyIntegralTypeEncoding(PointeeTy);
3595
Mike Stump1eb44332009-09-09 15:08:12 +00003596 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003597 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 return;
3599 }
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003601 if (const ArrayType *AT =
3602 // Ignore type qualifiers etc.
3603 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003604 if (isa<IncompleteArrayType>(AT)) {
3605 // Incomplete arrays are encoded as a pointer to the array element.
3606 S += '^';
3607
Mike Stump1eb44332009-09-09 15:08:12 +00003608 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003609 false, ExpandStructures, FD);
3610 } else {
3611 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Anders Carlsson559a8332009-02-22 01:38:57 +00003613 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3614 S += llvm::utostr(CAT->getSize().getZExtValue());
3615 else {
3616 //Variable length arrays are encoded as a regular array with 0 elements.
3617 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3618 S += '0';
3619 }
Mike Stump1eb44332009-09-09 15:08:12 +00003620
3621 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003622 false, ExpandStructures, FD);
3623 S += ']';
3624 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003625 return;
3626 }
Mike Stump1eb44332009-09-09 15:08:12 +00003627
John McCall183700f2009-09-21 23:43:11 +00003628 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003629 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003630 return;
3631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Ted Kremenek6217b802009-07-29 21:53:49 +00003633 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003634 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003635 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003636 // Anonymous structures print as '?'
3637 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3638 S += II->getName();
3639 } else {
3640 S += '?';
3641 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003642 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003643 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003644 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3645 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003646 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003647 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003648 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003649 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003650 S += '"';
3651 }
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003653 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003654 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003655 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003656 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003657 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003658 QualType qt = Field->getType();
3659 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003660 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003661 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003662 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003663 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003664 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003665 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003666 return;
3667 }
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003669 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003670 if (FD && FD->isBitField())
3671 EncodeBitField(this, S, FD);
3672 else
3673 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003674 return;
3675 }
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003677 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003678 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003679 return;
3680 }
Mike Stump1eb44332009-09-09 15:08:12 +00003681
John McCall0953e762009-09-24 19:53:00 +00003682 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003683 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003684 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003685 S += '{';
3686 const IdentifierInfo *II = OI->getIdentifier();
3687 S += II->getName();
3688 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003689 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003690 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003691 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003692 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003693 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003694 RecFields[i]);
3695 else
Mike Stump1eb44332009-09-09 15:08:12 +00003696 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003697 FD);
3698 }
3699 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003700 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003701 }
Mike Stump1eb44332009-09-09 15:08:12 +00003702
John McCall183700f2009-09-21 23:43:11 +00003703 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003704 if (OPT->isObjCIdType()) {
3705 S += '@';
3706 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003707 }
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Steve Naroff27d20a22009-10-28 22:03:49 +00003709 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3710 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3711 // Since this is a binary compatibility issue, need to consult with runtime
3712 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003713 S += '#';
3714 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003715 }
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003717 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003718 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003719 ExpandPointedToStructures,
3720 ExpandStructures, FD);
3721 if (FD || EncodingProperty) {
3722 // Note that we do extended encoding of protocol qualifer list
3723 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003724 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003725 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3726 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003727 S += '<';
3728 S += (*I)->getNameAsString();
3729 S += '>';
3730 }
3731 S += '"';
3732 }
3733 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003734 }
Mike Stump1eb44332009-09-09 15:08:12 +00003735
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003736 QualType PointeeTy = OPT->getPointeeType();
3737 if (!EncodingProperty &&
3738 isa<TypedefType>(PointeeTy.getTypePtr())) {
3739 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003740 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003741 // {...};
3742 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003743 getObjCEncodingForTypeImpl(PointeeTy, S,
3744 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003745 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003746 return;
3747 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003748
3749 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003750 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003751 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003752 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003753 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3754 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003755 S += '<';
3756 S += (*I)->getNameAsString();
3757 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003758 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003759 S += '"';
3760 }
3761 return;
3762 }
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003764 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003765}
3766
Mike Stump1eb44332009-09-09 15:08:12 +00003767void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003768 std::string& S) const {
3769 if (QT & Decl::OBJC_TQ_In)
3770 S += 'n';
3771 if (QT & Decl::OBJC_TQ_Inout)
3772 S += 'N';
3773 if (QT & Decl::OBJC_TQ_Out)
3774 S += 'o';
3775 if (QT & Decl::OBJC_TQ_Bycopy)
3776 S += 'O';
3777 if (QT & Decl::OBJC_TQ_Byref)
3778 S += 'R';
3779 if (QT & Decl::OBJC_TQ_Oneway)
3780 S += 'V';
3781}
3782
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003783void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003784 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003786 BuiltinVaListType = T;
3787}
3788
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003789void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003790 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003791}
3792
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003793void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003794 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003795}
3796
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003797void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003798 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003799}
3800
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003801void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003802 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003803}
3804
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003805void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003806 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003807 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003809 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003810}
3811
John McCall0bd6feb2009-12-02 08:04:21 +00003812/// \brief Retrieve the template name that corresponds to a non-empty
3813/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003814TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3815 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003816 unsigned size = End - Begin;
3817 assert(size > 1 && "set is not overloaded!");
3818
3819 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3820 size * sizeof(FunctionTemplateDecl*));
3821 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3822
3823 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003824 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003825 NamedDecl *D = *I;
3826 assert(isa<FunctionTemplateDecl>(D) ||
3827 (isa<UsingShadowDecl>(D) &&
3828 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3829 *Storage++ = D;
3830 }
3831
3832 return TemplateName(OT);
3833}
3834
Douglas Gregor7532dc62009-03-30 22:58:21 +00003835/// \brief Retrieve the template name that represents a qualified
3836/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003837TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003838 bool TemplateKeyword,
3839 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003840 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003841 llvm::FoldingSetNodeID ID;
3842 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3843
3844 void *InsertPos = 0;
3845 QualifiedTemplateName *QTN =
3846 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3847 if (!QTN) {
3848 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3849 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3850 }
3851
3852 return TemplateName(QTN);
3853}
3854
3855/// \brief Retrieve the template name that represents a dependent
3856/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003857TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003858 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003859 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003860 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003861
3862 llvm::FoldingSetNodeID ID;
3863 DependentTemplateName::Profile(ID, NNS, Name);
3864
3865 void *InsertPos = 0;
3866 DependentTemplateName *QTN =
3867 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3868
3869 if (QTN)
3870 return TemplateName(QTN);
3871
3872 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3873 if (CanonNNS == NNS) {
3874 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3875 } else {
3876 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3877 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003878 DependentTemplateName *CheckQTN =
3879 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3880 assert(!CheckQTN && "Dependent type name canonicalization broken");
3881 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003882 }
3883
3884 DependentTemplateNames.InsertNode(QTN, InsertPos);
3885 return TemplateName(QTN);
3886}
3887
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003888/// \brief Retrieve the template name that represents a dependent
3889/// template name such as \c MetaFun::template operator+.
3890TemplateName
3891ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3892 OverloadedOperatorKind Operator) {
3893 assert((!NNS || NNS->isDependent()) &&
3894 "Nested name specifier must be dependent");
3895
3896 llvm::FoldingSetNodeID ID;
3897 DependentTemplateName::Profile(ID, NNS, Operator);
3898
3899 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003900 DependentTemplateName *QTN
3901 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003902
3903 if (QTN)
3904 return TemplateName(QTN);
3905
3906 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3907 if (CanonNNS == NNS) {
3908 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3909 } else {
3910 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3911 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003912
3913 DependentTemplateName *CheckQTN
3914 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3915 assert(!CheckQTN && "Dependent template name canonicalization broken");
3916 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003917 }
3918
3919 DependentTemplateNames.InsertNode(QTN, InsertPos);
3920 return TemplateName(QTN);
3921}
3922
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003923/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003924/// TargetInfo, produce the corresponding type. The unsigned @p Type
3925/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003926CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003927 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003928 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003929 case TargetInfo::SignedShort: return ShortTy;
3930 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3931 case TargetInfo::SignedInt: return IntTy;
3932 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3933 case TargetInfo::SignedLong: return LongTy;
3934 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3935 case TargetInfo::SignedLongLong: return LongLongTy;
3936 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3937 }
3938
3939 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003940 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003941}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003942
3943//===----------------------------------------------------------------------===//
3944// Type Predicates.
3945//===----------------------------------------------------------------------===//
3946
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003947/// isObjCNSObjectType - Return true if this is an NSObject object using
3948/// NSObject attribute on a c-style pointer type.
3949/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003950/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003951///
3952bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3953 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3954 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003955 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003956 return true;
3957 }
Mike Stump1eb44332009-09-09 15:08:12 +00003958 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003959}
3960
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003961/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3962/// garbage collection attribute.
3963///
John McCall0953e762009-09-24 19:53:00 +00003964Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3965 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003966 if (getLangOptions().ObjC1 &&
3967 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003968 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003969 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003970 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003971 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003972 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003973 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003974 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003975 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003976 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003977 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003978 // Non-pointers have none gc'able attribute regardless of the attribute
3979 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003980 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003981 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003982 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003983 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003984}
3985
Chris Lattner6ac46a42008-04-07 06:51:04 +00003986//===----------------------------------------------------------------------===//
3987// Type Compatibility Testing
3988//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003989
Mike Stump1eb44332009-09-09 15:08:12 +00003990/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003991/// compatible.
3992static bool areCompatVectorTypes(const VectorType *LHS,
3993 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003994 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003995 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003996 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003997}
3998
Steve Naroff4084c302009-07-23 01:01:38 +00003999//===----------------------------------------------------------------------===//
4000// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4001//===----------------------------------------------------------------------===//
4002
4003/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4004/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004005bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4006 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004007 if (lProto == rProto)
4008 return true;
4009 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4010 E = rProto->protocol_end(); PI != E; ++PI)
4011 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4012 return true;
4013 return false;
4014}
4015
Steve Naroff4084c302009-07-23 01:01:38 +00004016/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4017/// return true if lhs's protocols conform to rhs's protocol; false
4018/// otherwise.
4019bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4020 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4021 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4022 return false;
4023}
4024
4025/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4026/// ObjCQualifiedIDType.
4027bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4028 bool compare) {
4029 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004030 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004031 lhs->isObjCIdType() || lhs->isObjCClassType())
4032 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004033 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004034 rhs->isObjCIdType() || rhs->isObjCClassType())
4035 return true;
4036
4037 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004038 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Naroff4084c302009-07-23 01:01:38 +00004040 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Steve Naroff4084c302009-07-23 01:01:38 +00004042 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004043 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004044 // make sure we check the class hierarchy.
4045 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4046 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4047 E = lhsQID->qual_end(); I != E; ++I) {
4048 // when comparing an id<P> on lhs with a static type on rhs,
4049 // see if static class implements all of id's protocols, directly or
4050 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004051 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004052 return false;
4053 }
4054 }
4055 // If there are no qualifiers and no interface, we have an 'id'.
4056 return true;
4057 }
Mike Stump1eb44332009-09-09 15:08:12 +00004058 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004059 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4060 E = lhsQID->qual_end(); I != E; ++I) {
4061 ObjCProtocolDecl *lhsProto = *I;
4062 bool match = false;
4063
4064 // when comparing an id<P> on lhs with a static type on rhs,
4065 // see if static class implements all of id's protocols, directly or
4066 // through its super class and categories.
4067 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4068 E = rhsOPT->qual_end(); J != E; ++J) {
4069 ObjCProtocolDecl *rhsProto = *J;
4070 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4071 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4072 match = true;
4073 break;
4074 }
4075 }
Mike Stump1eb44332009-09-09 15:08:12 +00004076 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004077 // make sure we check the class hierarchy.
4078 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4079 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4080 E = lhsQID->qual_end(); I != E; ++I) {
4081 // when comparing an id<P> on lhs with a static type on rhs,
4082 // see if static class implements all of id's protocols, directly or
4083 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004084 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004085 match = true;
4086 break;
4087 }
4088 }
4089 }
4090 if (!match)
4091 return false;
4092 }
Mike Stump1eb44332009-09-09 15:08:12 +00004093
Steve Naroff4084c302009-07-23 01:01:38 +00004094 return true;
4095 }
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Steve Naroff4084c302009-07-23 01:01:38 +00004097 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4098 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4099
Mike Stump1eb44332009-09-09 15:08:12 +00004100 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004101 lhs->getAsObjCInterfacePointerType()) {
4102 if (lhsOPT->qual_empty()) {
4103 bool match = false;
4104 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4105 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4106 E = rhsQID->qual_end(); I != E; ++I) {
4107 // when comparing an id<P> on lhs with a static type on rhs,
4108 // see if static class implements all of id's protocols, directly or
4109 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004110 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004111 match = true;
4112 break;
4113 }
4114 }
4115 if (!match)
4116 return false;
4117 }
4118 return true;
4119 }
Mike Stump1eb44332009-09-09 15:08:12 +00004120 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004121 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4122 E = lhsOPT->qual_end(); I != E; ++I) {
4123 ObjCProtocolDecl *lhsProto = *I;
4124 bool match = false;
4125
4126 // when comparing an id<P> on lhs with a static type on rhs,
4127 // see if static class implements all of id's protocols, directly or
4128 // through its super class and categories.
4129 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4130 E = rhsQID->qual_end(); J != E; ++J) {
4131 ObjCProtocolDecl *rhsProto = *J;
4132 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4133 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4134 match = true;
4135 break;
4136 }
4137 }
4138 if (!match)
4139 return false;
4140 }
4141 return true;
4142 }
4143 return false;
4144}
4145
Eli Friedman3d815e72008-08-22 00:56:42 +00004146/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004147/// compatible for assignment from RHS to LHS. This handles validation of any
4148/// protocol qualifiers on the LHS or RHS.
4149///
Steve Naroff14108da2009-07-10 23:34:53 +00004150bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4151 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004152 // If either type represents the built-in 'id' or 'Class' types, return true.
4153 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004154 return true;
4155
Steve Naroff4084c302009-07-23 01:01:38 +00004156 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004157 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4158 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004159 false);
4160
Steve Naroff14108da2009-07-10 23:34:53 +00004161 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4162 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004163 if (LHS && RHS) // We have 2 user-defined types.
4164 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004165
Steve Naroff4084c302009-07-23 01:01:38 +00004166 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004167}
4168
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004169/// getIntersectionOfProtocols - This routine finds the intersection of set
4170/// of protocols inherited from two distinct objective-c pointer objects.
4171/// It is used to build composite qualifier list of the composite type of
4172/// the conditional expression involving two objective-c pointer objects.
4173static
4174void getIntersectionOfProtocols(ASTContext &Context,
4175 const ObjCObjectPointerType *LHSOPT,
4176 const ObjCObjectPointerType *RHSOPT,
4177 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4178
4179 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4180 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4181
4182 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4183 unsigned LHSNumProtocols = LHS->getNumProtocols();
4184 if (LHSNumProtocols > 0)
4185 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4186 else {
4187 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4188 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4189 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4190 LHSInheritedProtocols.end());
4191 }
4192
4193 unsigned RHSNumProtocols = RHS->getNumProtocols();
4194 if (RHSNumProtocols > 0) {
4195 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4196 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4197 if (InheritedProtocolSet.count(RHSProtocols[i]))
4198 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4199 }
4200 else {
4201 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4202 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4203 // FIXME. This may cause duplication of protocols in the list, but should
4204 // be harmless.
4205 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4206 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4207 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4208 }
4209}
4210
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004211/// areCommonBaseCompatible - Returns common base class of the two classes if
4212/// one found. Note that this is O'2 algorithm. But it will be called as the
4213/// last type comparison in a ?-exp of ObjC pointer types before a
4214/// warning is issued. So, its invokation is extremely rare.
4215QualType ASTContext::areCommonBaseCompatible(
4216 const ObjCObjectPointerType *LHSOPT,
4217 const ObjCObjectPointerType *RHSOPT) {
4218 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4219 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4220 if (!LHS || !RHS)
4221 return QualType();
4222
4223 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4224 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4225 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004226 if (canAssignObjCInterfaces(LHS, RHS)) {
4227 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4228 getIntersectionOfProtocols(*this,
4229 LHSOPT, RHSOPT, IntersectionOfProtocols);
4230 if (IntersectionOfProtocols.empty())
4231 LHSTy = getObjCObjectPointerType(LHSTy);
4232 else
4233 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4234 IntersectionOfProtocols.size());
4235 return LHSTy;
4236 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004237 }
4238
4239 return QualType();
4240}
4241
Eli Friedman3d815e72008-08-22 00:56:42 +00004242bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4243 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004244 // Verify that the base decls are compatible: the RHS must be a subclass of
4245 // the LHS.
4246 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4247 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Chris Lattner6ac46a42008-04-07 06:51:04 +00004249 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4250 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004251 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004252 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Chris Lattner6ac46a42008-04-07 06:51:04 +00004254 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4255 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004256 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004257 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004258
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004259 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4260 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004261 LHSPI != LHSPE; LHSPI++) {
4262 bool RHSImplementsProtocol = false;
4263
4264 // If the RHS doesn't implement the protocol on the left, the types
4265 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004266 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004267 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004268 RHSPI != RHSPE; RHSPI++) {
4269 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004270 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004271 break;
4272 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004273 }
4274 // FIXME: For better diagnostics, consider passing back the protocol name.
4275 if (!RHSImplementsProtocol)
4276 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004277 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004278 // The RHS implements all protocols listed on the LHS.
4279 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004280}
4281
Steve Naroff389bf462009-02-12 17:52:19 +00004282bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4283 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004284 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4285 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Steve Naroff14108da2009-07-10 23:34:53 +00004287 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004288 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004289
4290 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4291 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004292}
4293
Mike Stump1eb44332009-09-09 15:08:12 +00004294/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004295/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004296/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004297/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004298bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004299 if (getLangOptions().CPlusPlus)
4300 return hasSameType(LHS, RHS);
4301
Eli Friedman3d815e72008-08-22 00:56:42 +00004302 return !mergeTypes(LHS, RHS).isNull();
4303}
4304
4305QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004306 const FunctionType *lbase = lhs->getAs<FunctionType>();
4307 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004308 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4309 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004310 bool allLTypes = true;
4311 bool allRTypes = true;
4312
4313 // Check return type
Fariborz Jahanian15ced592010-02-08 21:09:39 +00004314 QualType LRES = lbase->getResultType();
4315 QualType RRES = rbase->getResultType();
4316 Qualifiers::GC GC_L = LRES.getObjCGCAttr();
4317 Qualifiers::GC GC_R = RRES.getObjCGCAttr();
4318 // __weak/__strong attribute on one function/block return type but
4319 // not the other is OK.
4320 if (GC_L != GC_R) {
4321 if (GC_R == Qualifiers::GCNone)
4322 RRES = getObjCGCQualType(RRES, GC_L);
4323 else if (GC_L == Qualifiers::GCNone)
4324 LRES = getObjCGCQualType(LRES, GC_R);
4325 }
4326
4327 QualType retType = mergeTypes(LRES, RRES);
Eli Friedman3d815e72008-08-22 00:56:42 +00004328 if (retType.isNull()) return QualType();
Fariborz Jahanian15ced592010-02-08 21:09:39 +00004329 if (getCanonicalType(retType) != getCanonicalType(LRES))
Chris Lattner61710852008-10-05 17:34:18 +00004330 allLTypes = false;
Fariborz Jahanian15ced592010-02-08 21:09:39 +00004331 if (getCanonicalType(retType) != getCanonicalType(RRES))
Chris Lattner61710852008-10-05 17:34:18 +00004332 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004333 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004334 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4335 if (NoReturn != lbase->getNoReturnAttr())
4336 allLTypes = false;
4337 if (NoReturn != rbase->getNoReturnAttr())
4338 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004339 CallingConv lcc = lbase->getCallConv();
4340 CallingConv rcc = rbase->getCallConv();
4341 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004342 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004343 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004344
Eli Friedman3d815e72008-08-22 00:56:42 +00004345 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004346 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4347 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004348 unsigned lproto_nargs = lproto->getNumArgs();
4349 unsigned rproto_nargs = rproto->getNumArgs();
4350
4351 // Compatible functions must have the same number of arguments
4352 if (lproto_nargs != rproto_nargs)
4353 return QualType();
4354
4355 // Variadic and non-variadic functions aren't compatible
4356 if (lproto->isVariadic() != rproto->isVariadic())
4357 return QualType();
4358
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004359 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4360 return QualType();
4361
Eli Friedman3d815e72008-08-22 00:56:42 +00004362 // Check argument compatibility
4363 llvm::SmallVector<QualType, 10> types;
4364 for (unsigned i = 0; i < lproto_nargs; i++) {
4365 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4366 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4367 QualType argtype = mergeTypes(largtype, rargtype);
4368 if (argtype.isNull()) return QualType();
4369 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004370 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4371 allLTypes = false;
4372 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4373 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004374 }
4375 if (allLTypes) return lhs;
4376 if (allRTypes) return rhs;
4377 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004378 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004379 NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004380 }
4381
4382 if (lproto) allRTypes = false;
4383 if (rproto) allLTypes = false;
4384
Douglas Gregor72564e72009-02-26 23:50:07 +00004385 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004386 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004387 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004388 if (proto->isVariadic()) return QualType();
4389 // Check that the types are compatible with the types that
4390 // would result from default argument promotions (C99 6.7.5.3p15).
4391 // The only types actually affected are promotable integer
4392 // types and floats, which would be passed as a different
4393 // type depending on whether the prototype is visible.
4394 unsigned proto_nargs = proto->getNumArgs();
4395 for (unsigned i = 0; i < proto_nargs; ++i) {
4396 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004397
4398 // Look at the promotion type of enum types, since that is the type used
4399 // to pass enum values.
4400 if (const EnumType *Enum = argTy->getAs<EnumType>())
4401 argTy = Enum->getDecl()->getPromotionType();
4402
Eli Friedman3d815e72008-08-22 00:56:42 +00004403 if (argTy->isPromotableIntegerType() ||
4404 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4405 return QualType();
4406 }
4407
4408 if (allLTypes) return lhs;
4409 if (allRTypes) return rhs;
4410 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004411 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004412 proto->getTypeQuals(), NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004413 }
4414
4415 if (allLTypes) return lhs;
4416 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004417 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004418}
4419
4420QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004421 // C++ [expr]: If an expression initially has the type "reference to T", the
4422 // type is adjusted to "T" prior to any further analysis, the expression
4423 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004424 // expression is an lvalue unless the reference is an rvalue reference and
4425 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004426 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4427 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4428
Eli Friedman3d815e72008-08-22 00:56:42 +00004429 QualType LHSCan = getCanonicalType(LHS),
4430 RHSCan = getCanonicalType(RHS);
4431
4432 // If two types are identical, they are compatible.
4433 if (LHSCan == RHSCan)
4434 return LHS;
4435
John McCall0953e762009-09-24 19:53:00 +00004436 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004437 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4438 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004439 if (LQuals != RQuals) {
4440 // If any of these qualifiers are different, we have a type
4441 // mismatch.
4442 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4443 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4444 return QualType();
4445
4446 // Exactly one GC qualifier difference is allowed: __strong is
4447 // okay if the other type has no GC qualifier but is an Objective
4448 // C object pointer (i.e. implicitly strong by default). We fix
4449 // this by pretending that the unqualified type was actually
4450 // qualified __strong.
4451 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4452 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4453 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4454
4455 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4456 return QualType();
4457
4458 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4459 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4460 }
4461 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4462 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4463 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004464 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004465 }
4466
4467 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004468
Eli Friedman852d63b2009-06-01 01:22:52 +00004469 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4470 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004471
Chris Lattner1adb8832008-01-14 05:45:46 +00004472 // We want to consider the two function types to be the same for these
4473 // comparisons, just force one to the other.
4474 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4475 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004476
4477 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004478 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4479 LHSClass = Type::ConstantArray;
4480 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4481 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Nate Begeman213541a2008-04-18 23:10:10 +00004483 // Canonicalize ExtVector -> Vector.
4484 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4485 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Chris Lattnera36a61f2008-04-07 05:43:21 +00004487 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004488 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004489 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004490 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004491 // Compatibility is based on the underlying type, not the promotion
4492 // type.
John McCall183700f2009-09-21 23:43:11 +00004493 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004494 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4495 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004496 }
John McCall183700f2009-09-21 23:43:11 +00004497 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004498 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4499 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004500 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004501
Eli Friedman3d815e72008-08-22 00:56:42 +00004502 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004503 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004504
Steve Naroff4a746782008-01-09 22:43:08 +00004505 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004506 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004507#define TYPE(Class, Base)
4508#define ABSTRACT_TYPE(Class, Base)
4509#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4510#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4511#include "clang/AST/TypeNodes.def"
4512 assert(false && "Non-canonical and dependent types shouldn't get here");
4513 return QualType();
4514
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004515 case Type::LValueReference:
4516 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004517 case Type::MemberPointer:
4518 assert(false && "C++ should never be in mergeTypes");
4519 return QualType();
4520
4521 case Type::IncompleteArray:
4522 case Type::VariableArray:
4523 case Type::FunctionProto:
4524 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004525 assert(false && "Types are eliminated above");
4526 return QualType();
4527
Chris Lattner1adb8832008-01-14 05:45:46 +00004528 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004529 {
4530 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004531 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4532 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004533 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4534 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004535 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004536 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004537 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004538 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004539 return getPointerType(ResultType);
4540 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004541 case Type::BlockPointer:
4542 {
4543 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004544 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4545 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004546 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4547 if (ResultType.isNull()) return QualType();
4548 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4549 return LHS;
4550 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4551 return RHS;
4552 return getBlockPointerType(ResultType);
4553 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004554 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004555 {
4556 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4557 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4558 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4559 return QualType();
4560
4561 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4562 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4563 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4564 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004565 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4566 return LHS;
4567 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4568 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004569 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4570 ArrayType::ArraySizeModifier(), 0);
4571 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4572 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004573 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4574 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004575 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4576 return LHS;
4577 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4578 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004579 if (LVAT) {
4580 // FIXME: This isn't correct! But tricky to implement because
4581 // the array's size has to be the size of LHS, but the type
4582 // has to be different.
4583 return LHS;
4584 }
4585 if (RVAT) {
4586 // FIXME: This isn't correct! But tricky to implement because
4587 // the array's size has to be the size of RHS, but the type
4588 // has to be different.
4589 return RHS;
4590 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004591 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4592 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004593 return getIncompleteArrayType(ResultType,
4594 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004595 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004596 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004597 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004598 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004599 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004600 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004601 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004602 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004603 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004604 case Type::Complex:
4605 // Distinct complex types are incompatible.
4606 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004607 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004608 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004609 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004610 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004611 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004612 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004613 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004614 // FIXME: This should be type compatibility, e.g. whether
4615 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004616 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4617 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004618 if (LHSIface && RHSIface &&
4619 canAssignObjCInterfaces(LHSIface, RHSIface))
4620 return LHS;
4621
Eli Friedman3d815e72008-08-22 00:56:42 +00004622 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004623 }
Steve Naroff14108da2009-07-10 23:34:53 +00004624 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004625 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4626 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004627 return LHS;
4628
Steve Naroffbc76dd02008-12-10 22:14:21 +00004629 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004630 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00004631 case Type::TemplateSpecialization:
4632 assert(false && "Dependent types have no size");
4633 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004634 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004635
4636 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004637}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004638
Chris Lattner5426bf62008-04-07 07:01:58 +00004639//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004640// Integer Predicates
4641//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004642
Eli Friedmanad74a752008-06-28 06:23:08 +00004643unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004644 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004645 return 1;
John McCall842aef82009-12-09 09:09:27 +00004646 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004647 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004648 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004649 return (unsigned)getTypeSize(T);
4650}
4651
4652QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4653 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004654
4655 // Turn <4 x signed int> -> <4 x unsigned int>
4656 if (const VectorType *VTy = T->getAs<VectorType>())
4657 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004658 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004659
4660 // For enums, we return the unsigned version of the base type.
4661 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004662 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004663
4664 const BuiltinType *BTy = T->getAs<BuiltinType>();
4665 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004666 switch (BTy->getKind()) {
4667 case BuiltinType::Char_S:
4668 case BuiltinType::SChar:
4669 return UnsignedCharTy;
4670 case BuiltinType::Short:
4671 return UnsignedShortTy;
4672 case BuiltinType::Int:
4673 return UnsignedIntTy;
4674 case BuiltinType::Long:
4675 return UnsignedLongTy;
4676 case BuiltinType::LongLong:
4677 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004678 case BuiltinType::Int128:
4679 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004680 default:
4681 assert(0 && "Unexpected signed integer type");
4682 return QualType();
4683 }
4684}
4685
Douglas Gregor2cf26342009-04-09 22:27:44 +00004686ExternalASTSource::~ExternalASTSource() { }
4687
4688void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004689
4690
4691//===----------------------------------------------------------------------===//
4692// Builtin Type Computation
4693//===----------------------------------------------------------------------===//
4694
4695/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4696/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004697static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004698 ASTContext::GetBuiltinTypeError &Error,
4699 bool AllowTypeModifiers = true) {
4700 // Modifiers.
4701 int HowLong = 0;
4702 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Chris Lattner86df27b2009-06-14 00:45:47 +00004704 // Read the modifiers first.
4705 bool Done = false;
4706 while (!Done) {
4707 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004708 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004709 case 'S':
4710 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4711 assert(!Signed && "Can't use 'S' modifier multiple times!");
4712 Signed = true;
4713 break;
4714 case 'U':
4715 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4716 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4717 Unsigned = true;
4718 break;
4719 case 'L':
4720 assert(HowLong <= 2 && "Can't have LLLL modifier");
4721 ++HowLong;
4722 break;
4723 }
4724 }
4725
4726 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Chris Lattner86df27b2009-06-14 00:45:47 +00004728 // Read the base type.
4729 switch (*Str++) {
4730 default: assert(0 && "Unknown builtin type letter!");
4731 case 'v':
4732 assert(HowLong == 0 && !Signed && !Unsigned &&
4733 "Bad modifiers used with 'v'!");
4734 Type = Context.VoidTy;
4735 break;
4736 case 'f':
4737 assert(HowLong == 0 && !Signed && !Unsigned &&
4738 "Bad modifiers used with 'f'!");
4739 Type = Context.FloatTy;
4740 break;
4741 case 'd':
4742 assert(HowLong < 2 && !Signed && !Unsigned &&
4743 "Bad modifiers used with 'd'!");
4744 if (HowLong)
4745 Type = Context.LongDoubleTy;
4746 else
4747 Type = Context.DoubleTy;
4748 break;
4749 case 's':
4750 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4751 if (Unsigned)
4752 Type = Context.UnsignedShortTy;
4753 else
4754 Type = Context.ShortTy;
4755 break;
4756 case 'i':
4757 if (HowLong == 3)
4758 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4759 else if (HowLong == 2)
4760 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4761 else if (HowLong == 1)
4762 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4763 else
4764 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4765 break;
4766 case 'c':
4767 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4768 if (Signed)
4769 Type = Context.SignedCharTy;
4770 else if (Unsigned)
4771 Type = Context.UnsignedCharTy;
4772 else
4773 Type = Context.CharTy;
4774 break;
4775 case 'b': // boolean
4776 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4777 Type = Context.BoolTy;
4778 break;
4779 case 'z': // size_t.
4780 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4781 Type = Context.getSizeType();
4782 break;
4783 case 'F':
4784 Type = Context.getCFConstantStringType();
4785 break;
4786 case 'a':
4787 Type = Context.getBuiltinVaListType();
4788 assert(!Type.isNull() && "builtin va list type not initialized!");
4789 break;
4790 case 'A':
4791 // This is a "reference" to a va_list; however, what exactly
4792 // this means depends on how va_list is defined. There are two
4793 // different kinds of va_list: ones passed by value, and ones
4794 // passed by reference. An example of a by-value va_list is
4795 // x86, where va_list is a char*. An example of by-ref va_list
4796 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4797 // we want this argument to be a char*&; for x86-64, we want
4798 // it to be a __va_list_tag*.
4799 Type = Context.getBuiltinVaListType();
4800 assert(!Type.isNull() && "builtin va list type not initialized!");
4801 if (Type->isArrayType()) {
4802 Type = Context.getArrayDecayedType(Type);
4803 } else {
4804 Type = Context.getLValueReferenceType(Type);
4805 }
4806 break;
4807 case 'V': {
4808 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004809 unsigned NumElements = strtoul(Str, &End, 10);
4810 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Chris Lattner86df27b2009-06-14 00:45:47 +00004812 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Chris Lattner86df27b2009-06-14 00:45:47 +00004814 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004815 // FIXME: Don't know what to do about AltiVec.
4816 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004817 break;
4818 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004819 case 'X': {
4820 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4821 Type = Context.getComplexType(ElementType);
4822 break;
4823 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004824 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004825 Type = Context.getFILEType();
4826 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004827 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004828 return QualType();
4829 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004830 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004831 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004832 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004833 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004834 else
4835 Type = Context.getjmp_bufType();
4836
Mike Stumpfd612db2009-07-28 23:47:15 +00004837 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004838 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004839 return QualType();
4840 }
4841 break;
Mike Stump782fa302009-07-28 02:25:19 +00004842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Chris Lattner86df27b2009-06-14 00:45:47 +00004844 if (!AllowTypeModifiers)
4845 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Chris Lattner86df27b2009-06-14 00:45:47 +00004847 Done = false;
4848 while (!Done) {
4849 switch (*Str++) {
4850 default: Done = true; --Str; break;
4851 case '*':
4852 Type = Context.getPointerType(Type);
4853 break;
4854 case '&':
4855 Type = Context.getLValueReferenceType(Type);
4856 break;
4857 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4858 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004859 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004860 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004861 case 'D':
4862 Type = Context.getVolatileType(Type);
4863 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004864 }
4865 }
Mike Stump1eb44332009-09-09 15:08:12 +00004866
Chris Lattner86df27b2009-06-14 00:45:47 +00004867 return Type;
4868}
4869
4870/// GetBuiltinType - Return the type for the specified builtin.
4871QualType ASTContext::GetBuiltinType(unsigned id,
4872 GetBuiltinTypeError &Error) {
4873 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004874
Chris Lattner86df27b2009-06-14 00:45:47 +00004875 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Chris Lattner86df27b2009-06-14 00:45:47 +00004877 Error = GE_None;
4878 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4879 if (Error != GE_None)
4880 return QualType();
4881 while (TypeStr[0] && TypeStr[0] != '.') {
4882 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4883 if (Error != GE_None)
4884 return QualType();
4885
4886 // Do array -> pointer decay. The builtin should use the decayed type.
4887 if (Ty->isArrayType())
4888 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004889
Chris Lattner86df27b2009-06-14 00:45:47 +00004890 ArgTypes.push_back(Ty);
4891 }
4892
4893 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4894 "'.' should only occur at end of builtin type list!");
4895
4896 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4897 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4898 return getFunctionNoProtoType(ResType);
4899 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4900 TypeStr[0] == '.', 0);
4901}
Eli Friedmana95d7572009-08-19 07:44:53 +00004902
4903QualType
4904ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4905 // Perform the usual unary conversions. We do this early so that
4906 // integral promotions to "int" can allow us to exit early, in the
4907 // lhs == rhs check. Also, for conversion purposes, we ignore any
4908 // qualifiers. For example, "const float" and "float" are
4909 // equivalent.
4910 if (lhs->isPromotableIntegerType())
4911 lhs = getPromotedIntegerType(lhs);
4912 else
4913 lhs = lhs.getUnqualifiedType();
4914 if (rhs->isPromotableIntegerType())
4915 rhs = getPromotedIntegerType(rhs);
4916 else
4917 rhs = rhs.getUnqualifiedType();
4918
4919 // If both types are identical, no conversion is needed.
4920 if (lhs == rhs)
4921 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Eli Friedmana95d7572009-08-19 07:44:53 +00004923 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4924 // The caller can deal with this (e.g. pointer + int).
4925 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4926 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004927
4928 // At this point, we have two different arithmetic types.
4929
Eli Friedmana95d7572009-08-19 07:44:53 +00004930 // Handle complex types first (C99 6.3.1.8p1).
4931 if (lhs->isComplexType() || rhs->isComplexType()) {
4932 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004933 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004934 // convert the rhs to the lhs complex type.
4935 return lhs;
4936 }
Mike Stump1eb44332009-09-09 15:08:12 +00004937 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004938 // convert the lhs to the rhs complex type.
4939 return rhs;
4940 }
4941 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004942 // When both operands are complex, the shorter operand is converted to the
4943 // type of the longer, and that is the type of the result. This corresponds
4944 // to what is done when combining two real floating-point operands.
4945 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004946 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004947 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004948 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004949 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004950 // "double _Complex" is promoted to "long double _Complex".
4951 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004952
4953 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004954 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004955 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004956 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004957 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004958 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4959 // domains match. This is a requirement for our implementation, C99
4960 // does not require this promotion.
4961 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4962 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4963 return rhs;
4964 } else { // handle "_Complex double, double".
4965 return lhs;
4966 }
4967 }
4968 return lhs; // The domain/size match exactly.
4969 }
4970 // Now handle "real" floating types (i.e. float, double, long double).
4971 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4972 // if we have an integer operand, the result is the real floating type.
4973 if (rhs->isIntegerType()) {
4974 // convert rhs to the lhs floating point type.
4975 return lhs;
4976 }
4977 if (rhs->isComplexIntegerType()) {
4978 // convert rhs to the complex floating point type.
4979 return getComplexType(lhs);
4980 }
4981 if (lhs->isIntegerType()) {
4982 // convert lhs to the rhs floating point type.
4983 return rhs;
4984 }
Mike Stump1eb44332009-09-09 15:08:12 +00004985 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004986 // convert lhs to the complex floating point type.
4987 return getComplexType(rhs);
4988 }
4989 // We have two real floating types, float/complex combos were handled above.
4990 // Convert the smaller operand to the bigger result.
4991 int result = getFloatingTypeOrder(lhs, rhs);
4992 if (result > 0) // convert the rhs
4993 return lhs;
4994 assert(result < 0 && "illegal float comparison");
4995 return rhs; // convert the lhs
4996 }
4997 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4998 // Handle GCC complex int extension.
4999 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5000 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5001
5002 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005003 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005004 rhsComplexInt->getElementType()) >= 0)
5005 return lhs; // convert the rhs
5006 return rhs;
5007 } else if (lhsComplexInt && rhs->isIntegerType()) {
5008 // convert the rhs to the lhs complex type.
5009 return lhs;
5010 } else if (rhsComplexInt && lhs->isIntegerType()) {
5011 // convert the lhs to the rhs complex type.
5012 return rhs;
5013 }
5014 }
5015 // Finally, we have two differing integer types.
5016 // The rules for this case are in C99 6.3.1.8
5017 int compare = getIntegerTypeOrder(lhs, rhs);
5018 bool lhsSigned = lhs->isSignedIntegerType(),
5019 rhsSigned = rhs->isSignedIntegerType();
5020 QualType destType;
5021 if (lhsSigned == rhsSigned) {
5022 // Same signedness; use the higher-ranked type
5023 destType = compare >= 0 ? lhs : rhs;
5024 } else if (compare != (lhsSigned ? 1 : -1)) {
5025 // The unsigned type has greater than or equal rank to the
5026 // signed type, so use the unsigned type
5027 destType = lhsSigned ? rhs : lhs;
5028 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5029 // The two types are different widths; if we are here, that
5030 // means the signed type is larger than the unsigned type, so
5031 // use the signed type.
5032 destType = lhsSigned ? lhs : rhs;
5033 } else {
5034 // The signed type is higher-ranked than the unsigned type,
5035 // but isn't actually any bigger (like unsigned int and long
5036 // on most 32-bit systems). Use the unsigned type corresponding
5037 // to the signed type.
5038 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5039 }
5040 return destType;
5041}