blob: e729b1b58d55785acee332e1f6845aa31f78d80f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000059 if (FreeMemory) {
60 // Deallocate all the types.
61 while (!Types.empty()) {
62 Types.back()->Destroy(*this);
63 Types.pop_back();
64 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000065
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000066 for (llvm::FoldingSet<ExtQuals>::iterator
67 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
68 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000069 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 }
71 }
72
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000073 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
74 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
75 // Increment in loop to prevent using deallocated memory.
76 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
77 delete R;
78 }
79
80 for (llvm::DenseMap<const ObjCContainerDecl*,
81 const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
83 // Increment in loop to prevent using deallocated memory.
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
Nuno Lopesb74668e2008-12-17 22:30:25 +000086 }
87
Douglas Gregorab452ba2009-03-26 23:50:42 +000088 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000089 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000091 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000092 NNS != NNSEnd; ) {
93 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000095 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000263ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000265 = InstantiatedFromUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
John McCalled976492009-12-04 22:46:56 +0000273ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
274 assert((isa<UsingDecl>(Pattern) ||
275 isa<UnresolvedUsingValueDecl>(Pattern) ||
276 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277 "pattern decl is not a using decl");
278 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279 InstantiatedFromUsingDecl[Inst] = Pattern;
280}
281
282UsingShadowDecl *
283ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
284 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
285 = InstantiatedFromUsingShadowDecl.find(Inst);
286 if (Pos == InstantiatedFromUsingShadowDecl.end())
287 return 0;
288
289 return Pos->second;
290}
291
292void
293ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294 UsingShadowDecl *Pattern) {
295 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
296 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000297}
298
Anders Carlssond8b285f2009-09-01 04:26:58 +0000299FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301 = InstantiatedFromUnnamedFieldDecl.find(Field);
302 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Anders Carlssond8b285f2009-09-01 04:26:58 +0000305 return Pos->second;
306}
307
308void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309 FieldDecl *Tmpl) {
310 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
311 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316}
317
Douglas Gregor2e222532009-07-02 17:08:52 +0000318namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000320 : std::binary_function<SourceRange, SourceRange, bool> {
321 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Douglas Gregor2e222532009-07-02 17:08:52 +0000323 public:
324 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2e222532009-07-02 17:08:52 +0000326 bool operator()(SourceRange X, SourceRange Y) {
327 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328 }
329 };
330}
331
332/// \brief Determine whether the given comment is a Doxygen-style comment.
333///
334/// \param Start the start of the comment text.
335///
336/// \param End the end of the comment text.
337///
338/// \param Member whether we want to check whether this is a member comment
339/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
340/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000341static bool
342isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000343 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000345 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
346 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
347 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 if (End - Start < 4)
350 return false;
351
352 assert(Start[0] == '/' && "Not a comment?");
353 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
354 return false;
355 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
356 return false;
357
358 return (Start[3] == '<') == Member;
359}
360
361/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000362/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000363const char *ASTContext::getCommentForDecl(const Decl *D) {
364 if (!D)
365 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Douglas Gregor2e222532009-07-02 17:08:52 +0000367 // Check whether we have cached a comment string for this declaration
368 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000369 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000370 = DeclComments.find(D);
371 if (Pos != DeclComments.end())
372 return Pos->second.c_str();
373
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000375 // that source, do so now.
376 if (ExternalSource && !LoadedExternalComments) {
377 std::vector<SourceRange> LoadedComments;
378 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Douglas Gregor2e222532009-07-02 17:08:52 +0000380 if (!LoadedComments.empty())
381 Comments.insert(Comments.begin(), LoadedComments.begin(),
382 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 LoadedExternalComments = true;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
387 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 if (Comments.empty())
389 return 0;
390
391 // If the declaration doesn't map directly to a location in a file, we
392 // can't find the comment.
393 SourceLocation DeclStartLoc = D->getLocStart();
394 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
395 return 0;
396
397 // Find the comment that occurs just before this declaration.
398 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000399 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000400 SourceRange(DeclStartLoc),
401 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 // Decompose the location for the start of the declaration and find the
404 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000406 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000407 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000408 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 // First check whether we have a comment for a member.
411 if (LastComment != Comments.end() &&
412 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
413 isDoxygenComment(SourceMgr, *LastComment, true)) {
414 std::pair<FileID, unsigned> LastCommentEndDecomp
415 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
416 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000418 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000419 LastCommentEndDecomp.second)) {
420 // The Doxygen member comment comes after the declaration starts and
421 // is on the same line and in the same file as the declaration. This
422 // is the comment we want.
423 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000424 Result.append(FileBufferStart +
425 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000426 FileBufferStart + LastCommentEndDecomp.second + 1);
427 return Result.c_str();
428 }
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Douglas Gregor2e222532009-07-02 17:08:52 +0000431 if (LastComment == Comments.begin())
432 return 0;
433 --LastComment;
434
435 // Decompose the end of the comment.
436 std::pair<FileID, unsigned> LastCommentEndDecomp
437 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor2e222532009-07-02 17:08:52 +0000439 // If the comment and the declaration aren't in the same file, then they
440 // aren't related.
441 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
442 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor2e222532009-07-02 17:08:52 +0000444 // Check that we actually have a Doxygen comment.
445 if (!isDoxygenComment(SourceMgr, *LastComment))
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-07-02 17:08:52 +0000448 // Compute the starting line for the declaration and for the end of the
449 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000450 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000453 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregor2e222532009-07-02 17:08:52 +0000456 // If the comment does not end on the line prior to the declaration, then
457 // the comment is not associated with the declaration at all.
458 if (CommentEndLine + 1 != DeclStartLine)
459 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Douglas Gregor2e222532009-07-02 17:08:52 +0000461 // We have a comment, but there may be more comments on the previous lines.
462 // Keep looking so long as the comments are still Doxygen comments and are
463 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000464 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000465 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
466 std::vector<SourceRange>::iterator FirstComment = LastComment;
467 while (FirstComment != Comments.begin()) {
468 // Look at the previous comment
469 --FirstComment;
470 std::pair<FileID, unsigned> Decomp
471 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor2e222532009-07-02 17:08:52 +0000473 // If this previous comment is in a different file, we're done.
474 if (Decomp.first != DeclStartDecomp.first) {
475 ++FirstComment;
476 break;
477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregor2e222532009-07-02 17:08:52 +0000479 // If this comment is not a Doxygen comment, we're done.
480 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
481 ++FirstComment;
482 break;
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor2e222532009-07-02 17:08:52 +0000485 // If the line number is not what we expected, we're done.
486 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
487 if (Line != ExpectedLine) {
488 ++FirstComment;
489 break;
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000493 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Douglas Gregor2e222532009-07-02 17:08:52 +0000497 // The iterator range [FirstComment, LastComment] contains all of the
498 // BCPL comments that, together, are associated with this declaration.
499 // Form a single comment block string for this declaration that concatenates
500 // all of these comments.
501 std::string &Result = DeclComments[D];
502 while (FirstComment != LastComment) {
503 std::pair<FileID, unsigned> DecompStart
504 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
505 std::pair<FileID, unsigned> DecompEnd
506 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
507 Result.append(FileBufferStart + DecompStart.second,
508 FileBufferStart + DecompEnd.second + 1);
509 ++FirstComment;
510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregor2e222532009-07-02 17:08:52 +0000512 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 Result.append(FileBufferStart +
514 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 FileBufferStart + LastCommentEndDecomp.second + 1);
516 return Result.c_str();
517}
518
Chris Lattner464175b2007-07-18 17:52:12 +0000519//===----------------------------------------------------------------------===//
520// Type Sizing and Analysis
521//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000522
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000523/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
524/// scalar floating point type.
525const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000526 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527 assert(BT && "Not a floating point type!");
528 switch (BT->getKind()) {
529 default: assert(0 && "Not a floating point type!");
530 case BuiltinType::Float: return Target.getFloatFormat();
531 case BuiltinType::Double: return Target.getDoubleFormat();
532 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
533 }
534}
535
Mike Stump196efbf2009-09-22 02:43:44 +0000536/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537/// specified decl. Note that bitfields do not have a valid alignment, so
538/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000539/// If @p RefAsPointee, references are treated like their underlying type
540/// (for alignof), else they're treated like pointers (for CodeGen).
541unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000542 unsigned Align = Target.getCharWidth();
543
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000544 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000545 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546
Chris Lattneraf707ab2009-01-24 21:53:27 +0000547 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000549 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000550 if (RefAsPointee)
551 T = RT->getPointeeType();
552 else
553 T = getPointerType(RT->getPointeeType());
554 }
555 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000557 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558 T = cast<ArrayType>(T)->getElementType();
559
560 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000562 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000563
564 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000565}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000566
Chris Lattnera7674d82007-07-13 22:13:22 +0000567/// getTypeSize - Return the size of the specified type, in bits. This method
568/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000569///
570/// FIXME: Pointers into different addr spaces could have different sizes and
571/// alignment requirements: getPointerInfo should take an AddrSpace, this
572/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000573std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000574ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000575 uint64_t Width=0;
576 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000577 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000578#define TYPE(Class, Base)
579#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000580#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000583 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000584 break;
585
Chris Lattner692233e2007-07-13 22:27:08 +0000586 case Type::FunctionNoProto:
587 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000588 // GCC extension: alignof(function) = 32 bits
589 Width = 0;
590 Align = 32;
591 break;
592
Douglas Gregor72564e72009-02-26 23:50:07 +0000593 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000594 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000595 Width = 0;
596 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597 break;
598
Steve Narofffb22d962007-08-30 01:06:46 +0000599 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000600 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner98be4942008-03-05 18:54:05 +0000602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000603 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000604 Align = EltInfo.second;
605 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000606 }
Nate Begeman213541a2008-04-18 23:10:10 +0000607 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000608 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000609 const VectorType *VT = cast<VectorType>(T);
610 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
611 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000612 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000613 // If the alignment is not a power of 2, round up to the next power of 2.
614 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000615 if (VT->getNumElements() & (VT->getNumElements()-1)) {
616 Align = llvm::NextPowerOf2(Align);
617 Width = llvm::RoundUpToAlignment(Width, Align);
618 }
Chris Lattner030d8842007-07-19 22:06:24 +0000619 break;
620 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000621
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000622 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000623 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000624 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000625 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000626 // GCC extension: alignof(void) = 8 bits.
627 Width = 0;
628 Align = 8;
629 break;
630
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000632 Width = Target.getBoolWidth();
633 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000634 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000635 case BuiltinType::Char_S:
636 case BuiltinType::Char_U:
637 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getCharWidth();
640 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000642 case BuiltinType::WChar:
643 Width = Target.getWCharWidth();
644 Align = Target.getWCharAlign();
645 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000646 case BuiltinType::Char16:
647 Width = Target.getChar16Width();
648 Align = Target.getChar16Align();
649 break;
650 case BuiltinType::Char32:
651 Width = Target.getChar32Width();
652 Align = Target.getChar32Align();
653 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000654 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getShortWidth();
657 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000659 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000660 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000661 Width = Target.getIntWidth();
662 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000664 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000666 Width = Target.getLongWidth();
667 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000669 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000671 Width = Target.getLongLongWidth();
672 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000674 case BuiltinType::Int128:
675 case BuiltinType::UInt128:
676 Width = 128;
677 Align = 128; // int128_t is 128-bit aligned on all targets.
678 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000680 Width = Target.getFloatWidth();
681 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 break;
683 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000684 Width = Target.getDoubleWidth();
685 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 Width = Target.getLongDoubleWidth();
689 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000691 case BuiltinType::NullPtr:
692 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
693 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000694 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000695 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000696 break;
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
Chris Lattner34ebde42009-01-27 18:08:34 +0000823/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
824/// type for the current target in bits. This can be different than the ABI
825/// alignment in cases where it is beneficial for performance to overalign
826/// a data type.
827unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
828 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000829
830 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000831 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000832 T = CT->getElementType().getTypePtr();
833 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
834 T->isSpecificBuiltinType(BuiltinType::LongLong))
835 return std::max(ABIAlign, (unsigned)getTypeSize(T));
836
Chris Lattner34ebde42009-01-27 18:08:34 +0000837 return ABIAlign;
838}
839
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000840static void CollectLocalObjCIvars(ASTContext *Ctx,
841 const ObjCInterfaceDecl *OI,
842 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000843 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
844 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000845 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000846 if (!IVDecl->isInvalidDecl())
847 Fields.push_back(cast<FieldDecl>(IVDecl));
848 }
849}
850
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000851void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
852 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
853 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
854 CollectObjCIvars(SuperClass, Fields);
855 CollectLocalObjCIvars(this, OI, Fields);
856}
857
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000858/// ShallowCollectObjCIvars -
859/// Collect all ivars, including those synthesized, in the current class.
860///
861void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
862 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
863 bool CollectSynthesized) {
864 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
865 E = OI->ivar_end(); I != E; ++I) {
866 Ivars.push_back(*I);
867 }
868 if (CollectSynthesized)
869 CollectSynthesizedIvars(OI, Ivars);
870}
871
Fariborz Jahanian98200742009-05-12 18:14:29 +0000872void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
873 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000874 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
875 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000876 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
877 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Fariborz Jahanian98200742009-05-12 18:14:29 +0000879 // Also look into nested protocols.
880 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
881 E = PD->protocol_end(); P != E; ++P)
882 CollectProtocolSynthesizedIvars(*P, Ivars);
883}
884
885/// CollectSynthesizedIvars -
886/// This routine collect synthesized ivars for the designated class.
887///
888void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
889 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000890 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
891 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000892 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
893 Ivars.push_back(Ivar);
894 }
895 // Also look into interface's protocol list for properties declared
896 // in the protocol and whose ivars are synthesized.
897 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
898 PE = OI->protocol_end(); P != PE; ++P) {
899 ObjCProtocolDecl *PD = (*P);
900 CollectProtocolSynthesizedIvars(PD, Ivars);
901 }
902}
903
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000904/// CollectInheritedProtocols - Collect all protocols in current class and
905/// those inherited by it.
906void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
907 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
908 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
909 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
910 PE = OI->protocol_end(); P != PE; ++P) {
911 ObjCProtocolDecl *Proto = (*P);
912 Protocols.push_back(Proto);
913 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
914 PE = Proto->protocol_end(); P != PE; ++P)
915 CollectInheritedProtocols(*P, Protocols);
916 }
917
918 // Categories of this Interface.
919 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
920 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
921 CollectInheritedProtocols(CDeclChain, Protocols);
922 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
923 while (SD) {
924 CollectInheritedProtocols(SD, Protocols);
925 SD = SD->getSuperClass();
926 }
927 return;
928 }
929 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
930 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
931 PE = OC->protocol_end(); P != PE; ++P) {
932 ObjCProtocolDecl *Proto = (*P);
933 Protocols.push_back(Proto);
934 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
935 PE = Proto->protocol_end(); P != PE; ++P)
936 CollectInheritedProtocols(*P, Protocols);
937 }
938 return;
939 }
940 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
941 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
942 PE = OP->protocol_end(); P != PE; ++P) {
943 ObjCProtocolDecl *Proto = (*P);
944 Protocols.push_back(Proto);
945 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
946 PE = Proto->protocol_end(); P != PE; ++P)
947 CollectInheritedProtocols(*P, Protocols);
948 }
949 return;
950 }
951}
952
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000953unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
954 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000955 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
956 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000957 if ((*I)->getPropertyIvarDecl())
958 ++count;
959
960 // Also look into nested protocols.
961 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
962 E = PD->protocol_end(); P != E; ++P)
963 count += CountProtocolSynthesizedIvars(*P);
964 return count;
965}
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000968 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000969 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
970 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000971 if ((*I)->getPropertyIvarDecl())
972 ++count;
973 }
974 // Also look into interface's protocol list for properties declared
975 // in the protocol and whose ivars are synthesized.
976 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
977 PE = OI->protocol_end(); P != PE; ++P) {
978 ObjCProtocolDecl *PD = (*P);
979 count += CountProtocolSynthesizedIvars(PD);
980 }
981 return count;
982}
983
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000984/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
985ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
986 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
987 I = ObjCImpls.find(D);
988 if (I != ObjCImpls.end())
989 return cast<ObjCImplementationDecl>(I->second);
990 return 0;
991}
992/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
993ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
994 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
995 I = ObjCImpls.find(D);
996 if (I != ObjCImpls.end())
997 return cast<ObjCCategoryImplDecl>(I->second);
998 return 0;
999}
1000
1001/// \brief Set the implementation of ObjCInterfaceDecl.
1002void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1003 ObjCImplementationDecl *ImplD) {
1004 assert(IFaceD && ImplD && "Passed null params");
1005 ObjCImpls[IFaceD] = ImplD;
1006}
1007/// \brief Set the implementation of ObjCCategoryDecl.
1008void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1009 ObjCCategoryImplDecl *ImplD) {
1010 assert(CatD && ImplD && "Passed null params");
1011 ObjCImpls[CatD] = ImplD;
1012}
1013
John McCalla93c9342009-12-07 02:54:59 +00001014/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001015///
John McCalla93c9342009-12-07 02:54:59 +00001016/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001017/// the TypeLoc wrappers.
1018///
1019/// \param T the type that will be the basis for type source info. This type
1020/// should refer to how the declarator was written in source code, not to
1021/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001022TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001023 unsigned DataSize) {
1024 if (!DataSize)
1025 DataSize = TypeLoc::getFullDataSizeForType(T);
1026 else
1027 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001028 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001029
John McCalla93c9342009-12-07 02:54:59 +00001030 TypeSourceInfo *TInfo =
1031 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1032 new (TInfo) TypeSourceInfo(T);
1033 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001034}
1035
John McCalla93c9342009-12-07 02:54:59 +00001036TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001037 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001038 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001039 DI->getTypeLoc().initialize(L);
1040 return DI;
1041}
1042
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001043/// getInterfaceLayoutImpl - Get or compute information about the
1044/// layout of the given interface.
1045///
1046/// \param Impl - If given, also include the layout of the interface's
1047/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001048const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001049ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1050 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001051 assert(!D->isForwardDecl() && "Invalid interface decl!");
1052
Devang Patel44a3dde2008-06-04 21:54:36 +00001053 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001054 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001055 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1056 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1057 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001058
Daniel Dunbar453addb2009-05-03 11:16:44 +00001059 // Add in synthesized ivar count if laying out an implementation.
1060 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001061 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001062 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001063 // entry. Note we can't cache this because we simply free all
1064 // entries later; however we shouldn't look up implementations
1065 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001066 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001067 return getObjCLayout(D, 0);
1068 }
1069
Mike Stump1eb44332009-09-09 15:08:12 +00001070 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001071 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1072 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Devang Patel44a3dde2008-06-04 21:54:36 +00001074 return *NewEntry;
1075}
1076
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001077const ASTRecordLayout &
1078ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1079 return getObjCLayout(D, 0);
1080}
1081
1082const ASTRecordLayout &
1083ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1084 return getObjCLayout(D->getClassInterface(), D);
1085}
1086
Devang Patel88a981b2007-11-01 19:11:01 +00001087/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001088/// specified record (struct/union/class), which indicates its size and field
1089/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001090const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001091 D = D->getDefinition(*this);
1092 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001093
Chris Lattner464175b2007-07-18 17:52:12 +00001094 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001095 // Note that we can't save a reference to the entry because this function
1096 // is recursive.
1097 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001098 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001099
Mike Stump1eb44332009-09-09 15:08:12 +00001100 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001101 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001102 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Chris Lattner5d2a6302007-07-18 18:26:58 +00001104 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001105}
1106
Anders Carlssonf53df232009-12-07 04:35:11 +00001107const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1108 RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1109 assert(RD && "Cannot get key function for forward declarations!");
1110
1111 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1112 if (!Entry)
1113 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1114 else
1115 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1116 "Key function changed!");
1117
1118 return Entry;
1119}
1120
Chris Lattnera7674d82007-07-13 22:13:22 +00001121//===----------------------------------------------------------------------===//
1122// Type creation/memoization methods
1123//===----------------------------------------------------------------------===//
1124
John McCall0953e762009-09-24 19:53:00 +00001125QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1126 unsigned Fast = Quals.getFastQualifiers();
1127 Quals.removeFastQualifiers();
1128
1129 // Check if we've already instantiated this type.
1130 llvm::FoldingSetNodeID ID;
1131 ExtQuals::Profile(ID, TypeNode, Quals);
1132 void *InsertPos = 0;
1133 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1134 assert(EQ->getQualifiers() == Quals);
1135 QualType T = QualType(EQ, Fast);
1136 return T;
1137 }
1138
John McCall6b304a02009-09-24 23:30:46 +00001139 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001140 ExtQualNodes.InsertNode(New, InsertPos);
1141 QualType T = QualType(New, Fast);
1142 return T;
1143}
1144
1145QualType ASTContext::getVolatileType(QualType T) {
1146 QualType CanT = getCanonicalType(T);
1147 if (CanT.isVolatileQualified()) return T;
1148
1149 QualifierCollector Quals;
1150 const Type *TypeNode = Quals.strip(T);
1151 Quals.addVolatile();
1152
1153 return getExtQualType(TypeNode, Quals);
1154}
1155
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001156QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001157 QualType CanT = getCanonicalType(T);
1158 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001159 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001160
John McCall0953e762009-09-24 19:53:00 +00001161 // If we are composing extended qualifiers together, merge together
1162 // into one ExtQuals node.
1163 QualifierCollector Quals;
1164 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
John McCall0953e762009-09-24 19:53:00 +00001166 // If this type already has an address space specified, it cannot get
1167 // another one.
1168 assert(!Quals.hasAddressSpace() &&
1169 "Type cannot be in multiple addr spaces!");
1170 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001171
John McCall0953e762009-09-24 19:53:00 +00001172 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001173}
1174
Chris Lattnerb7d25532009-02-18 22:53:11 +00001175QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001176 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001177 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001178 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001179 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001181 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001182 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001183 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001184 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1185 return getPointerType(ResultType);
1186 }
1187 }
Mike Stump1eb44332009-09-09 15:08:12 +00001188
John McCall0953e762009-09-24 19:53:00 +00001189 // If we are composing extended qualifiers together, merge together
1190 // into one ExtQuals node.
1191 QualifierCollector Quals;
1192 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
John McCall0953e762009-09-24 19:53:00 +00001194 // If this type already has an ObjCGC specified, it cannot get
1195 // another one.
1196 assert(!Quals.hasObjCGCAttr() &&
1197 "Type cannot have multiple ObjCGCs!");
1198 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
John McCall0953e762009-09-24 19:53:00 +00001200 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001201}
Chris Lattnera7674d82007-07-13 22:13:22 +00001202
Douglas Gregor43c79c22009-12-09 00:47:37 +00001203QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
John McCall0953e762009-09-24 19:53:00 +00001204 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001205 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1206 QualType Pointee = Pointer->getPointeeType();
1207 ResultType = getNoReturnType(Pointee, AddNoReturn);
1208 if (ResultType == Pointee)
1209 return T;
1210
Mike Stump6dcbc292009-07-25 23:24:03 +00001211 ResultType = getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001212 } else if (const BlockPointerType *BlockPointer
1213 = T->getAs<BlockPointerType>()) {
1214 QualType Pointee = BlockPointer->getPointeeType();
1215 ResultType = getNoReturnType(Pointee, AddNoReturn);
1216 if (ResultType == Pointee)
1217 return T;
1218
Mike Stump6dcbc292009-07-25 23:24:03 +00001219 ResultType = getBlockPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001220 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1221 if (F->getNoReturnAttr() == AddNoReturn)
1222 return T;
1223
1224 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1225 ResultType = getFunctionNoProtoType(FNPT->getResultType(), AddNoReturn);
John McCall0953e762009-09-24 19:53:00 +00001226 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001227 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001228 ResultType
Douglas Gregor43c79c22009-12-09 00:47:37 +00001229 = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1230 FPT->getNumArgs(), FPT->isVariadic(),
1231 FPT->getTypeQuals(),
1232 FPT->hasExceptionSpec(), FPT->hasAnyExceptionSpec(),
1233 FPT->getNumExceptions(), FPT->exception_begin(),
1234 AddNoReturn);
John McCall0953e762009-09-24 19:53:00 +00001235 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001236 } else
1237 return T;
1238
Douglas Gregora4923eb2009-11-16 21:35:15 +00001239 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001240}
1241
Reid Spencer5f016e22007-07-11 17:01:13 +00001242/// getComplexType - Return the uniqued reference to the type for a complex
1243/// number with the specified element type.
1244QualType ASTContext::getComplexType(QualType T) {
1245 // Unique pointers, to guarantee there is only one pointer of a particular
1246 // structure.
1247 llvm::FoldingSetNodeID ID;
1248 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 void *InsertPos = 0;
1251 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1252 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // If the pointee type isn't canonical, this won't be a canonical type either,
1255 // so fill in the canonical type field.
1256 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001257 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001258 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 // Get the new insert position for the node we care about.
1261 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001262 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 }
John McCall6b304a02009-09-24 23:30:46 +00001264 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 Types.push_back(New);
1266 ComplexTypes.InsertNode(New, InsertPos);
1267 return QualType(New, 0);
1268}
1269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270/// getPointerType - Return the uniqued reference to the type for a pointer to
1271/// the specified type.
1272QualType ASTContext::getPointerType(QualType T) {
1273 // Unique pointers, to guarantee there is only one pointer of a particular
1274 // structure.
1275 llvm::FoldingSetNodeID ID;
1276 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 void *InsertPos = 0;
1279 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1280 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // If the pointee type isn't canonical, this won't be a canonical type either,
1283 // so fill in the canonical type field.
1284 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001285 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001286 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // Get the new insert position for the node we care about.
1289 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001290 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 }
John McCall6b304a02009-09-24 23:30:46 +00001292 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 Types.push_back(New);
1294 PointerTypes.InsertNode(New, InsertPos);
1295 return QualType(New, 0);
1296}
1297
Mike Stump1eb44332009-09-09 15:08:12 +00001298/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001299/// a pointer to the specified block.
1300QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001301 assert(T->isFunctionType() && "block of function types only");
1302 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001303 // structure.
1304 llvm::FoldingSetNodeID ID;
1305 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Steve Naroff5618bd42008-08-27 16:04:49 +00001307 void *InsertPos = 0;
1308 if (BlockPointerType *PT =
1309 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1310 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001311
1312 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001313 // type either so fill in the canonical type field.
1314 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001315 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001316 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Steve Naroff5618bd42008-08-27 16:04:49 +00001318 // Get the new insert position for the node we care about.
1319 BlockPointerType *NewIP =
1320 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001321 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001322 }
John McCall6b304a02009-09-24 23:30:46 +00001323 BlockPointerType *New
1324 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001325 Types.push_back(New);
1326 BlockPointerTypes.InsertNode(New, InsertPos);
1327 return QualType(New, 0);
1328}
1329
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001330/// getLValueReferenceType - Return the uniqued reference to the type for an
1331/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001332QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 // Unique pointers, to guarantee there is only one pointer of a particular
1334 // structure.
1335 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001336 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001337
1338 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001339 if (LValueReferenceType *RT =
1340 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001342
John McCall54e14c42009-10-22 22:37:11 +00001343 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 // If the referencee type isn't canonical, this won't be a canonical type
1346 // either, so fill in the canonical type field.
1347 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001348 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1349 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1350 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001353 LValueReferenceType *NewIP =
1354 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001355 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 }
1357
John McCall6b304a02009-09-24 23:30:46 +00001358 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001359 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1360 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001362 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001363
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001364 return QualType(New, 0);
1365}
1366
1367/// getRValueReferenceType - Return the uniqued reference to the type for an
1368/// rvalue reference to the specified type.
1369QualType ASTContext::getRValueReferenceType(QualType T) {
1370 // Unique pointers, to guarantee there is only one pointer of a particular
1371 // structure.
1372 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001373 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001374
1375 void *InsertPos = 0;
1376 if (RValueReferenceType *RT =
1377 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1378 return QualType(RT, 0);
1379
John McCall54e14c42009-10-22 22:37:11 +00001380 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1381
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001382 // If the referencee type isn't canonical, this won't be a canonical type
1383 // either, so fill in the canonical type field.
1384 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001385 if (InnerRef || !T.isCanonical()) {
1386 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1387 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001388
1389 // Get the new insert position for the node we care about.
1390 RValueReferenceType *NewIP =
1391 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1392 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1393 }
1394
John McCall6b304a02009-09-24 23:30:46 +00001395 RValueReferenceType *New
1396 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001397 Types.push_back(New);
1398 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 return QualType(New, 0);
1400}
1401
Sebastian Redlf30208a2009-01-24 21:16:55 +00001402/// getMemberPointerType - Return the uniqued reference to the type for a
1403/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001404QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001405 // Unique pointers, to guarantee there is only one pointer of a particular
1406 // structure.
1407 llvm::FoldingSetNodeID ID;
1408 MemberPointerType::Profile(ID, T, Cls);
1409
1410 void *InsertPos = 0;
1411 if (MemberPointerType *PT =
1412 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1413 return QualType(PT, 0);
1414
1415 // If the pointee or class type isn't canonical, this won't be a canonical
1416 // type either, so fill in the canonical type field.
1417 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001418 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001419 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1420
1421 // Get the new insert position for the node we care about.
1422 MemberPointerType *NewIP =
1423 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1424 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1425 }
John McCall6b304a02009-09-24 23:30:46 +00001426 MemberPointerType *New
1427 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001428 Types.push_back(New);
1429 MemberPointerTypes.InsertNode(New, InsertPos);
1430 return QualType(New, 0);
1431}
1432
Mike Stump1eb44332009-09-09 15:08:12 +00001433/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001434/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001435QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001436 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001437 ArrayType::ArraySizeModifier ASM,
1438 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001439 assert((EltTy->isDependentType() ||
1440 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001441 "Constant array of VLAs is illegal!");
1442
Chris Lattner38aeec72009-05-13 04:12:56 +00001443 // Convert the array size into a canonical width matching the pointer size for
1444 // the target.
1445 llvm::APInt ArySize(ArySizeIn);
1446 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001449 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001452 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001453 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // If the element type isn't canonical, this won't be a canonical type either,
1457 // so fill in the canonical type field.
1458 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001459 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001460 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001461 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001463 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001464 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001465 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
John McCall6b304a02009-09-24 23:30:46 +00001468 ConstantArrayType *New = new(*this,TypeAlignment)
1469 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001470 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 Types.push_back(New);
1472 return QualType(New, 0);
1473}
1474
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001475/// getVariableArrayType - Returns a non-unique reference to the type for a
1476/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001477QualType ASTContext::getVariableArrayType(QualType EltTy,
1478 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001479 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001480 unsigned EltTypeQuals,
1481 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001482 // Since we don't unique expressions, it isn't possible to unique VLA's
1483 // that have an expression provided for their size.
1484
John McCall6b304a02009-09-24 23:30:46 +00001485 VariableArrayType *New = new(*this, TypeAlignment)
1486 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001487
1488 VariableArrayTypes.push_back(New);
1489 Types.push_back(New);
1490 return QualType(New, 0);
1491}
1492
Douglas Gregor898574e2008-12-05 23:32:09 +00001493/// getDependentSizedArrayType - Returns a non-unique reference to
1494/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001495/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001496QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1497 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001498 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001499 unsigned EltTypeQuals,
1500 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001501 assert((!NumElts || NumElts->isTypeDependent() ||
1502 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001503 "Size must be type- or value-dependent!");
1504
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001505 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001506 DependentSizedArrayType *Canon = 0;
1507
1508 if (NumElts) {
1509 // Dependently-sized array types that do not have a specified
1510 // number of elements will have their sizes deduced from an
1511 // initializer.
1512 llvm::FoldingSetNodeID ID;
1513 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1514 EltTypeQuals, NumElts);
1515
1516 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1517 }
1518
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001519 DependentSizedArrayType *New;
1520 if (Canon) {
1521 // We already have a canonical version of this array type; use it as
1522 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001523 New = new (*this, TypeAlignment)
1524 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1525 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001526 } else {
1527 QualType CanonEltTy = getCanonicalType(EltTy);
1528 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001529 New = new (*this, TypeAlignment)
1530 DependentSizedArrayType(*this, EltTy, QualType(),
1531 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001532
1533 if (NumElts)
1534 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001535 } else {
1536 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1537 ASM, EltTypeQuals,
1538 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001539 New = new (*this, TypeAlignment)
1540 DependentSizedArrayType(*this, EltTy, Canon,
1541 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001542 }
1543 }
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Douglas Gregor898574e2008-12-05 23:32:09 +00001545 Types.push_back(New);
1546 return QualType(New, 0);
1547}
1548
Eli Friedmanc5773c42008-02-15 18:16:39 +00001549QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1550 ArrayType::ArraySizeModifier ASM,
1551 unsigned EltTypeQuals) {
1552 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001553 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001554
1555 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001556 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001557 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1558 return QualType(ATP, 0);
1559
1560 // If the element type isn't canonical, this won't be a canonical type
1561 // either, so fill in the canonical type field.
1562 QualType Canonical;
1563
John McCall467b27b2009-10-22 20:10:53 +00001564 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001565 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001566 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001567
1568 // Get the new insert position for the node we care about.
1569 IncompleteArrayType *NewIP =
1570 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001571 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001572 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001573
John McCall6b304a02009-09-24 23:30:46 +00001574 IncompleteArrayType *New = new (*this, TypeAlignment)
1575 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001576
1577 IncompleteArrayTypes.InsertNode(New, InsertPos);
1578 Types.push_back(New);
1579 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001580}
1581
Steve Naroff73322922007-07-18 18:00:27 +00001582/// getVectorType - Return the unique reference to a vector type of
1583/// the specified element type and size. VectorType must be a built-in type.
1584QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Chris Lattnerf52ab252008-04-06 22:59:24 +00001587 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001588 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Check if we've already instantiated a vector of this type.
1591 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001592 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 void *InsertPos = 0;
1594 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1595 return QualType(VTP, 0);
1596
1597 // If the element type isn't canonical, this won't be a canonical type either,
1598 // so fill in the canonical type field.
1599 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001600 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001601 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 // Get the new insert position for the node we care about.
1604 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001605 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 }
John McCall6b304a02009-09-24 23:30:46 +00001607 VectorType *New = new (*this, TypeAlignment)
1608 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 VectorTypes.InsertNode(New, InsertPos);
1610 Types.push_back(New);
1611 return QualType(New, 0);
1612}
1613
Nate Begeman213541a2008-04-18 23:10:10 +00001614/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001615/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001616QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001617 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattnerf52ab252008-04-06 22:59:24 +00001619 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001620 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Steve Naroff73322922007-07-18 18:00:27 +00001622 // Check if we've already instantiated a vector of this type.
1623 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001624 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001625 void *InsertPos = 0;
1626 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1627 return QualType(VTP, 0);
1628
1629 // If the element type isn't canonical, this won't be a canonical type either,
1630 // so fill in the canonical type field.
1631 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001632 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001633 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Steve Naroff73322922007-07-18 18:00:27 +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;
Steve Naroff73322922007-07-18 18:00:27 +00001638 }
John McCall6b304a02009-09-24 23:30:46 +00001639 ExtVectorType *New = new (*this, TypeAlignment)
1640 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001641 VectorTypes.InsertNode(New, InsertPos);
1642 Types.push_back(New);
1643 return QualType(New, 0);
1644}
1645
Mike Stump1eb44332009-09-09 15:08:12 +00001646QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001647 Expr *SizeExpr,
1648 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001649 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001650 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001651 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001653 void *InsertPos = 0;
1654 DependentSizedExtVectorType *Canon
1655 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1656 DependentSizedExtVectorType *New;
1657 if (Canon) {
1658 // We already have a canonical version of this array type; use it as
1659 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001660 New = new (*this, TypeAlignment)
1661 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1662 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001663 } else {
1664 QualType CanonVecTy = getCanonicalType(vecType);
1665 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001666 New = new (*this, TypeAlignment)
1667 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1668 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001669 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1670 } else {
1671 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1672 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001673 New = new (*this, TypeAlignment)
1674 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001675 }
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001678 Types.push_back(New);
1679 return QualType(New, 0);
1680}
1681
Douglas Gregor72564e72009-02-26 23:50:07 +00001682/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001683///
Mike Stump24556362009-07-25 21:26:53 +00001684QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // Unique functions, to guarantee there is only one function of a particular
1686 // structure.
1687 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001688 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001691 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001692 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001696 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001697 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001700 FunctionNoProtoType *NewIP =
1701 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001702 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 }
Mike Stump1eb44332009-09-09 15:08:12 +00001704
John McCall6b304a02009-09-24 23:30:46 +00001705 FunctionNoProtoType *New = new (*this, TypeAlignment)
1706 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001708 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 return QualType(New, 0);
1710}
1711
1712/// getFunctionType - Return a normal function type with a typed argument
1713/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001714QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001715 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001716 unsigned TypeQuals, bool hasExceptionSpec,
1717 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001718 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 // Unique functions, to guarantee there is only one function of a particular
1720 // structure.
1721 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001722 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001723 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001724 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725
1726 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001727 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001728 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001730
1731 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001732 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001734 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 isCanonical = false;
1736
1737 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001738 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 QualType Canonical;
1740 if (!isCanonical) {
1741 llvm::SmallVector<QualType, 16> CanonicalArgs;
1742 CanonicalArgs.reserve(NumArgs);
1743 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001744 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001745
Chris Lattnerf52ab252008-04-06 22:59:24 +00001746 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001747 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001748 isVariadic, TypeQuals, false,
1749 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001750
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001752 FunctionProtoType *NewIP =
1753 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001754 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001756
Douglas Gregor72564e72009-02-26 23:50:07 +00001757 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001758 // for two variable size arrays (for parameter and exception types) at the
1759 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001760 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001761 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1762 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001763 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001764 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001765 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001766 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001768 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 return QualType(FTP, 0);
1770}
1771
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001772/// getTypeDeclType - Return the unique reference to the type for the
1773/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001774QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001775 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001776 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001778 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001779 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001780 else if (isa<TemplateTypeParmDecl>(Decl)) {
1781 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001782 } else if (ObjCInterfaceDecl *ObjCInterface
1783 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001784 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001785
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001786 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001787 if (PrevDecl)
1788 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001789 else
John McCall6b304a02009-09-24 23:30:46 +00001790 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001791 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001792 if (PrevDecl)
1793 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001794 else
John McCall6b304a02009-09-24 23:30:46 +00001795 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001796 } else if (UnresolvedUsingTypenameDecl *Using =
1797 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1798 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001799 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001800 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001801
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001802 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001803 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001804}
1805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806/// getTypedefType - Return the unique reference to the type for the
1807/// specified typename decl.
1808QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1809 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Chris Lattnerf52ab252008-04-06 22:59:24 +00001811 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001812 Decl->TypeForDecl = new(*this, TypeAlignment)
1813 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 Types.push_back(Decl->TypeForDecl);
1815 return QualType(Decl->TypeForDecl, 0);
1816}
1817
John McCall49a832b2009-10-18 09:09:24 +00001818/// \brief Retrieve a substitution-result type.
1819QualType
1820ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1821 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001822 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001823 && "replacement types must always be canonical");
1824
1825 llvm::FoldingSetNodeID ID;
1826 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1827 void *InsertPos = 0;
1828 SubstTemplateTypeParmType *SubstParm
1829 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1830
1831 if (!SubstParm) {
1832 SubstParm = new (*this, TypeAlignment)
1833 SubstTemplateTypeParmType(Parm, Replacement);
1834 Types.push_back(SubstParm);
1835 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1836 }
1837
1838 return QualType(SubstParm, 0);
1839}
1840
Douglas Gregorfab9d672009-02-05 23:33:38 +00001841/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001842/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001843/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001844QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001845 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001846 IdentifierInfo *Name) {
1847 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001848 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001849 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001850 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001851 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1852
1853 if (TypeParm)
1854 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001856 if (Name) {
1857 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001858 TypeParm = new (*this, TypeAlignment)
1859 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001860 } else
John McCall6b304a02009-09-24 23:30:46 +00001861 TypeParm = new (*this, TypeAlignment)
1862 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001863
1864 Types.push_back(TypeParm);
1865 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1866
1867 return QualType(TypeParm, 0);
1868}
1869
Mike Stump1eb44332009-09-09 15:08:12 +00001870QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001871ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001872 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001873 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001874 unsigned NumArgs = Args.size();
1875
John McCall833ca992009-10-29 08:12:44 +00001876 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1877 ArgVec.reserve(NumArgs);
1878 for (unsigned i = 0; i != NumArgs; ++i)
1879 ArgVec.push_back(Args[i].getArgument());
1880
1881 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1882}
1883
1884QualType
1885ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001886 const TemplateArgument *Args,
1887 unsigned NumArgs,
1888 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001889 if (!Canon.isNull())
1890 Canon = getCanonicalType(Canon);
1891 else {
1892 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001893 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1894 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1895 CanonArgs.reserve(NumArgs);
1896 for (unsigned I = 0; I != NumArgs; ++I)
1897 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1898
1899 // Determine whether this canonical template specialization type already
1900 // exists.
1901 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001902 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001903 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001904
1905 void *InsertPos = 0;
1906 TemplateSpecializationType *Spec
1907 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor1275ae02009-07-28 23:00:59 +00001909 if (!Spec) {
1910 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001911 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001912 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001913 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001914 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001915 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001916 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001917 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001918 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001919 }
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Douglas Gregorb88e8882009-07-30 17:40:51 +00001921 if (Canon.isNull())
1922 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001923 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001924 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001925 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001926
Douglas Gregor1275ae02009-07-28 23:00:59 +00001927 // Allocate the (non-canonical) template specialization type, but don't
1928 // try to unique it: these types typically have location information that
1929 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001930 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001931 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001932 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001933 TemplateSpecializationType *Spec
1934 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001935 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Douglas Gregor55f6b142009-02-09 18:46:07 +00001937 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001938 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001939}
1940
Mike Stump1eb44332009-09-09 15:08:12 +00001941QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001942ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001943 QualType NamedType) {
1944 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001945 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001946
1947 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001948 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001949 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1950 if (T)
1951 return QualType(T, 0);
1952
Mike Stump1eb44332009-09-09 15:08:12 +00001953 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001954 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001955 Types.push_back(T);
1956 QualifiedNameTypes.InsertNode(T, InsertPos);
1957 return QualType(T, 0);
1958}
1959
Mike Stump1eb44332009-09-09 15:08:12 +00001960QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001961 const IdentifierInfo *Name,
1962 QualType Canon) {
1963 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1964
1965 if (Canon.isNull()) {
1966 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1967 if (CanonNNS != NNS)
1968 Canon = getTypenameType(CanonNNS, Name);
1969 }
1970
1971 llvm::FoldingSetNodeID ID;
1972 TypenameType::Profile(ID, NNS, Name);
1973
1974 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001975 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001976 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1977 if (T)
1978 return QualType(T, 0);
1979
1980 T = new (*this) TypenameType(NNS, Name, Canon);
1981 Types.push_back(T);
1982 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001983 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001984}
1985
Mike Stump1eb44332009-09-09 15:08:12 +00001986QualType
1987ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001988 const TemplateSpecializationType *TemplateId,
1989 QualType Canon) {
1990 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1991
1992 if (Canon.isNull()) {
1993 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1994 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1995 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1996 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001997 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001998 assert(CanonTemplateId &&
1999 "Canonical type must also be a template specialization type");
2000 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2001 }
2002 }
2003
2004 llvm::FoldingSetNodeID ID;
2005 TypenameType::Profile(ID, NNS, TemplateId);
2006
2007 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002008 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00002009 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2010 if (T)
2011 return QualType(T, 0);
2012
2013 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2014 Types.push_back(T);
2015 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002016 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002017}
2018
John McCall7da24312009-09-05 00:15:47 +00002019QualType
2020ASTContext::getElaboratedType(QualType UnderlyingType,
2021 ElaboratedType::TagKind Tag) {
2022 llvm::FoldingSetNodeID ID;
2023 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002024
John McCall7da24312009-09-05 00:15:47 +00002025 void *InsertPos = 0;
2026 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2027 if (T)
2028 return QualType(T, 0);
2029
2030 QualType Canon = getCanonicalType(UnderlyingType);
2031
2032 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2033 Types.push_back(T);
2034 ElaboratedTypes.InsertNode(T, InsertPos);
2035 return QualType(T, 0);
2036}
2037
Chris Lattner88cb27a2008-04-07 04:56:42 +00002038/// CmpProtocolNames - Comparison predicate for sorting protocols
2039/// alphabetically.
2040static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2041 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002042 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002043}
2044
John McCall54e14c42009-10-22 22:37:11 +00002045static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2046 unsigned NumProtocols) {
2047 if (NumProtocols == 0) return true;
2048
2049 for (unsigned i = 1; i != NumProtocols; ++i)
2050 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2051 return false;
2052 return true;
2053}
2054
2055static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002056 unsigned &NumProtocols) {
2057 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Chris Lattner88cb27a2008-04-07 04:56:42 +00002059 // Sort protocols, keyed by name.
2060 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2061
2062 // Remove duplicates.
2063 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2064 NumProtocols = ProtocolsEnd-Protocols;
2065}
2066
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002067/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2068/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002069QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002070 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002071 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002072 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002073 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002074
2075 void *InsertPos = 0;
2076 if (ObjCObjectPointerType *QT =
2077 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2078 return QualType(QT, 0);
2079
John McCall54e14c42009-10-22 22:37:11 +00002080 // Sort the protocol list alphabetically to canonicalize it.
2081 QualType Canonical;
2082 if (!InterfaceT.isCanonical() ||
2083 !areSortedAndUniqued(Protocols, NumProtocols)) {
2084 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2085 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2086 unsigned UniqueCount = NumProtocols;
2087
2088 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2089 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2090
2091 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2092 &Sorted[0], UniqueCount);
2093 } else {
2094 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2095 Protocols, NumProtocols);
2096 }
2097
2098 // Regenerate InsertPos.
2099 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2100 }
2101
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002102 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002103 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002104 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002106 Types.push_back(QType);
2107 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2108 return QualType(QType, 0);
2109}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002110
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002111/// getObjCInterfaceType - Return the unique reference to the type for the
2112/// specified ObjC interface decl. The list of protocols is optional.
2113QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002114 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002115 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002116 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002118 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002119 if (ObjCInterfaceType *QT =
2120 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002121 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002122
John McCall54e14c42009-10-22 22:37:11 +00002123 // Sort the protocol list alphabetically to canonicalize it.
2124 QualType Canonical;
2125 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2126 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2127 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2128
2129 unsigned UniqueCount = NumProtocols;
2130 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2131
2132 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2133
2134 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2135 }
2136
John McCall6b304a02009-09-24 23:30:46 +00002137 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002138 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002139 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002140
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002141 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002142 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002143 return QualType(QType, 0);
2144}
2145
Douglas Gregor72564e72009-02-26 23:50:07 +00002146/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2147/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002148/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002149/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002150/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002151QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002152 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002153 if (tofExpr->isTypeDependent()) {
2154 llvm::FoldingSetNodeID ID;
2155 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Douglas Gregorb1975722009-07-30 23:18:24 +00002157 void *InsertPos = 0;
2158 DependentTypeOfExprType *Canon
2159 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2160 if (Canon) {
2161 // We already have a "canonical" version of an identical, dependent
2162 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002163 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002164 QualType((TypeOfExprType*)Canon, 0));
2165 }
2166 else {
2167 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002168 Canon
2169 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002170 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2171 toe = Canon;
2172 }
2173 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002174 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002175 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002176 }
Steve Naroff9752f252007-08-01 18:02:17 +00002177 Types.push_back(toe);
2178 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002179}
2180
Steve Naroff9752f252007-08-01 18:02:17 +00002181/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2182/// TypeOfType AST's. The only motivation to unique these nodes would be
2183/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002184/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002185/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002186QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002187 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002188 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002189 Types.push_back(tot);
2190 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002191}
2192
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002193/// getDecltypeForExpr - Given an expr, will return the decltype for that
2194/// expression, according to the rules in C++0x [dcl.type.simple]p4
2195static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002196 if (e->isTypeDependent())
2197 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002199 // If e is an id expression or a class member access, decltype(e) is defined
2200 // as the type of the entity named by e.
2201 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2202 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2203 return VD->getType();
2204 }
2205 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2206 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2207 return FD->getType();
2208 }
2209 // If e is a function call or an invocation of an overloaded operator,
2210 // (parentheses around e are ignored), decltype(e) is defined as the
2211 // return type of that function.
2212 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2213 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002215 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
2217 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002218 // defined as T&, otherwise decltype(e) is defined as T.
2219 if (e->isLvalue(Context) == Expr::LV_Valid)
2220 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002222 return T;
2223}
2224
Anders Carlsson395b4752009-06-24 19:06:50 +00002225/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2226/// DecltypeType AST's. The only motivation to unique these nodes would be
2227/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002228/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002229/// on canonical type's (which are always unique).
2230QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002231 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002232 if (e->isTypeDependent()) {
2233 llvm::FoldingSetNodeID ID;
2234 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002236 void *InsertPos = 0;
2237 DependentDecltypeType *Canon
2238 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2239 if (Canon) {
2240 // We already have a "canonical" version of an equivalent, dependent
2241 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002242 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002243 QualType((DecltypeType*)Canon, 0));
2244 }
2245 else {
2246 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002247 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002248 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2249 dt = Canon;
2250 }
2251 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002252 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002253 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002254 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002255 Types.push_back(dt);
2256 return QualType(dt, 0);
2257}
2258
Reid Spencer5f016e22007-07-11 17:01:13 +00002259/// getTagDeclType - Return the unique reference to the type for the
2260/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002261QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002262 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002263 // FIXME: What is the design on getTagDeclType when it requires casting
2264 // away const? mutable?
2265 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002266}
2267
Mike Stump1eb44332009-09-09 15:08:12 +00002268/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2269/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2270/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002271CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002272 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002273}
2274
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002275/// getSignedWCharType - Return the type of "signed wchar_t".
2276/// Used when in C++, as a GCC extension.
2277QualType ASTContext::getSignedWCharType() const {
2278 // FIXME: derive from "Target" ?
2279 return WCharTy;
2280}
2281
2282/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2283/// Used when in C++, as a GCC extension.
2284QualType ASTContext::getUnsignedWCharType() const {
2285 // FIXME: derive from "Target" ?
2286 return UnsignedIntTy;
2287}
2288
Chris Lattner8b9023b2007-07-13 03:05:23 +00002289/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2290/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2291QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002292 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002293}
2294
Chris Lattnere6327742008-04-02 05:18:44 +00002295//===----------------------------------------------------------------------===//
2296// Type Operators
2297//===----------------------------------------------------------------------===//
2298
John McCall54e14c42009-10-22 22:37:11 +00002299CanQualType ASTContext::getCanonicalParamType(QualType T) {
2300 // Push qualifiers into arrays, and then discard any remaining
2301 // qualifiers.
2302 T = getCanonicalType(T);
2303 const Type *Ty = T.getTypePtr();
2304
2305 QualType Result;
2306 if (isa<ArrayType>(Ty)) {
2307 Result = getArrayDecayedType(QualType(Ty,0));
2308 } else if (isa<FunctionType>(Ty)) {
2309 Result = getPointerType(QualType(Ty, 0));
2310 } else {
2311 Result = QualType(Ty, 0);
2312 }
2313
2314 return CanQualType::CreateUnsafe(Result);
2315}
2316
Chris Lattner77c96472008-04-06 22:41:35 +00002317/// getCanonicalType - Return the canonical (structural) type corresponding to
2318/// the specified potentially non-canonical type. The non-canonical version
2319/// of a type may have many "decorated" versions of types. Decorators can
2320/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2321/// to be free of any of these, allowing two canonical types to be compared
2322/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002323CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002324 QualifierCollector Quals;
2325 const Type *Ptr = Quals.strip(T);
2326 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002327
John McCall0953e762009-09-24 19:53:00 +00002328 // The canonical internal type will be the canonical type *except*
2329 // that we push type qualifiers down through array types.
2330
2331 // If there are no new qualifiers to push down, stop here.
2332 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002333 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002334
John McCall0953e762009-09-24 19:53:00 +00002335 // If the type qualifiers are on an array type, get the canonical
2336 // type of the array with the qualifiers applied to the element
2337 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002338 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2339 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002340 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002342 // Get the canonical version of the element with the extra qualifiers on it.
2343 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002344 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002345 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002347 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002348 return CanQualType::CreateUnsafe(
2349 getConstantArrayType(NewEltTy, CAT->getSize(),
2350 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002351 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002352 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002353 return CanQualType::CreateUnsafe(
2354 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002355 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Douglas Gregor898574e2008-12-05 23:32:09 +00002357 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002358 return CanQualType::CreateUnsafe(
2359 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002360 DSAT->getSizeExpr() ?
2361 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002362 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002363 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002364 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002365
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002366 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002367 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002368 VAT->getSizeExpr() ?
2369 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002370 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002371 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002372 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002373}
2374
Chandler Carruth28e318c2009-12-29 07:16:59 +00002375QualType ASTContext::getUnqualifiedArrayType(QualType T,
2376 Qualifiers &Quals) {
2377 assert(T.isCanonical() && "Only operates on canonical types");
2378 if (!isa<ArrayType>(T)) {
2379 Quals = T.getLocalQualifiers();
2380 return T.getLocalUnqualifiedType();
2381 }
2382
2383 assert(!T.hasQualifiers() && "canonical array type has qualifiers!");
2384 const ArrayType *AT = cast<ArrayType>(T);
2385 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002386 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002387 if (Elt == UnqualElt)
2388 return T;
2389
2390 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2391 return getConstantArrayType(UnqualElt, CAT->getSize(),
2392 CAT->getSizeModifier(), 0);
2393 }
2394
2395 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2396 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2397 }
2398
2399 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2400 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2401 DSAT->getSizeModifier(), 0,
2402 SourceRange());
2403}
2404
John McCall80ad16f2009-11-24 18:42:40 +00002405DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2406 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2407 return TD->getDeclName();
2408
2409 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2410 if (DTN->isIdentifier()) {
2411 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2412 } else {
2413 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2414 }
2415 }
2416
John McCall0bd6feb2009-12-02 08:04:21 +00002417 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2418 assert(Storage);
2419 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002420}
2421
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002422TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2423 // If this template name refers to a template, the canonical
2424 // template name merely stores the template itself.
2425 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002426 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002427
John McCall0bd6feb2009-12-02 08:04:21 +00002428 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002430 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2431 assert(DTN && "Non-dependent template names must refer to template decls.");
2432 return DTN->CanonicalTemplateName;
2433}
2434
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002435bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2436 X = getCanonicalTemplateName(X);
2437 Y = getCanonicalTemplateName(Y);
2438 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2439}
2440
Mike Stump1eb44332009-09-09 15:08:12 +00002441TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002442ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2443 switch (Arg.getKind()) {
2444 case TemplateArgument::Null:
2445 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor1275ae02009-07-28 23:00:59 +00002447 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002448 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor1275ae02009-07-28 23:00:59 +00002450 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002451 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Douglas Gregor788cd062009-11-11 01:00:40 +00002453 case TemplateArgument::Template:
2454 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2455
Douglas Gregor1275ae02009-07-28 23:00:59 +00002456 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002457 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002458 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Douglas Gregor1275ae02009-07-28 23:00:59 +00002460 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002461 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Douglas Gregor1275ae02009-07-28 23:00:59 +00002463 case TemplateArgument::Pack: {
2464 // FIXME: Allocate in ASTContext
2465 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2466 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002467 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002468 AEnd = Arg.pack_end();
2469 A != AEnd; (void)++A, ++Idx)
2470 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Douglas Gregor1275ae02009-07-28 23:00:59 +00002472 TemplateArgument Result;
2473 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2474 return Result;
2475 }
2476 }
2477
2478 // Silence GCC warning
2479 assert(false && "Unhandled template argument kind");
2480 return TemplateArgument();
2481}
2482
Douglas Gregord57959a2009-03-27 23:10:48 +00002483NestedNameSpecifier *
2484ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002485 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002486 return 0;
2487
2488 switch (NNS->getKind()) {
2489 case NestedNameSpecifier::Identifier:
2490 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002491 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002492 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2493 NNS->getAsIdentifier());
2494
2495 case NestedNameSpecifier::Namespace:
2496 // A namespace is canonical; build a nested-name-specifier with
2497 // this namespace and no prefix.
2498 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2499
2500 case NestedNameSpecifier::TypeSpec:
2501 case NestedNameSpecifier::TypeSpecWithTemplate: {
2502 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002503 return NestedNameSpecifier::Create(*this, 0,
2504 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002505 T.getTypePtr());
2506 }
2507
2508 case NestedNameSpecifier::Global:
2509 // The global specifier is canonical and unique.
2510 return NNS;
2511 }
2512
2513 // Required to silence a GCC warning
2514 return 0;
2515}
2516
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002517
2518const ArrayType *ASTContext::getAsArrayType(QualType T) {
2519 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002520 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521 // Handle the common positive case fast.
2522 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2523 return AT;
2524 }
Mike Stump1eb44332009-09-09 15:08:12 +00002525
John McCall0953e762009-09-24 19:53:00 +00002526 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002527 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002528 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002529 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002530
John McCall0953e762009-09-24 19:53:00 +00002531 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002532 // implements C99 6.7.3p8: "If the specification of an array type includes
2533 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002535 // If we get here, we either have type qualifiers on the type, or we have
2536 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002537 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002538
John McCall0953e762009-09-24 19:53:00 +00002539 QualifierCollector Qs;
2540 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002542 // If we have a simple case, just return now.
2543 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002544 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002545 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002547 // Otherwise, we have an array and we have qualifiers on it. Push the
2548 // qualifiers into the array element type and return a new array type.
2549 // Get the canonical version of the element with the extra qualifiers on it.
2550 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002551 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002553 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2554 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2555 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002556 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002557 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2558 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2559 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002560 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002561
Mike Stump1eb44332009-09-09 15:08:12 +00002562 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002563 = dyn_cast<DependentSizedArrayType>(ATy))
2564 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002565 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002566 DSAT->getSizeExpr() ?
2567 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002568 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002569 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002570 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002572 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002573 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002574 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002575 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002576 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002577 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002578 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002579}
2580
2581
Chris Lattnere6327742008-04-02 05:18:44 +00002582/// getArrayDecayedType - Return the properly qualified result of decaying the
2583/// specified array type to a pointer. This operation is non-trivial when
2584/// handling typedefs etc. The canonical type of "T" must be an array type,
2585/// this returns a pointer to a properly qualified element of the array.
2586///
2587/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2588QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002589 // Get the element type with 'getAsArrayType' so that we don't lose any
2590 // typedefs in the element type of the array. This also handles propagation
2591 // of type qualifiers from the array type into the element type if present
2592 // (C99 6.7.3p8).
2593 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2594 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002596 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002597
2598 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002599 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002600}
2601
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002602QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002603 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002604 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002605 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002606 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2607 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002608 } else {
John McCall0953e762009-09-24 19:53:00 +00002609 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002610 }
2611 }
2612}
2613
Anders Carlssonfbbce492009-09-25 01:23:32 +00002614QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2615 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Anders Carlssonfbbce492009-09-25 01:23:32 +00002617 if (const ArrayType *AT = getAsArrayType(ElemTy))
2618 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Anders Carlsson6183a992008-12-21 03:44:36 +00002620 return ElemTy;
2621}
2622
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002623/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002624uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002625ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2626 uint64_t ElementCount = 1;
2627 do {
2628 ElementCount *= CA->getSize().getZExtValue();
2629 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2630 } while (CA);
2631 return ElementCount;
2632}
2633
Reid Spencer5f016e22007-07-11 17:01:13 +00002634/// getFloatingRank - Return a relative rank for floating point types.
2635/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002636static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002637 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002639
John McCall183700f2009-09-21 23:43:11 +00002640 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2641 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002642 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 case BuiltinType::Float: return FloatRank;
2644 case BuiltinType::Double: return DoubleRank;
2645 case BuiltinType::LongDouble: return LongDoubleRank;
2646 }
2647}
2648
Mike Stump1eb44332009-09-09 15:08:12 +00002649/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2650/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002651/// 'typeDomain' is a real floating point or complex type.
2652/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002653QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2654 QualType Domain) const {
2655 FloatingRank EltRank = getFloatingRank(Size);
2656 if (Domain->isComplexType()) {
2657 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002658 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002659 case FloatRank: return FloatComplexTy;
2660 case DoubleRank: return DoubleComplexTy;
2661 case LongDoubleRank: return LongDoubleComplexTy;
2662 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 }
Chris Lattner1361b112008-04-06 23:58:54 +00002664
2665 assert(Domain->isRealFloatingType() && "Unknown domain!");
2666 switch (EltRank) {
2667 default: assert(0 && "getFloatingRank(): illegal value for rank");
2668 case FloatRank: return FloatTy;
2669 case DoubleRank: return DoubleTy;
2670 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002671 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002672}
2673
Chris Lattner7cfeb082008-04-06 23:55:33 +00002674/// getFloatingTypeOrder - Compare the rank of the two specified floating
2675/// point types, ignoring the domain of the type (i.e. 'double' ==
2676/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002677/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002678int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2679 FloatingRank LHSR = getFloatingRank(LHS);
2680 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Chris Lattnera75cea32008-04-06 23:38:49 +00002682 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002683 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002684 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002685 return 1;
2686 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002687}
2688
Chris Lattnerf52ab252008-04-06 22:59:24 +00002689/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2690/// routine will assert if passed a built-in type that isn't an integer or enum,
2691/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002692unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002693 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002694 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002695 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002696
Eli Friedmana3426752009-07-05 23:44:27 +00002697 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2698 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2699
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002700 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2701 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2702
2703 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2704 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2705
Chris Lattnerf52ab252008-04-06 22:59:24 +00002706 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002707 default: assert(0 && "getIntegerRank(): not a built-in integer");
2708 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002709 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002710 case BuiltinType::Char_S:
2711 case BuiltinType::Char_U:
2712 case BuiltinType::SChar:
2713 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002714 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002715 case BuiltinType::Short:
2716 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002717 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002718 case BuiltinType::Int:
2719 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002720 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002721 case BuiltinType::Long:
2722 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002723 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002724 case BuiltinType::LongLong:
2725 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002726 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002727 case BuiltinType::Int128:
2728 case BuiltinType::UInt128:
2729 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002730 }
2731}
2732
Eli Friedman04e83572009-08-20 04:21:42 +00002733/// \brief Whether this is a promotable bitfield reference according
2734/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2735///
2736/// \returns the type this bit-field will promote to, or NULL if no
2737/// promotion occurs.
2738QualType ASTContext::isPromotableBitField(Expr *E) {
2739 FieldDecl *Field = E->getBitField();
2740 if (!Field)
2741 return QualType();
2742
2743 QualType FT = Field->getType();
2744
2745 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2746 uint64_t BitWidth = BitWidthAP.getZExtValue();
2747 uint64_t IntSize = getTypeSize(IntTy);
2748 // GCC extension compatibility: if the bit-field size is less than or equal
2749 // to the size of int, it gets promoted no matter what its type is.
2750 // For instance, unsigned long bf : 4 gets promoted to signed int.
2751 if (BitWidth < IntSize)
2752 return IntTy;
2753
2754 if (BitWidth == IntSize)
2755 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2756
2757 // Types bigger than int are not subject to promotions, and therefore act
2758 // like the base type.
2759 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2760 // is ridiculous.
2761 return QualType();
2762}
2763
Eli Friedmana95d7572009-08-19 07:44:53 +00002764/// getPromotedIntegerType - Returns the type that Promotable will
2765/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2766/// integer type.
2767QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2768 assert(!Promotable.isNull());
2769 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002770 if (const EnumType *ET = Promotable->getAs<EnumType>())
2771 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002772 if (Promotable->isSignedIntegerType())
2773 return IntTy;
2774 uint64_t PromotableSize = getTypeSize(Promotable);
2775 uint64_t IntSize = getTypeSize(IntTy);
2776 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2777 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2778}
2779
Mike Stump1eb44332009-09-09 15:08:12 +00002780/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002781/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002782/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002783int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002784 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2785 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002786 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Chris Lattnerf52ab252008-04-06 22:59:24 +00002788 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2789 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Chris Lattner7cfeb082008-04-06 23:55:33 +00002791 unsigned LHSRank = getIntegerRank(LHSC);
2792 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Chris Lattner7cfeb082008-04-06 23:55:33 +00002794 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2795 if (LHSRank == RHSRank) return 0;
2796 return LHSRank > RHSRank ? 1 : -1;
2797 }
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Chris Lattner7cfeb082008-04-06 23:55:33 +00002799 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2800 if (LHSUnsigned) {
2801 // If the unsigned [LHS] type is larger, return it.
2802 if (LHSRank >= RHSRank)
2803 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Chris Lattner7cfeb082008-04-06 23:55:33 +00002805 // If the signed type can represent all values of the unsigned type, it
2806 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002807 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002808 return -1;
2809 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002810
Chris Lattner7cfeb082008-04-06 23:55:33 +00002811 // If the unsigned [RHS] type is larger, return it.
2812 if (RHSRank >= LHSRank)
2813 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Chris Lattner7cfeb082008-04-06 23:55:33 +00002815 // If the signed type can represent all values of the unsigned type, it
2816 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002817 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002818 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002819}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002820
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002821static RecordDecl *
2822CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2823 SourceLocation L, IdentifierInfo *Id) {
2824 if (Ctx.getLangOptions().CPlusPlus)
2825 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2826 else
2827 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2828}
2829
Mike Stump1eb44332009-09-09 15:08:12 +00002830// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002831QualType ASTContext::getCFConstantStringType() {
2832 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002833 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002834 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2835 &Idents.get("NSConstantString"));
2836
Anders Carlssonf06273f2007-11-19 00:25:30 +00002837 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Anders Carlsson71993dd2007-08-17 05:31:46 +00002839 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002840 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002841 // int flags;
2842 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002843 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002844 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002845 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002846 FieldTypes[3] = LongTy;
2847
Anders Carlsson71993dd2007-08-17 05:31:46 +00002848 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002849 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002850 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002851 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002852 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002853 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002854 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002855 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002856 }
2857
2858 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002859 }
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Anders Carlsson71993dd2007-08-17 05:31:46 +00002861 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002862}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002863
Douglas Gregor319ac892009-04-23 22:29:11 +00002864void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002865 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002866 assert(Rec && "Invalid CFConstantStringType");
2867 CFConstantStringTypeDecl = Rec->getDecl();
2868}
2869
Mike Stump1eb44332009-09-09 15:08:12 +00002870QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002871 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002872 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002873 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2874 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002876 QualType FieldTypes[] = {
2877 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002878 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002879 getPointerType(UnsignedLongTy),
2880 getConstantArrayType(UnsignedLongTy,
2881 llvm::APInt(32, 5), ArrayType::Normal, 0)
2882 };
Mike Stump1eb44332009-09-09 15:08:12 +00002883
Douglas Gregor44b43212008-12-11 16:49:14 +00002884 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002885 FieldDecl *Field = FieldDecl::Create(*this,
2886 ObjCFastEnumerationStateTypeDecl,
2887 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002888 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002889 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002890 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002891 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002892 }
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Douglas Gregor44b43212008-12-11 16:49:14 +00002894 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002895 }
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002897 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2898}
2899
Mike Stumpadaaad32009-10-20 02:12:22 +00002900QualType ASTContext::getBlockDescriptorType() {
2901 if (BlockDescriptorType)
2902 return getTagDeclType(BlockDescriptorType);
2903
2904 RecordDecl *T;
2905 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002906 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2907 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002908
2909 QualType FieldTypes[] = {
2910 UnsignedLongTy,
2911 UnsignedLongTy,
2912 };
2913
2914 const char *FieldNames[] = {
2915 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002916 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002917 };
2918
2919 for (size_t i = 0; i < 2; ++i) {
2920 FieldDecl *Field = FieldDecl::Create(*this,
2921 T,
2922 SourceLocation(),
2923 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002924 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002925 /*BitWidth=*/0,
2926 /*Mutable=*/false);
2927 T->addDecl(Field);
2928 }
2929
2930 T->completeDefinition(*this);
2931
2932 BlockDescriptorType = T;
2933
2934 return getTagDeclType(BlockDescriptorType);
2935}
2936
2937void ASTContext::setBlockDescriptorType(QualType T) {
2938 const RecordType *Rec = T->getAs<RecordType>();
2939 assert(Rec && "Invalid BlockDescriptorType");
2940 BlockDescriptorType = Rec->getDecl();
2941}
2942
Mike Stump083c25e2009-10-22 00:49:09 +00002943QualType ASTContext::getBlockDescriptorExtendedType() {
2944 if (BlockDescriptorExtendedType)
2945 return getTagDeclType(BlockDescriptorExtendedType);
2946
2947 RecordDecl *T;
2948 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002949 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2950 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002951
2952 QualType FieldTypes[] = {
2953 UnsignedLongTy,
2954 UnsignedLongTy,
2955 getPointerType(VoidPtrTy),
2956 getPointerType(VoidPtrTy)
2957 };
2958
2959 const char *FieldNames[] = {
2960 "reserved",
2961 "Size",
2962 "CopyFuncPtr",
2963 "DestroyFuncPtr"
2964 };
2965
2966 for (size_t i = 0; i < 4; ++i) {
2967 FieldDecl *Field = FieldDecl::Create(*this,
2968 T,
2969 SourceLocation(),
2970 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002971 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00002972 /*BitWidth=*/0,
2973 /*Mutable=*/false);
2974 T->addDecl(Field);
2975 }
2976
2977 T->completeDefinition(*this);
2978
2979 BlockDescriptorExtendedType = T;
2980
2981 return getTagDeclType(BlockDescriptorExtendedType);
2982}
2983
2984void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2985 const RecordType *Rec = T->getAs<RecordType>();
2986 assert(Rec && "Invalid BlockDescriptorType");
2987 BlockDescriptorExtendedType = Rec->getDecl();
2988}
2989
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002990bool ASTContext::BlockRequiresCopying(QualType Ty) {
2991 if (Ty->isBlockPointerType())
2992 return true;
2993 if (isObjCNSObjectType(Ty))
2994 return true;
2995 if (Ty->isObjCObjectPointerType())
2996 return true;
2997 return false;
2998}
2999
3000QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3001 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003002 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003003 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003004 // unsigned int __flags;
3005 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003006 // void *__copy_helper; // as needed
3007 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003008 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003009 // } *
3010
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003011 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3012
3013 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003014 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003015 llvm::SmallString<36> Name;
3016 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3017 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003018 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003019 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3020 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003021 T->startDefinition();
3022 QualType Int32Ty = IntTy;
3023 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3024 QualType FieldTypes[] = {
3025 getPointerType(VoidPtrTy),
3026 getPointerType(getTagDeclType(T)),
3027 Int32Ty,
3028 Int32Ty,
3029 getPointerType(VoidPtrTy),
3030 getPointerType(VoidPtrTy),
3031 Ty
3032 };
3033
3034 const char *FieldNames[] = {
3035 "__isa",
3036 "__forwarding",
3037 "__flags",
3038 "__size",
3039 "__copy_helper",
3040 "__destroy_helper",
3041 DeclName,
3042 };
3043
3044 for (size_t i = 0; i < 7; ++i) {
3045 if (!HasCopyAndDispose && i >=4 && i <= 5)
3046 continue;
3047 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3048 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003049 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003050 /*BitWidth=*/0, /*Mutable=*/false);
3051 T->addDecl(Field);
3052 }
3053
3054 T->completeDefinition(*this);
3055
3056 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003057}
3058
3059
3060QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003061 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003062 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003063 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003064 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003065 llvm::SmallString<36> Name;
3066 llvm::raw_svector_ostream(Name) << "__block_literal_"
3067 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003068 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003069 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3070 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003071 QualType FieldTypes[] = {
3072 getPointerType(VoidPtrTy),
3073 IntTy,
3074 IntTy,
3075 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003076 (BlockHasCopyDispose ?
3077 getPointerType(getBlockDescriptorExtendedType()) :
3078 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003079 };
3080
3081 const char *FieldNames[] = {
3082 "__isa",
3083 "__flags",
3084 "__reserved",
3085 "__FuncPtr",
3086 "__descriptor"
3087 };
3088
3089 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003090 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003091 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003092 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003093 /*BitWidth=*/0, /*Mutable=*/false);
3094 T->addDecl(Field);
3095 }
3096
3097 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3098 const Expr *E = BlockDeclRefDecls[i];
3099 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3100 clang::IdentifierInfo *Name = 0;
3101 if (BDRE) {
3102 const ValueDecl *D = BDRE->getDecl();
3103 Name = &Idents.get(D->getName());
3104 }
3105 QualType FieldType = E->getType();
3106
3107 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003108 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3109 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003110
3111 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003112 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003113 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003114 T->addDecl(Field);
3115 }
3116
3117 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003118
3119 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003120}
3121
Douglas Gregor319ac892009-04-23 22:29:11 +00003122void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003123 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003124 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3125 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3126}
3127
Anders Carlssone8c49532007-10-29 06:33:42 +00003128// This returns true if a type has been typedefed to BOOL:
3129// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003130static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003131 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003132 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3133 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003135 return false;
3136}
3137
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003138/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003139/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003140CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003141 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003143 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003144 if (sz.isPositive() && type->isIntegralType())
3145 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003146 // Treat arrays as pointers, since that's how they're passed in.
3147 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003148 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003149 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003150}
3151
3152static inline
3153std::string charUnitsToString(const CharUnits &CU) {
3154 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003155}
3156
David Chisnall5e530af2009-11-17 19:33:30 +00003157/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3158/// declaration.
3159void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3160 std::string& S) {
3161 const BlockDecl *Decl = Expr->getBlockDecl();
3162 QualType BlockTy =
3163 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3164 // Encode result type.
3165 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3166 // Compute size of all parameters.
3167 // Start with computing size of a pointer in number of bytes.
3168 // FIXME: There might(should) be a better way of doing this computation!
3169 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003170 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3171 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003172 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3173 E = Decl->param_end(); PI != E; ++PI) {
3174 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003175 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003176 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003177 ParmOffset += sz;
3178 }
3179 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003180 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003181 // Block pointer and offset.
3182 S += "@?0";
3183 ParmOffset = PtrSize;
3184
3185 // Argument types.
3186 ParmOffset = PtrSize;
3187 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3188 Decl->param_end(); PI != E; ++PI) {
3189 ParmVarDecl *PVDecl = *PI;
3190 QualType PType = PVDecl->getOriginalType();
3191 if (const ArrayType *AT =
3192 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3193 // Use array's original type only if it has known number of
3194 // elements.
3195 if (!isa<ConstantArrayType>(AT))
3196 PType = PVDecl->getType();
3197 } else if (PType->isFunctionType())
3198 PType = PVDecl->getType();
3199 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003200 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003201 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003202 }
3203}
3204
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003205/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003206/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003207void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003208 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003209 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003210 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003211 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003212 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003213 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003214 // Compute size of all parameters.
3215 // Start with computing size of a pointer in number of bytes.
3216 // FIXME: There might(should) be a better way of doing this computation!
3217 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003218 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003219 // The first two arguments (self and _cmd) are pointers; account for
3220 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003221 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003222 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3223 E = Decl->param_end(); PI != E; ++PI) {
3224 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003225 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003226 assert (sz.isPositive() &&
3227 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003228 ParmOffset += sz;
3229 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003230 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003231 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003232 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003234 // Argument types.
3235 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003236 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3237 E = Decl->param_end(); PI != E; ++PI) {
3238 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003239 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003240 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003241 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3242 // Use array's original type only if it has known number of
3243 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003244 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003245 PType = PVDecl->getType();
3246 } else if (PType->isFunctionType())
3247 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003248 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003249 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003250 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003251 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003252 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003253 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003254 }
3255}
3256
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003257/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003258/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003259/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3260/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003261/// Property attributes are stored as a comma-delimited C string. The simple
3262/// attributes readonly and bycopy are encoded as single characters. The
3263/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3264/// encoded as single characters, followed by an identifier. Property types
3265/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003266/// these attributes are defined by the following enumeration:
3267/// @code
3268/// enum PropertyAttributes {
3269/// kPropertyReadOnly = 'R', // property is read-only.
3270/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3271/// kPropertyByref = '&', // property is a reference to the value last assigned
3272/// kPropertyDynamic = 'D', // property is dynamic
3273/// kPropertyGetter = 'G', // followed by getter selector name
3274/// kPropertySetter = 'S', // followed by setter selector name
3275/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3276/// kPropertyType = 't' // followed by old-style type encoding.
3277/// kPropertyWeak = 'W' // 'weak' property
3278/// kPropertyStrong = 'P' // property GC'able
3279/// kPropertyNonAtomic = 'N' // property non-atomic
3280/// };
3281/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003282void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003283 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003284 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003285 // Collect information from the property implementation decl(s).
3286 bool Dynamic = false;
3287 ObjCPropertyImplDecl *SynthesizePID = 0;
3288
3289 // FIXME: Duplicated code due to poor abstraction.
3290 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003291 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003292 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3293 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003294 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003295 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003296 ObjCPropertyImplDecl *PID = *i;
3297 if (PID->getPropertyDecl() == PD) {
3298 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3299 Dynamic = true;
3300 } else {
3301 SynthesizePID = PID;
3302 }
3303 }
3304 }
3305 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003306 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003307 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003308 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003309 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003310 ObjCPropertyImplDecl *PID = *i;
3311 if (PID->getPropertyDecl() == PD) {
3312 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3313 Dynamic = true;
3314 } else {
3315 SynthesizePID = PID;
3316 }
3317 }
Mike Stump1eb44332009-09-09 15:08:12 +00003318 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003319 }
3320 }
3321
3322 // FIXME: This is not very efficient.
3323 S = "T";
3324
3325 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003326 // GCC has some special rules regarding encoding of properties which
3327 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003328 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003329 true /* outermost type */,
3330 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003331
3332 if (PD->isReadOnly()) {
3333 S += ",R";
3334 } else {
3335 switch (PD->getSetterKind()) {
3336 case ObjCPropertyDecl::Assign: break;
3337 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003338 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003339 }
3340 }
3341
3342 // It really isn't clear at all what this means, since properties
3343 // are "dynamic by default".
3344 if (Dynamic)
3345 S += ",D";
3346
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003347 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3348 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003350 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3351 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003352 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003353 }
3354
3355 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3356 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003357 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003358 }
3359
3360 if (SynthesizePID) {
3361 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3362 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003363 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003364 }
3365
3366 // FIXME: OBJCGC: weak & strong
3367}
3368
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003369/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003370/// Another legacy compatibility encoding: 32-bit longs are encoded as
3371/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003372/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3373///
3374void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003375 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003376 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003377 if (BT->getKind() == BuiltinType::ULong &&
3378 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003379 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003380 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003381 if (BT->getKind() == BuiltinType::Long &&
3382 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003383 PointeeTy = IntTy;
3384 }
3385 }
3386}
3387
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003388void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003389 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003390 // We follow the behavior of gcc, expanding structures which are
3391 // directly pointed to, and expanding embedded structures. Note that
3392 // these rules are sufficient to prevent recursive encoding of the
3393 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003394 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003395 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003396}
3397
Mike Stump1eb44332009-09-09 15:08:12 +00003398static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003399 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003400 const Expr *E = FD->getBitWidth();
3401 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3402 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003403 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003404 S += 'b';
3405 S += llvm::utostr(N);
3406}
3407
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003408// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003409void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3410 bool ExpandPointedToStructures,
3411 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003412 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003413 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003414 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003415 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003416 if (FD && FD->isBitField())
3417 return EncodeBitField(this, S, FD);
3418 char encoding;
3419 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003420 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003421 case BuiltinType::Void: encoding = 'v'; break;
3422 case BuiltinType::Bool: encoding = 'B'; break;
3423 case BuiltinType::Char_U:
3424 case BuiltinType::UChar: encoding = 'C'; break;
3425 case BuiltinType::UShort: encoding = 'S'; break;
3426 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003427 case BuiltinType::ULong:
3428 encoding =
3429 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003430 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003431 case BuiltinType::UInt128: encoding = 'T'; break;
3432 case BuiltinType::ULongLong: encoding = 'Q'; break;
3433 case BuiltinType::Char_S:
3434 case BuiltinType::SChar: encoding = 'c'; break;
3435 case BuiltinType::Short: encoding = 's'; break;
3436 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003437 case BuiltinType::Long:
3438 encoding =
3439 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003440 break;
3441 case BuiltinType::LongLong: encoding = 'q'; break;
3442 case BuiltinType::Int128: encoding = 't'; break;
3443 case BuiltinType::Float: encoding = 'f'; break;
3444 case BuiltinType::Double: encoding = 'd'; break;
3445 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003446 }
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003448 S += encoding;
3449 return;
3450 }
Mike Stump1eb44332009-09-09 15:08:12 +00003451
John McCall183700f2009-09-21 23:43:11 +00003452 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003453 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003454 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003455 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003456 return;
3457 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003458
Ted Kremenek6217b802009-07-29 21:53:49 +00003459 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003460 if (PT->isObjCSelType()) {
3461 S += ':';
3462 return;
3463 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003464 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003465
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003466 bool isReadOnly = false;
3467 // For historical/compatibility reasons, the read-only qualifier of the
3468 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3469 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003470 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003471 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003472 if (OutermostType && T.isConstQualified()) {
3473 isReadOnly = true;
3474 S += 'r';
3475 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003476 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003477 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003478 while (P->getAs<PointerType>())
3479 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003480 if (P.isConstQualified()) {
3481 isReadOnly = true;
3482 S += 'r';
3483 }
3484 }
3485 if (isReadOnly) {
3486 // Another legacy compatibility encoding. Some ObjC qualifier and type
3487 // combinations need to be rearranged.
3488 // Rewrite "in const" from "nr" to "rn"
3489 const char * s = S.c_str();
3490 int len = S.length();
3491 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3492 std::string replace = "rn";
3493 S.replace(S.end()-2, S.end(), replace);
3494 }
3495 }
Mike Stump1eb44332009-09-09 15:08:12 +00003496
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003497 if (PointeeTy->isCharType()) {
3498 // char pointer types should be encoded as '*' unless it is a
3499 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003500 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003501 S += '*';
3502 return;
3503 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003504 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003505 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3506 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3507 S += '#';
3508 return;
3509 }
3510 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3511 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3512 S += '@';
3513 return;
3514 }
3515 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003516 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003517 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003518 getLegacyIntegralTypeEncoding(PointeeTy);
3519
Mike Stump1eb44332009-09-09 15:08:12 +00003520 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003521 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003522 return;
3523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003525 if (const ArrayType *AT =
3526 // Ignore type qualifiers etc.
3527 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003528 if (isa<IncompleteArrayType>(AT)) {
3529 // Incomplete arrays are encoded as a pointer to the array element.
3530 S += '^';
3531
Mike Stump1eb44332009-09-09 15:08:12 +00003532 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003533 false, ExpandStructures, FD);
3534 } else {
3535 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Anders Carlsson559a8332009-02-22 01:38:57 +00003537 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3538 S += llvm::utostr(CAT->getSize().getZExtValue());
3539 else {
3540 //Variable length arrays are encoded as a regular array with 0 elements.
3541 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3542 S += '0';
3543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
3545 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003546 false, ExpandStructures, FD);
3547 S += ']';
3548 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003549 return;
3550 }
Mike Stump1eb44332009-09-09 15:08:12 +00003551
John McCall183700f2009-09-21 23:43:11 +00003552 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003553 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003554 return;
3555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Ted Kremenek6217b802009-07-29 21:53:49 +00003557 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003558 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003559 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003560 // Anonymous structures print as '?'
3561 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3562 S += II->getName();
3563 } else {
3564 S += '?';
3565 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003566 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003567 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003568 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3569 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003570 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003571 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003572 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003573 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003574 S += '"';
3575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003577 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003578 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003579 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003580 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003581 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003582 QualType qt = Field->getType();
3583 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003584 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003585 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003586 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003587 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003588 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003589 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003590 return;
3591 }
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003593 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003594 if (FD && FD->isBitField())
3595 EncodeBitField(this, S, FD);
3596 else
3597 S += 'i';
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 (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003602 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003603 return;
3604 }
Mike Stump1eb44332009-09-09 15:08:12 +00003605
John McCall0953e762009-09-24 19:53:00 +00003606 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003607 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003608 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003609 S += '{';
3610 const IdentifierInfo *II = OI->getIdentifier();
3611 S += II->getName();
3612 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003613 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003614 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003615 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003616 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003617 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003618 RecFields[i]);
3619 else
Mike Stump1eb44332009-09-09 15:08:12 +00003620 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003621 FD);
3622 }
3623 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003624 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003625 }
Mike Stump1eb44332009-09-09 15:08:12 +00003626
John McCall183700f2009-09-21 23:43:11 +00003627 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003628 if (OPT->isObjCIdType()) {
3629 S += '@';
3630 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Steve Naroff27d20a22009-10-28 22:03:49 +00003633 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3634 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3635 // Since this is a binary compatibility issue, need to consult with runtime
3636 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003637 S += '#';
3638 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003641 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003642 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003643 ExpandPointedToStructures,
3644 ExpandStructures, FD);
3645 if (FD || EncodingProperty) {
3646 // Note that we do extended encoding of protocol qualifer list
3647 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003648 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003649 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3650 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003651 S += '<';
3652 S += (*I)->getNameAsString();
3653 S += '>';
3654 }
3655 S += '"';
3656 }
3657 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003658 }
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003660 QualType PointeeTy = OPT->getPointeeType();
3661 if (!EncodingProperty &&
3662 isa<TypedefType>(PointeeTy.getTypePtr())) {
3663 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003664 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003665 // {...};
3666 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003667 getObjCEncodingForTypeImpl(PointeeTy, S,
3668 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003669 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003670 return;
3671 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003672
3673 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003674 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003675 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003676 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003677 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3678 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003679 S += '<';
3680 S += (*I)->getNameAsString();
3681 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003682 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003683 S += '"';
3684 }
3685 return;
3686 }
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003688 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003689}
3690
Mike Stump1eb44332009-09-09 15:08:12 +00003691void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003692 std::string& S) const {
3693 if (QT & Decl::OBJC_TQ_In)
3694 S += 'n';
3695 if (QT & Decl::OBJC_TQ_Inout)
3696 S += 'N';
3697 if (QT & Decl::OBJC_TQ_Out)
3698 S += 'o';
3699 if (QT & Decl::OBJC_TQ_Bycopy)
3700 S += 'O';
3701 if (QT & Decl::OBJC_TQ_Byref)
3702 S += 'R';
3703 if (QT & Decl::OBJC_TQ_Oneway)
3704 S += 'V';
3705}
3706
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003707void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003708 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003710 BuiltinVaListType = T;
3711}
3712
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003713void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003714 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003715}
3716
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003717void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003718 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003719}
3720
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003721void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003722 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003723}
3724
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003725void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003726 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003727}
3728
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003729void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003730 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003731 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003733 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003734}
3735
John McCall0bd6feb2009-12-02 08:04:21 +00003736/// \brief Retrieve the template name that corresponds to a non-empty
3737/// lookup.
3738TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3739 NamedDecl * const *End) {
3740 unsigned size = End - Begin;
3741 assert(size > 1 && "set is not overloaded!");
3742
3743 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3744 size * sizeof(FunctionTemplateDecl*));
3745 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3746
3747 NamedDecl **Storage = OT->getStorage();
3748 for (NamedDecl * const *I = Begin; I != End; ++I) {
3749 NamedDecl *D = *I;
3750 assert(isa<FunctionTemplateDecl>(D) ||
3751 (isa<UsingShadowDecl>(D) &&
3752 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3753 *Storage++ = D;
3754 }
3755
3756 return TemplateName(OT);
3757}
3758
Douglas Gregor7532dc62009-03-30 22:58:21 +00003759/// \brief Retrieve the template name that represents a qualified
3760/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003761TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003762 bool TemplateKeyword,
3763 TemplateDecl *Template) {
3764 llvm::FoldingSetNodeID ID;
3765 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3766
3767 void *InsertPos = 0;
3768 QualifiedTemplateName *QTN =
3769 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3770 if (!QTN) {
3771 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3772 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3773 }
3774
3775 return TemplateName(QTN);
3776}
3777
3778/// \brief Retrieve the template name that represents a dependent
3779/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003780TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003781 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003782 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003783 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003784
3785 llvm::FoldingSetNodeID ID;
3786 DependentTemplateName::Profile(ID, NNS, Name);
3787
3788 void *InsertPos = 0;
3789 DependentTemplateName *QTN =
3790 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3791
3792 if (QTN)
3793 return TemplateName(QTN);
3794
3795 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3796 if (CanonNNS == NNS) {
3797 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3798 } else {
3799 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3800 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3801 }
3802
3803 DependentTemplateNames.InsertNode(QTN, InsertPos);
3804 return TemplateName(QTN);
3805}
3806
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003807/// \brief Retrieve the template name that represents a dependent
3808/// template name such as \c MetaFun::template operator+.
3809TemplateName
3810ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3811 OverloadedOperatorKind Operator) {
3812 assert((!NNS || NNS->isDependent()) &&
3813 "Nested name specifier must be dependent");
3814
3815 llvm::FoldingSetNodeID ID;
3816 DependentTemplateName::Profile(ID, NNS, Operator);
3817
3818 void *InsertPos = 0;
3819 DependentTemplateName *QTN =
3820 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3821
3822 if (QTN)
3823 return TemplateName(QTN);
3824
3825 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3826 if (CanonNNS == NNS) {
3827 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3828 } else {
3829 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3830 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3831 }
3832
3833 DependentTemplateNames.InsertNode(QTN, InsertPos);
3834 return TemplateName(QTN);
3835}
3836
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003837/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003838/// TargetInfo, produce the corresponding type. The unsigned @p Type
3839/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003840CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003841 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003842 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003843 case TargetInfo::SignedShort: return ShortTy;
3844 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3845 case TargetInfo::SignedInt: return IntTy;
3846 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3847 case TargetInfo::SignedLong: return LongTy;
3848 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3849 case TargetInfo::SignedLongLong: return LongLongTy;
3850 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3851 }
3852
3853 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003854 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003855}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003856
3857//===----------------------------------------------------------------------===//
3858// Type Predicates.
3859//===----------------------------------------------------------------------===//
3860
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003861/// isObjCNSObjectType - Return true if this is an NSObject object using
3862/// NSObject attribute on a c-style pointer type.
3863/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003864/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003865///
3866bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3867 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3868 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003869 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003870 return true;
3871 }
Mike Stump1eb44332009-09-09 15:08:12 +00003872 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003873}
3874
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003875/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3876/// garbage collection attribute.
3877///
John McCall0953e762009-09-24 19:53:00 +00003878Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3879 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003880 if (getLangOptions().ObjC1 &&
3881 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003882 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003883 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003884 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003885 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003886 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003887 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003888 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003889 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003890 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003891 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003892 // Non-pointers have none gc'able attribute regardless of the attribute
3893 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003894 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003895 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003896 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003897 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003898}
3899
Chris Lattner6ac46a42008-04-07 06:51:04 +00003900//===----------------------------------------------------------------------===//
3901// Type Compatibility Testing
3902//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003903
Mike Stump1eb44332009-09-09 15:08:12 +00003904/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003905/// compatible.
3906static bool areCompatVectorTypes(const VectorType *LHS,
3907 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003908 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003909 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003910 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003911}
3912
Steve Naroff4084c302009-07-23 01:01:38 +00003913//===----------------------------------------------------------------------===//
3914// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3915//===----------------------------------------------------------------------===//
3916
3917/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3918/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003919bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3920 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003921 if (lProto == rProto)
3922 return true;
3923 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3924 E = rProto->protocol_end(); PI != E; ++PI)
3925 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3926 return true;
3927 return false;
3928}
3929
Steve Naroff4084c302009-07-23 01:01:38 +00003930/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3931/// return true if lhs's protocols conform to rhs's protocol; false
3932/// otherwise.
3933bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3934 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3935 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3936 return false;
3937}
3938
3939/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3940/// ObjCQualifiedIDType.
3941bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3942 bool compare) {
3943 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003944 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003945 lhs->isObjCIdType() || lhs->isObjCClassType())
3946 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003947 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003948 rhs->isObjCIdType() || rhs->isObjCClassType())
3949 return true;
3950
3951 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003952 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Steve Naroff4084c302009-07-23 01:01:38 +00003954 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Steve Naroff4084c302009-07-23 01:01:38 +00003956 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003957 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003958 // make sure we check the class hierarchy.
3959 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3960 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3961 E = lhsQID->qual_end(); I != E; ++I) {
3962 // when comparing an id<P> on lhs with a static type on rhs,
3963 // see if static class implements all of id's protocols, directly or
3964 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003965 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003966 return false;
3967 }
3968 }
3969 // If there are no qualifiers and no interface, we have an 'id'.
3970 return true;
3971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003973 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3974 E = lhsQID->qual_end(); I != E; ++I) {
3975 ObjCProtocolDecl *lhsProto = *I;
3976 bool match = false;
3977
3978 // when comparing an id<P> on lhs with a static type on rhs,
3979 // see if static class implements all of id's protocols, directly or
3980 // through its super class and categories.
3981 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3982 E = rhsOPT->qual_end(); J != E; ++J) {
3983 ObjCProtocolDecl *rhsProto = *J;
3984 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3985 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3986 match = true;
3987 break;
3988 }
3989 }
Mike Stump1eb44332009-09-09 15:08:12 +00003990 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003991 // make sure we check the class hierarchy.
3992 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3993 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3994 E = lhsQID->qual_end(); I != E; ++I) {
3995 // when comparing an id<P> on lhs with a static type on rhs,
3996 // see if static class implements all of id's protocols, directly or
3997 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003998 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003999 match = true;
4000 break;
4001 }
4002 }
4003 }
4004 if (!match)
4005 return false;
4006 }
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Steve Naroff4084c302009-07-23 01:01:38 +00004008 return true;
4009 }
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Steve Naroff4084c302009-07-23 01:01:38 +00004011 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4012 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4013
Mike Stump1eb44332009-09-09 15:08:12 +00004014 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004015 lhs->getAsObjCInterfacePointerType()) {
4016 if (lhsOPT->qual_empty()) {
4017 bool match = false;
4018 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4019 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4020 E = rhsQID->qual_end(); I != E; ++I) {
4021 // when comparing an id<P> on lhs with a static type on rhs,
4022 // see if static class implements all of id's protocols, directly or
4023 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004024 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004025 match = true;
4026 break;
4027 }
4028 }
4029 if (!match)
4030 return false;
4031 }
4032 return true;
4033 }
Mike Stump1eb44332009-09-09 15:08:12 +00004034 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004035 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4036 E = lhsOPT->qual_end(); I != E; ++I) {
4037 ObjCProtocolDecl *lhsProto = *I;
4038 bool match = false;
4039
4040 // when comparing an id<P> on lhs with a static type on rhs,
4041 // see if static class implements all of id's protocols, directly or
4042 // through its super class and categories.
4043 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4044 E = rhsQID->qual_end(); J != E; ++J) {
4045 ObjCProtocolDecl *rhsProto = *J;
4046 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4047 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4048 match = true;
4049 break;
4050 }
4051 }
4052 if (!match)
4053 return false;
4054 }
4055 return true;
4056 }
4057 return false;
4058}
4059
Eli Friedman3d815e72008-08-22 00:56:42 +00004060/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004061/// compatible for assignment from RHS to LHS. This handles validation of any
4062/// protocol qualifiers on the LHS or RHS.
4063///
Steve Naroff14108da2009-07-10 23:34:53 +00004064bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4065 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004066 // If either type represents the built-in 'id' or 'Class' types, return true.
4067 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004068 return true;
4069
Steve Naroff4084c302009-07-23 01:01:38 +00004070 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004071 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4072 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004073 false);
4074
Steve Naroff14108da2009-07-10 23:34:53 +00004075 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4076 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004077 if (LHS && RHS) // We have 2 user-defined types.
4078 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004079
Steve Naroff4084c302009-07-23 01:01:38 +00004080 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004081}
4082
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004083/// getIntersectionOfProtocols - This routine finds the intersection of set
4084/// of protocols inherited from two distinct objective-c pointer objects.
4085/// It is used to build composite qualifier list of the composite type of
4086/// the conditional expression involving two objective-c pointer objects.
4087static
4088void getIntersectionOfProtocols(ASTContext &Context,
4089 const ObjCObjectPointerType *LHSOPT,
4090 const ObjCObjectPointerType *RHSOPT,
4091 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4092
4093 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4094 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4095
4096 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4097 unsigned LHSNumProtocols = LHS->getNumProtocols();
4098 if (LHSNumProtocols > 0)
4099 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4100 else {
4101 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4102 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4103 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4104 LHSInheritedProtocols.end());
4105 }
4106
4107 unsigned RHSNumProtocols = RHS->getNumProtocols();
4108 if (RHSNumProtocols > 0) {
4109 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4110 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4111 if (InheritedProtocolSet.count(RHSProtocols[i]))
4112 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4113 }
4114 else {
4115 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4116 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4117 // FIXME. This may cause duplication of protocols in the list, but should
4118 // be harmless.
4119 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4120 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4121 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4122 }
4123}
4124
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004125/// areCommonBaseCompatible - Returns common base class of the two classes if
4126/// one found. Note that this is O'2 algorithm. But it will be called as the
4127/// last type comparison in a ?-exp of ObjC pointer types before a
4128/// warning is issued. So, its invokation is extremely rare.
4129QualType ASTContext::areCommonBaseCompatible(
4130 const ObjCObjectPointerType *LHSOPT,
4131 const ObjCObjectPointerType *RHSOPT) {
4132 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4133 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4134 if (!LHS || !RHS)
4135 return QualType();
4136
4137 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4138 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4139 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004140 if (canAssignObjCInterfaces(LHS, RHS)) {
4141 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4142 getIntersectionOfProtocols(*this,
4143 LHSOPT, RHSOPT, IntersectionOfProtocols);
4144 if (IntersectionOfProtocols.empty())
4145 LHSTy = getObjCObjectPointerType(LHSTy);
4146 else
4147 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4148 IntersectionOfProtocols.size());
4149 return LHSTy;
4150 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004151 }
4152
4153 return QualType();
4154}
4155
Eli Friedman3d815e72008-08-22 00:56:42 +00004156bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4157 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004158 // Verify that the base decls are compatible: the RHS must be a subclass of
4159 // the LHS.
4160 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4161 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Chris Lattner6ac46a42008-04-07 06:51:04 +00004163 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4164 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004165 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004166 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Chris Lattner6ac46a42008-04-07 06:51:04 +00004168 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4169 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004170 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004171 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004172
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004173 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4174 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004175 LHSPI != LHSPE; LHSPI++) {
4176 bool RHSImplementsProtocol = false;
4177
4178 // If the RHS doesn't implement the protocol on the left, the types
4179 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004180 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004181 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004182 RHSPI != RHSPE; RHSPI++) {
4183 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004184 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004185 break;
4186 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004187 }
4188 // FIXME: For better diagnostics, consider passing back the protocol name.
4189 if (!RHSImplementsProtocol)
4190 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004191 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004192 // The RHS implements all protocols listed on the LHS.
4193 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004194}
4195
Steve Naroff389bf462009-02-12 17:52:19 +00004196bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4197 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004198 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4199 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004200
Steve Naroff14108da2009-07-10 23:34:53 +00004201 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004202 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004203
4204 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4205 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004206}
4207
Mike Stump1eb44332009-09-09 15:08:12 +00004208/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004209/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004210/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004211/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004212bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4213 return !mergeTypes(LHS, RHS).isNull();
4214}
4215
4216QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004217 const FunctionType *lbase = lhs->getAs<FunctionType>();
4218 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004219 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4220 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004221 bool allLTypes = true;
4222 bool allRTypes = true;
4223
4224 // Check return type
4225 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4226 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004227 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4228 allLTypes = false;
4229 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4230 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004231 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004232 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4233 if (NoReturn != lbase->getNoReturnAttr())
4234 allLTypes = false;
4235 if (NoReturn != rbase->getNoReturnAttr())
4236 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Eli Friedman3d815e72008-08-22 00:56:42 +00004238 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004239 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4240 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004241 unsigned lproto_nargs = lproto->getNumArgs();
4242 unsigned rproto_nargs = rproto->getNumArgs();
4243
4244 // Compatible functions must have the same number of arguments
4245 if (lproto_nargs != rproto_nargs)
4246 return QualType();
4247
4248 // Variadic and non-variadic functions aren't compatible
4249 if (lproto->isVariadic() != rproto->isVariadic())
4250 return QualType();
4251
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004252 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4253 return QualType();
4254
Eli Friedman3d815e72008-08-22 00:56:42 +00004255 // Check argument compatibility
4256 llvm::SmallVector<QualType, 10> types;
4257 for (unsigned i = 0; i < lproto_nargs; i++) {
4258 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4259 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4260 QualType argtype = mergeTypes(largtype, rargtype);
4261 if (argtype.isNull()) return QualType();
4262 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004263 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4264 allLTypes = false;
4265 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4266 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004267 }
4268 if (allLTypes) return lhs;
4269 if (allRTypes) return rhs;
4270 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004271 lproto->isVariadic(), lproto->getTypeQuals(),
4272 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004273 }
4274
4275 if (lproto) allRTypes = false;
4276 if (rproto) allLTypes = false;
4277
Douglas Gregor72564e72009-02-26 23:50:07 +00004278 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004279 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004280 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004281 if (proto->isVariadic()) return QualType();
4282 // Check that the types are compatible with the types that
4283 // would result from default argument promotions (C99 6.7.5.3p15).
4284 // The only types actually affected are promotable integer
4285 // types and floats, which would be passed as a different
4286 // type depending on whether the prototype is visible.
4287 unsigned proto_nargs = proto->getNumArgs();
4288 for (unsigned i = 0; i < proto_nargs; ++i) {
4289 QualType argTy = proto->getArgType(i);
4290 if (argTy->isPromotableIntegerType() ||
4291 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4292 return QualType();
4293 }
4294
4295 if (allLTypes) return lhs;
4296 if (allRTypes) return rhs;
4297 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004298 proto->getNumArgs(), proto->isVariadic(),
4299 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004300 }
4301
4302 if (allLTypes) return lhs;
4303 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004304 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004305}
4306
4307QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004308 // C++ [expr]: If an expression initially has the type "reference to T", the
4309 // type is adjusted to "T" prior to any further analysis, the expression
4310 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004311 // expression is an lvalue unless the reference is an rvalue reference and
4312 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004313 // FIXME: C++ shouldn't be going through here! The rules are different
4314 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004315 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4316 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004317 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004318 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004319 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004320 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004321
Eli Friedman3d815e72008-08-22 00:56:42 +00004322 QualType LHSCan = getCanonicalType(LHS),
4323 RHSCan = getCanonicalType(RHS);
4324
4325 // If two types are identical, they are compatible.
4326 if (LHSCan == RHSCan)
4327 return LHS;
4328
John McCall0953e762009-09-24 19:53:00 +00004329 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004330 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4331 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004332 if (LQuals != RQuals) {
4333 // If any of these qualifiers are different, we have a type
4334 // mismatch.
4335 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4336 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4337 return QualType();
4338
4339 // Exactly one GC qualifier difference is allowed: __strong is
4340 // okay if the other type has no GC qualifier but is an Objective
4341 // C object pointer (i.e. implicitly strong by default). We fix
4342 // this by pretending that the unqualified type was actually
4343 // qualified __strong.
4344 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4345 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4346 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4347
4348 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4349 return QualType();
4350
4351 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4352 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4353 }
4354 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4355 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4356 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004357 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004358 }
4359
4360 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004361
Eli Friedman852d63b2009-06-01 01:22:52 +00004362 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4363 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004364
Chris Lattner1adb8832008-01-14 05:45:46 +00004365 // We want to consider the two function types to be the same for these
4366 // comparisons, just force one to the other.
4367 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4368 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004369
4370 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004371 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4372 LHSClass = Type::ConstantArray;
4373 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4374 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Nate Begeman213541a2008-04-18 23:10:10 +00004376 // Canonicalize ExtVector -> Vector.
4377 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4378 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Chris Lattnera36a61f2008-04-07 05:43:21 +00004380 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004381 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004382 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004383 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004384 // Compatibility is based on the underlying type, not the promotion
4385 // type.
John McCall183700f2009-09-21 23:43:11 +00004386 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004387 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4388 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004389 }
John McCall183700f2009-09-21 23:43:11 +00004390 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004391 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4392 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004393 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004394
Eli Friedman3d815e72008-08-22 00:56:42 +00004395 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004396 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004397
Steve Naroff4a746782008-01-09 22:43:08 +00004398 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004399 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004400#define TYPE(Class, Base)
4401#define ABSTRACT_TYPE(Class, Base)
4402#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4403#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4404#include "clang/AST/TypeNodes.def"
4405 assert(false && "Non-canonical and dependent types shouldn't get here");
4406 return QualType();
4407
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004408 case Type::LValueReference:
4409 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004410 case Type::MemberPointer:
4411 assert(false && "C++ should never be in mergeTypes");
4412 return QualType();
4413
4414 case Type::IncompleteArray:
4415 case Type::VariableArray:
4416 case Type::FunctionProto:
4417 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004418 assert(false && "Types are eliminated above");
4419 return QualType();
4420
Chris Lattner1adb8832008-01-14 05:45:46 +00004421 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004422 {
4423 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004424 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4425 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004426 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4427 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004428 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004429 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004430 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004431 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004432 return getPointerType(ResultType);
4433 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004434 case Type::BlockPointer:
4435 {
4436 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004437 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4438 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004439 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4440 if (ResultType.isNull()) return QualType();
4441 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4442 return LHS;
4443 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4444 return RHS;
4445 return getBlockPointerType(ResultType);
4446 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004447 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004448 {
4449 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4450 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4451 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4452 return QualType();
4453
4454 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4455 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4456 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4457 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004458 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4459 return LHS;
4460 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4461 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004462 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4463 ArrayType::ArraySizeModifier(), 0);
4464 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4465 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004466 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4467 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004468 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4469 return LHS;
4470 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4471 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004472 if (LVAT) {
4473 // FIXME: This isn't correct! But tricky to implement because
4474 // the array's size has to be the size of LHS, but the type
4475 // has to be different.
4476 return LHS;
4477 }
4478 if (RVAT) {
4479 // FIXME: This isn't correct! But tricky to implement because
4480 // the array's size has to be the size of RHS, but the type
4481 // has to be different.
4482 return RHS;
4483 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004484 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4485 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004486 return getIncompleteArrayType(ResultType,
4487 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004488 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004489 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004490 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004491 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004492 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004493 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004494 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004495 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004496 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004497 case Type::Complex:
4498 // Distinct complex types are incompatible.
4499 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004500 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004501 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004502 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004503 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004504 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004505 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004506 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004507 // FIXME: This should be type compatibility, e.g. whether
4508 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004509 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4510 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004511 if (LHSIface && RHSIface &&
4512 canAssignObjCInterfaces(LHSIface, RHSIface))
4513 return LHS;
4514
Eli Friedman3d815e72008-08-22 00:56:42 +00004515 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004516 }
Steve Naroff14108da2009-07-10 23:34:53 +00004517 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004518 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4519 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004520 return LHS;
4521
Steve Naroffbc76dd02008-12-10 22:14:21 +00004522 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004523 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00004524 case Type::TemplateSpecialization:
4525 assert(false && "Dependent types have no size");
4526 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004527 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004528
4529 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004530}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004531
Chris Lattner5426bf62008-04-07 07:01:58 +00004532//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004533// Integer Predicates
4534//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004535
Eli Friedmanad74a752008-06-28 06:23:08 +00004536unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004537 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004538 return 1;
John McCall842aef82009-12-09 09:09:27 +00004539 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004540 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004541 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004542 return (unsigned)getTypeSize(T);
4543}
4544
4545QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4546 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004547
4548 // Turn <4 x signed int> -> <4 x unsigned int>
4549 if (const VectorType *VTy = T->getAs<VectorType>())
4550 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4551 VTy->getNumElements());
4552
4553 // For enums, we return the unsigned version of the base type.
4554 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004555 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004556
4557 const BuiltinType *BTy = T->getAs<BuiltinType>();
4558 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004559 switch (BTy->getKind()) {
4560 case BuiltinType::Char_S:
4561 case BuiltinType::SChar:
4562 return UnsignedCharTy;
4563 case BuiltinType::Short:
4564 return UnsignedShortTy;
4565 case BuiltinType::Int:
4566 return UnsignedIntTy;
4567 case BuiltinType::Long:
4568 return UnsignedLongTy;
4569 case BuiltinType::LongLong:
4570 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004571 case BuiltinType::Int128:
4572 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004573 default:
4574 assert(0 && "Unexpected signed integer type");
4575 return QualType();
4576 }
4577}
4578
Douglas Gregor2cf26342009-04-09 22:27:44 +00004579ExternalASTSource::~ExternalASTSource() { }
4580
4581void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004582
4583
4584//===----------------------------------------------------------------------===//
4585// Builtin Type Computation
4586//===----------------------------------------------------------------------===//
4587
4588/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4589/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004590static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004591 ASTContext::GetBuiltinTypeError &Error,
4592 bool AllowTypeModifiers = true) {
4593 // Modifiers.
4594 int HowLong = 0;
4595 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004596
Chris Lattner86df27b2009-06-14 00:45:47 +00004597 // Read the modifiers first.
4598 bool Done = false;
4599 while (!Done) {
4600 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004601 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004602 case 'S':
4603 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4604 assert(!Signed && "Can't use 'S' modifier multiple times!");
4605 Signed = true;
4606 break;
4607 case 'U':
4608 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4609 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4610 Unsigned = true;
4611 break;
4612 case 'L':
4613 assert(HowLong <= 2 && "Can't have LLLL modifier");
4614 ++HowLong;
4615 break;
4616 }
4617 }
4618
4619 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Chris Lattner86df27b2009-06-14 00:45:47 +00004621 // Read the base type.
4622 switch (*Str++) {
4623 default: assert(0 && "Unknown builtin type letter!");
4624 case 'v':
4625 assert(HowLong == 0 && !Signed && !Unsigned &&
4626 "Bad modifiers used with 'v'!");
4627 Type = Context.VoidTy;
4628 break;
4629 case 'f':
4630 assert(HowLong == 0 && !Signed && !Unsigned &&
4631 "Bad modifiers used with 'f'!");
4632 Type = Context.FloatTy;
4633 break;
4634 case 'd':
4635 assert(HowLong < 2 && !Signed && !Unsigned &&
4636 "Bad modifiers used with 'd'!");
4637 if (HowLong)
4638 Type = Context.LongDoubleTy;
4639 else
4640 Type = Context.DoubleTy;
4641 break;
4642 case 's':
4643 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4644 if (Unsigned)
4645 Type = Context.UnsignedShortTy;
4646 else
4647 Type = Context.ShortTy;
4648 break;
4649 case 'i':
4650 if (HowLong == 3)
4651 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4652 else if (HowLong == 2)
4653 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4654 else if (HowLong == 1)
4655 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4656 else
4657 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4658 break;
4659 case 'c':
4660 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4661 if (Signed)
4662 Type = Context.SignedCharTy;
4663 else if (Unsigned)
4664 Type = Context.UnsignedCharTy;
4665 else
4666 Type = Context.CharTy;
4667 break;
4668 case 'b': // boolean
4669 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4670 Type = Context.BoolTy;
4671 break;
4672 case 'z': // size_t.
4673 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4674 Type = Context.getSizeType();
4675 break;
4676 case 'F':
4677 Type = Context.getCFConstantStringType();
4678 break;
4679 case 'a':
4680 Type = Context.getBuiltinVaListType();
4681 assert(!Type.isNull() && "builtin va list type not initialized!");
4682 break;
4683 case 'A':
4684 // This is a "reference" to a va_list; however, what exactly
4685 // this means depends on how va_list is defined. There are two
4686 // different kinds of va_list: ones passed by value, and ones
4687 // passed by reference. An example of a by-value va_list is
4688 // x86, where va_list is a char*. An example of by-ref va_list
4689 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4690 // we want this argument to be a char*&; for x86-64, we want
4691 // it to be a __va_list_tag*.
4692 Type = Context.getBuiltinVaListType();
4693 assert(!Type.isNull() && "builtin va list type not initialized!");
4694 if (Type->isArrayType()) {
4695 Type = Context.getArrayDecayedType(Type);
4696 } else {
4697 Type = Context.getLValueReferenceType(Type);
4698 }
4699 break;
4700 case 'V': {
4701 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004702 unsigned NumElements = strtoul(Str, &End, 10);
4703 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Chris Lattner86df27b2009-06-14 00:45:47 +00004705 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Chris Lattner86df27b2009-06-14 00:45:47 +00004707 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4708 Type = Context.getVectorType(ElementType, NumElements);
4709 break;
4710 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004711 case 'X': {
4712 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4713 Type = Context.getComplexType(ElementType);
4714 break;
4715 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004716 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004717 Type = Context.getFILEType();
4718 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004719 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004720 return QualType();
4721 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004722 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004723 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004724 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004725 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004726 else
4727 Type = Context.getjmp_bufType();
4728
Mike Stumpfd612db2009-07-28 23:47:15 +00004729 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004730 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004731 return QualType();
4732 }
4733 break;
Mike Stump782fa302009-07-28 02:25:19 +00004734 }
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Chris Lattner86df27b2009-06-14 00:45:47 +00004736 if (!AllowTypeModifiers)
4737 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Chris Lattner86df27b2009-06-14 00:45:47 +00004739 Done = false;
4740 while (!Done) {
4741 switch (*Str++) {
4742 default: Done = true; --Str; break;
4743 case '*':
4744 Type = Context.getPointerType(Type);
4745 break;
4746 case '&':
4747 Type = Context.getLValueReferenceType(Type);
4748 break;
4749 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4750 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004751 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004752 break;
4753 }
4754 }
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Chris Lattner86df27b2009-06-14 00:45:47 +00004756 return Type;
4757}
4758
4759/// GetBuiltinType - Return the type for the specified builtin.
4760QualType ASTContext::GetBuiltinType(unsigned id,
4761 GetBuiltinTypeError &Error) {
4762 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Chris Lattner86df27b2009-06-14 00:45:47 +00004764 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Chris Lattner86df27b2009-06-14 00:45:47 +00004766 Error = GE_None;
4767 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4768 if (Error != GE_None)
4769 return QualType();
4770 while (TypeStr[0] && TypeStr[0] != '.') {
4771 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4772 if (Error != GE_None)
4773 return QualType();
4774
4775 // Do array -> pointer decay. The builtin should use the decayed type.
4776 if (Ty->isArrayType())
4777 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004778
Chris Lattner86df27b2009-06-14 00:45:47 +00004779 ArgTypes.push_back(Ty);
4780 }
4781
4782 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4783 "'.' should only occur at end of builtin type list!");
4784
4785 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4786 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4787 return getFunctionNoProtoType(ResType);
4788 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4789 TypeStr[0] == '.', 0);
4790}
Eli Friedmana95d7572009-08-19 07:44:53 +00004791
4792QualType
4793ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4794 // Perform the usual unary conversions. We do this early so that
4795 // integral promotions to "int" can allow us to exit early, in the
4796 // lhs == rhs check. Also, for conversion purposes, we ignore any
4797 // qualifiers. For example, "const float" and "float" are
4798 // equivalent.
4799 if (lhs->isPromotableIntegerType())
4800 lhs = getPromotedIntegerType(lhs);
4801 else
4802 lhs = lhs.getUnqualifiedType();
4803 if (rhs->isPromotableIntegerType())
4804 rhs = getPromotedIntegerType(rhs);
4805 else
4806 rhs = rhs.getUnqualifiedType();
4807
4808 // If both types are identical, no conversion is needed.
4809 if (lhs == rhs)
4810 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Eli Friedmana95d7572009-08-19 07:44:53 +00004812 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4813 // The caller can deal with this (e.g. pointer + int).
4814 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4815 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004816
4817 // At this point, we have two different arithmetic types.
4818
Eli Friedmana95d7572009-08-19 07:44:53 +00004819 // Handle complex types first (C99 6.3.1.8p1).
4820 if (lhs->isComplexType() || rhs->isComplexType()) {
4821 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004822 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004823 // convert the rhs to the lhs complex type.
4824 return lhs;
4825 }
Mike Stump1eb44332009-09-09 15:08:12 +00004826 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004827 // convert the lhs to the rhs complex type.
4828 return rhs;
4829 }
4830 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004831 // When both operands are complex, the shorter operand is converted to the
4832 // type of the longer, and that is the type of the result. This corresponds
4833 // to what is done when combining two real floating-point operands.
4834 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004835 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004836 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004837 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004838 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004839 // "double _Complex" is promoted to "long double _Complex".
4840 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004841
4842 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004843 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004844 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004845 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004846 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004847 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4848 // domains match. This is a requirement for our implementation, C99
4849 // does not require this promotion.
4850 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4851 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4852 return rhs;
4853 } else { // handle "_Complex double, double".
4854 return lhs;
4855 }
4856 }
4857 return lhs; // The domain/size match exactly.
4858 }
4859 // Now handle "real" floating types (i.e. float, double, long double).
4860 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4861 // if we have an integer operand, the result is the real floating type.
4862 if (rhs->isIntegerType()) {
4863 // convert rhs to the lhs floating point type.
4864 return lhs;
4865 }
4866 if (rhs->isComplexIntegerType()) {
4867 // convert rhs to the complex floating point type.
4868 return getComplexType(lhs);
4869 }
4870 if (lhs->isIntegerType()) {
4871 // convert lhs to the rhs floating point type.
4872 return rhs;
4873 }
Mike Stump1eb44332009-09-09 15:08:12 +00004874 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004875 // convert lhs to the complex floating point type.
4876 return getComplexType(rhs);
4877 }
4878 // We have two real floating types, float/complex combos were handled above.
4879 // Convert the smaller operand to the bigger result.
4880 int result = getFloatingTypeOrder(lhs, rhs);
4881 if (result > 0) // convert the rhs
4882 return lhs;
4883 assert(result < 0 && "illegal float comparison");
4884 return rhs; // convert the lhs
4885 }
4886 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4887 // Handle GCC complex int extension.
4888 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4889 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4890
4891 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004892 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004893 rhsComplexInt->getElementType()) >= 0)
4894 return lhs; // convert the rhs
4895 return rhs;
4896 } else if (lhsComplexInt && rhs->isIntegerType()) {
4897 // convert the rhs to the lhs complex type.
4898 return lhs;
4899 } else if (rhsComplexInt && lhs->isIntegerType()) {
4900 // convert the lhs to the rhs complex type.
4901 return rhs;
4902 }
4903 }
4904 // Finally, we have two differing integer types.
4905 // The rules for this case are in C99 6.3.1.8
4906 int compare = getIntegerTypeOrder(lhs, rhs);
4907 bool lhsSigned = lhs->isSignedIntegerType(),
4908 rhsSigned = rhs->isSignedIntegerType();
4909 QualType destType;
4910 if (lhsSigned == rhsSigned) {
4911 // Same signedness; use the higher-ranked type
4912 destType = compare >= 0 ? lhs : rhs;
4913 } else if (compare != (lhsSigned ? 1 : -1)) {
4914 // The unsigned type has greater than or equal rank to the
4915 // signed type, so use the unsigned type
4916 destType = lhsSigned ? rhs : lhs;
4917 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4918 // The two types are different widths; if we are here, that
4919 // means the signed type is larger than the unsigned type, so
4920 // use the signed type.
4921 destType = lhsSigned ? lhs : rhs;
4922 } else {
4923 // The signed type is higher-ranked than the unsigned type,
4924 // but isn't actually any bigger (like unsigned int and long
4925 // on most 32-bit systems). Use the unsigned type corresponding
4926 // to the signed type.
4927 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4928 }
4929 return destType;
4930}