blob: 4af1599b94a8f8ba7bb9025fab11453326383eda [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"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner61710852008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000036 Builtin::Context &builtins,
37 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000038 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
39 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2cf26342009-04-09 22:27:44 +000040 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels),
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 BuiltinInfo(builtins), ExternalSource(0) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000042 if (size_reserve > 0) Types.reserve(size_reserve);
43 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000044 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregord249e1d1f2009-05-29 20:38:28 +000045 PrintingPolicy.CPlusPlus = LangOpts.CPlusPlus;
Daniel Dunbare91593e2008-08-11 04:54:23 +000046}
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048ASTContext::~ASTContext() {
49 // Deallocate all the types.
50 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000051 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000052 Types.pop_back();
53 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000054
Nuno Lopesb74668e2008-12-17 22:30:25 +000055 {
56 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
57 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
58 while (I != E) {
59 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
60 delete R;
61 }
62 }
63
64 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000065 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
66 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000067 while (I != E) {
68 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
69 delete R;
70 }
71 }
72
Douglas Gregorab452ba2009-03-26 23:50:42 +000073 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000074 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
75 NNS = NestedNameSpecifiers.begin(),
76 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000077 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000078 /* Increment in loop */)
79 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000080
81 if (GlobalNestedNameSpecifier)
82 GlobalNestedNameSpecifier->Destroy(*this);
83
Eli Friedmanb26153c2008-05-27 03:08:09 +000084 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
86
Douglas Gregor2cf26342009-04-09 22:27:44 +000087void
88ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
89 ExternalSource.reset(Source.take());
90}
91
Reid Spencer5f016e22007-07-11 17:01:13 +000092void ASTContext::PrintStats() const {
93 fprintf(stderr, "*** AST Context Stats:\n");
94 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000095
Douglas Gregordbe833d2009-05-26 14:40:08 +000096 unsigned counts[] = {
97#define TYPE(Name, Parent) 0,
98#define ABSTRACT_TYPE(Name, Parent)
99#include "clang/AST/TypeNodes.def"
100 0 // Extra
101 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
104 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000105 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 }
107
Douglas Gregordbe833d2009-05-26 14:40:08 +0000108 unsigned Idx = 0;
109 unsigned TotalBytes = 0;
110#define TYPE(Name, Parent) \
111 if (counts[Idx]) \
112 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
113 TotalBytes += counts[Idx] * sizeof(Name##Type); \
114 ++Idx;
115#define ABSTRACT_TYPE(Name, Parent)
116#include "clang/AST/TypeNodes.def"
117
118 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000119
120 if (ExternalSource.get()) {
121 fprintf(stderr, "\n");
122 ExternalSource->PrintStats();
123 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000124}
125
126
127void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000128 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
Reid Spencer5f016e22007-07-11 17:01:13 +0000131void ASTContext::InitBuiltinTypes() {
132 assert(VoidTy.isNull() && "Context reinitialized?");
133
134 // C99 6.2.5p19.
135 InitBuiltinType(VoidTy, BuiltinType::Void);
136
137 // C99 6.2.5p2.
138 InitBuiltinType(BoolTy, BuiltinType::Bool);
139 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000140 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 InitBuiltinType(CharTy, BuiltinType::Char_S);
142 else
143 InitBuiltinType(CharTy, BuiltinType::Char_U);
144 // C99 6.2.5p4.
145 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
146 InitBuiltinType(ShortTy, BuiltinType::Short);
147 InitBuiltinType(IntTy, BuiltinType::Int);
148 InitBuiltinType(LongTy, BuiltinType::Long);
149 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
150
151 // C99 6.2.5p6.
152 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
153 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
154 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
155 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
156 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
157
158 // C99 6.2.5p10.
159 InitBuiltinType(FloatTy, BuiltinType::Float);
160 InitBuiltinType(DoubleTy, BuiltinType::Double);
161 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000162
Chris Lattner2df9ced2009-04-30 02:43:43 +0000163 // GNU extension, 128-bit integers.
164 InitBuiltinType(Int128Ty, BuiltinType::Int128);
165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
166
Chris Lattner3a250322009-02-26 23:43:47 +0000167 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
168 InitBuiltinType(WCharTy, BuiltinType::WChar);
169 else // C99
170 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000171
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000173 InitBuiltinType(OverloadTy, BuiltinType::Overload);
174
175 // Placeholder type for type-dependent expressions whose type is
176 // completely unknown. No code should ever check a type against
177 // DependentTy and users should never see it; however, it is here to
178 // help diagnose failures to properly check for type-dependent
179 // expressions.
180 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000181
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 // C99 6.2.5p11.
183 FloatComplexTy = getComplexType(FloatTy);
184 DoubleComplexTy = getComplexType(DoubleTy);
185 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186
Steve Naroff7e219e42007-10-15 14:41:52 +0000187 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000188 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000189 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000191 ClassStructType = 0;
192
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000194
195 // void * type
196 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000197
198 // nullptr type (C++0x 2.14.7)
199 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200}
201
Chris Lattner464175b2007-07-18 17:52:12 +0000202//===----------------------------------------------------------------------===//
203// Type Sizing and Analysis
204//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000205
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000206/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
207/// scalar floating point type.
208const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
209 const BuiltinType *BT = T->getAsBuiltinType();
210 assert(BT && "Not a floating point type!");
211 switch (BT->getKind()) {
212 default: assert(0 && "Not a floating point type!");
213 case BuiltinType::Float: return Target.getFloatFormat();
214 case BuiltinType::Double: return Target.getDoubleFormat();
215 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
216 }
217}
218
Chris Lattneraf707ab2009-01-24 21:53:27 +0000219/// getDeclAlign - Return a conservative estimate of the alignment of the
220/// specified decl. Note that bitfields do not have a valid alignment, so
221/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000222unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000223 unsigned Align = Target.getCharWidth();
224
225 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
226 Align = std::max(Align, AA->getAlignment());
227
Chris Lattneraf707ab2009-01-24 21:53:27 +0000228 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
229 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000230 if (const ReferenceType* RT = T->getAsReferenceType()) {
231 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000232 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000233 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
234 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000235 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
236 T = cast<ArrayType>(T)->getElementType();
237
238 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
239 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000240 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000241
242 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000243}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000244
Chris Lattnera7674d82007-07-13 22:13:22 +0000245/// getTypeSize - Return the size of the specified type, in bits. This method
246/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000247std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000248ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000249 uint64_t Width=0;
250 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000251 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000252#define TYPE(Class, Base)
253#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000254#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000255#define DEPENDENT_TYPE(Class, Base) case Type::Class:
256#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000257 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000258 break;
259
Chris Lattner692233e2007-07-13 22:27:08 +0000260 case Type::FunctionNoProto:
261 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000262 // GCC extension: alignof(function) = 32 bits
263 Width = 0;
264 Align = 32;
265 break;
266
Douglas Gregor72564e72009-02-26 23:50:07 +0000267 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000268 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000269 Width = 0;
270 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
271 break;
272
Steve Narofffb22d962007-08-30 01:06:46 +0000273 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000274 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000275
Chris Lattner98be4942008-03-05 18:54:05 +0000276 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000277 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000278 Align = EltInfo.second;
279 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000280 }
Nate Begeman213541a2008-04-18 23:10:10 +0000281 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000282 case Type::Vector: {
283 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000284 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000285 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000286 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000287 // If the alignment is not a power of 2, round up to the next power of 2.
288 // This happens for non-power-of-2 length vectors.
289 // FIXME: this should probably be a target property.
290 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000291 break;
292 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000293
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000294 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000295 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000296 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000297 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000298 // GCC extension: alignof(void) = 8 bits.
299 Width = 0;
300 Align = 8;
301 break;
302
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000303 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000304 Width = Target.getBoolWidth();
305 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000306 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000307 case BuiltinType::Char_S:
308 case BuiltinType::Char_U:
309 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000310 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000311 Width = Target.getCharWidth();
312 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000313 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000314 case BuiltinType::WChar:
315 Width = Target.getWCharWidth();
316 Align = Target.getWCharAlign();
317 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000318 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000319 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000320 Width = Target.getShortWidth();
321 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000322 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000323 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000324 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000325 Width = Target.getIntWidth();
326 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000327 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000328 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000329 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000330 Width = Target.getLongWidth();
331 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000332 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000333 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000334 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000335 Width = Target.getLongLongWidth();
336 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000337 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000338 case BuiltinType::Int128:
339 case BuiltinType::UInt128:
340 Width = 128;
341 Align = 128; // int128_t is 128-bit aligned on all targets.
342 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000343 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000344 Width = Target.getFloatWidth();
345 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000346 break;
347 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000348 Width = Target.getDoubleWidth();
349 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000350 break;
351 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000352 Width = Target.getLongDoubleWidth();
353 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000354 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000355 case BuiltinType::NullPtr:
356 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
357 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000358 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000359 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000360 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000361 case Type::FixedWidthInt:
362 // FIXME: This isn't precisely correct; the width/alignment should depend
363 // on the available types for the target
364 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000365 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000366 Align = Width;
367 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000368 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000369 // FIXME: Pointers into different addr spaces could have different sizes and
370 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000371 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000372 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000373 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000374 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000375 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000376 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000377 case Type::BlockPointer: {
378 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
379 Width = Target.getPointerWidth(AS);
380 Align = Target.getPointerAlign(AS);
381 break;
382 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000383 case Type::Pointer: {
384 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000385 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000386 Align = Target.getPointerAlign(AS);
387 break;
388 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000389 case Type::LValueReference:
390 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000391 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000392 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000393 // FIXME: This is wrong for struct layout: a reference in a struct has
394 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000395 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000396 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000397 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
398 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
399 // If we ever want to support other ABIs this needs to be abstracted.
400
Sebastian Redlf30208a2009-01-24 21:16:55 +0000401 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000402 std::pair<uint64_t, unsigned> PtrDiffInfo =
403 getTypeInfo(getPointerDiffType());
404 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000405 if (Pointee->isFunctionType())
406 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000407 Align = PtrDiffInfo.second;
408 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000409 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000410 case Type::Complex: {
411 // Complex types have the same alignment as their elements, but twice the
412 // size.
413 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000414 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000415 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000416 Align = EltInfo.second;
417 break;
418 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000419 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000420 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000421 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
422 Width = Layout.getSize();
423 Align = Layout.getAlignment();
424 break;
425 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000426 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000427 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000428 const TagType *TT = cast<TagType>(T);
429
430 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000431 Width = 1;
432 Align = 1;
433 break;
434 }
435
Daniel Dunbar1d751182008-11-08 05:48:37 +0000436 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000437 return getTypeInfo(ET->getDecl()->getIntegerType());
438
Daniel Dunbar1d751182008-11-08 05:48:37 +0000439 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000440 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
441 Width = Layout.getSize();
442 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000443 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000444 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000445
Douglas Gregor18857642009-04-30 17:32:17 +0000446 case Type::Typedef: {
447 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
448 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
449 Align = Aligned->getAlignment();
450 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
451 } else
452 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000453 break;
Chris Lattner71763312008-04-06 22:05:18 +0000454 }
Douglas Gregor18857642009-04-30 17:32:17 +0000455
456 case Type::TypeOfExpr:
457 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
458 .getTypePtr());
459
460 case Type::TypeOf:
461 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
462
463 case Type::QualifiedName:
464 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
465
466 case Type::TemplateSpecialization:
467 assert(getCanonicalType(T) != T &&
468 "Cannot request the size of a dependent type");
469 // FIXME: this is likely to be wrong once we support template
470 // aliases, since a template alias could refer to a typedef that
471 // has an __aligned__ attribute on it.
472 return getTypeInfo(getCanonicalType(T));
473 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000474
Chris Lattner464175b2007-07-18 17:52:12 +0000475 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000476 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000477}
478
Chris Lattner34ebde42009-01-27 18:08:34 +0000479/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
480/// type for the current target in bits. This can be different than the ABI
481/// alignment in cases where it is beneficial for performance to overalign
482/// a data type.
483unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
484 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000485
486 // Double and long long should be naturally aligned if possible.
487 if (const ComplexType* CT = T->getAsComplexType())
488 T = CT->getElementType().getTypePtr();
489 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
490 T->isSpecificBuiltinType(BuiltinType::LongLong))
491 return std::max(ABIAlign, (unsigned)getTypeSize(T));
492
Chris Lattner34ebde42009-01-27 18:08:34 +0000493 return ABIAlign;
494}
495
496
Devang Patel8b277042008-06-04 21:22:16 +0000497/// LayoutField - Field layout.
498void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000499 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000500 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000501 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000502 uint64_t FieldOffset = IsUnion ? 0 : Size;
503 uint64_t FieldSize;
504 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000505
506 // FIXME: Should this override struct packing? Probably we want to
507 // take the minimum?
508 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
509 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000510
511 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
512 // TODO: Need to check this algorithm on other targets!
513 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000514 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000515
516 std::pair<uint64_t, unsigned> FieldInfo =
517 Context.getTypeInfo(FD->getType());
518 uint64_t TypeSize = FieldInfo.first;
519
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000520 // Determine the alignment of this bitfield. The packing
521 // attributes define a maximum and the alignment attribute defines
522 // a minimum.
523 // FIXME: What is the right behavior when the specified alignment
524 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000525 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000526 if (FieldPacking)
527 FieldAlign = std::min(FieldAlign, FieldPacking);
Devang Patel8b277042008-06-04 21:22:16 +0000528 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
529 FieldAlign = std::max(FieldAlign, AA->getAlignment());
530
531 // Check if we need to add padding to give the field the correct
532 // alignment.
533 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
534 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
535
536 // Padding members don't affect overall alignment
537 if (!FD->getIdentifier())
538 FieldAlign = 1;
539 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000540 if (FD->getType()->isIncompleteArrayType()) {
541 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000542 // query getTypeInfo about these, so we figure it out here.
543 // Flexible array members don't have any size, but they
544 // have to be aligned appropriately for their element type.
545 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000546 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000547 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000548 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
549 unsigned AS = RT->getPointeeType().getAddressSpace();
550 FieldSize = Context.Target.getPointerWidth(AS);
551 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000552 } else {
553 std::pair<uint64_t, unsigned> FieldInfo =
554 Context.getTypeInfo(FD->getType());
555 FieldSize = FieldInfo.first;
556 FieldAlign = FieldInfo.second;
557 }
558
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000559 // Determine the alignment of this bitfield. The packing
560 // attributes define a maximum and the alignment attribute defines
561 // a minimum. Additionally, the packing alignment must be at least
562 // a byte for non-bitfields.
563 //
564 // FIXME: What is the right behavior when the specified alignment
565 // is smaller than the specified packing?
566 if (FieldPacking)
567 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Devang Patel8b277042008-06-04 21:22:16 +0000568 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
569 FieldAlign = std::max(FieldAlign, AA->getAlignment());
570
571 // Round up the current record size to the field's alignment boundary.
572 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
573 }
574
575 // Place this field at the current location.
576 FieldOffsets[FieldNo] = FieldOffset;
577
578 // Reserve space for this field.
579 if (IsUnion) {
580 Size = std::max(Size, FieldSize);
581 } else {
582 Size = FieldOffset + FieldSize;
583 }
584
Daniel Dunbard6884a02009-05-04 05:16:21 +0000585 // Remember the next available offset.
586 NextOffset = Size;
587
Devang Patel8b277042008-06-04 21:22:16 +0000588 // Remember max struct/class alignment.
589 Alignment = std::max(Alignment, FieldAlign);
590}
591
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000592static void CollectLocalObjCIvars(ASTContext *Ctx,
593 const ObjCInterfaceDecl *OI,
594 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000595 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
596 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000597 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000598 if (!IVDecl->isInvalidDecl())
599 Fields.push_back(cast<FieldDecl>(IVDecl));
600 }
601}
602
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000603void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
604 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
605 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
606 CollectObjCIvars(SuperClass, Fields);
607 CollectLocalObjCIvars(this, OI, Fields);
608}
609
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000610/// ShallowCollectObjCIvars -
611/// Collect all ivars, including those synthesized, in the current class.
612///
613void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
614 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
615 bool CollectSynthesized) {
616 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
617 E = OI->ivar_end(); I != E; ++I) {
618 Ivars.push_back(*I);
619 }
620 if (CollectSynthesized)
621 CollectSynthesizedIvars(OI, Ivars);
622}
623
Fariborz Jahanian98200742009-05-12 18:14:29 +0000624void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
625 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
626 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
627 E = PD->prop_end(*this); I != E; ++I)
628 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
629 Ivars.push_back(Ivar);
630
631 // Also look into nested protocols.
632 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
633 E = PD->protocol_end(); P != E; ++P)
634 CollectProtocolSynthesizedIvars(*P, Ivars);
635}
636
637/// CollectSynthesizedIvars -
638/// This routine collect synthesized ivars for the designated class.
639///
640void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
641 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
642 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
643 E = OI->prop_end(*this); I != E; ++I) {
644 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
645 Ivars.push_back(Ivar);
646 }
647 // Also look into interface's protocol list for properties declared
648 // in the protocol and whose ivars are synthesized.
649 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
650 PE = OI->protocol_end(); P != PE; ++P) {
651 ObjCProtocolDecl *PD = (*P);
652 CollectProtocolSynthesizedIvars(PD, Ivars);
653 }
654}
655
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000656unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
657 unsigned count = 0;
658 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
659 E = PD->prop_end(*this); I != E; ++I)
660 if ((*I)->getPropertyIvarDecl())
661 ++count;
662
663 // Also look into nested protocols.
664 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
665 E = PD->protocol_end(); P != E; ++P)
666 count += CountProtocolSynthesizedIvars(*P);
667 return count;
668}
669
670unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
671{
672 unsigned count = 0;
673 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
674 E = OI->prop_end(*this); I != E; ++I) {
675 if ((*I)->getPropertyIvarDecl())
676 ++count;
677 }
678 // Also look into interface's protocol list for properties declared
679 // in the protocol and whose ivars are synthesized.
680 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
681 PE = OI->protocol_end(); P != PE; ++P) {
682 ObjCProtocolDecl *PD = (*P);
683 count += CountProtocolSynthesizedIvars(PD);
684 }
685 return count;
686}
687
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000688/// getInterfaceLayoutImpl - Get or compute information about the
689/// layout of the given interface.
690///
691/// \param Impl - If given, also include the layout of the interface's
692/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000693const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000694ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
695 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000696 assert(!D->isForwardDecl() && "Invalid interface decl!");
697
Devang Patel44a3dde2008-06-04 21:54:36 +0000698 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000699 ObjCContainerDecl *Key =
700 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
701 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
702 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000703
Daniel Dunbar453addb2009-05-03 11:16:44 +0000704 unsigned FieldCount = D->ivar_size();
705 // Add in synthesized ivar count if laying out an implementation.
706 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000707 unsigned SynthCount = CountSynthesizedIvars(D);
708 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000709 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000710 // entry. Note we can't cache this because we simply free all
711 // entries later; however we shouldn't look up implementations
712 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000713 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000714 return getObjCLayout(D, 0);
715 }
716
Devang Patel6a5a34c2008-06-06 02:14:01 +0000717 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000718 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000719 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
720 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000721
Daniel Dunbar913af352009-05-07 21:58:26 +0000722 // We start laying out ivars not at the end of the superclass
723 // structure, but at the next byte following the last field.
724 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000725
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000726 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000727 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000728 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000729 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000730 NewEntry->InitializeLayout(FieldCount);
731 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000732
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000733 unsigned StructPacking = 0;
734 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
735 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000736
737 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
738 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
739 AA->getAlignment()));
740
741 // Layout each ivar sequentially.
742 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000743 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
744 ShallowCollectObjCIvars(D, Ivars, Impl);
745 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
746 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
747
Devang Patel44a3dde2008-06-04 21:54:36 +0000748 // Finally, round the size of the total struct up to the alignment of the
749 // struct itself.
750 NewEntry->FinalizeLayout();
751 return *NewEntry;
752}
753
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000754const ASTRecordLayout &
755ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
756 return getObjCLayout(D, 0);
757}
758
759const ASTRecordLayout &
760ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
761 return getObjCLayout(D->getClassInterface(), D);
762}
763
Devang Patel88a981b2007-11-01 19:11:01 +0000764/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000765/// specified record (struct/union/class), which indicates its size and field
766/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000767const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000768 D = D->getDefinition(*this);
769 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000770
Chris Lattner464175b2007-07-18 17:52:12 +0000771 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000772 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000773 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000774
Devang Patel88a981b2007-11-01 19:11:01 +0000775 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
776 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
777 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000778 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000779
Douglas Gregore267ff32008-12-11 20:41:00 +0000780 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000781 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
782 D->field_end(*this)));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000783 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000784
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000785 unsigned StructPacking = 0;
786 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
787 StructPacking = PA->getAlignment();
788
Eli Friedman4bd998b2008-05-30 09:31:38 +0000789 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000790 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
791 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000792
Eli Friedman4bd998b2008-05-30 09:31:38 +0000793 // Layout each field, for now, just sequentially, respecting alignment. In
794 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000795 unsigned FieldIdx = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000796 for (RecordDecl::field_iterator Field = D->field_begin(*this),
797 FieldEnd = D->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000798 Field != FieldEnd; (void)++Field, ++FieldIdx)
799 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000800
801 // Finally, round the size of the total struct up to the alignment of the
802 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000803 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +0000804 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000805}
806
Chris Lattnera7674d82007-07-13 22:13:22 +0000807//===----------------------------------------------------------------------===//
808// Type creation/memoization methods
809//===----------------------------------------------------------------------===//
810
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000811QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000812 QualType CanT = getCanonicalType(T);
813 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000814 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000815
816 // If we are composing extended qualifiers together, merge together into one
817 // ExtQualType node.
818 unsigned CVRQuals = T.getCVRQualifiers();
819 QualType::GCAttrTypes GCAttr = QualType::GCNone;
820 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000821
Chris Lattnerb7d25532009-02-18 22:53:11 +0000822 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
823 // If this type already has an address space specified, it cannot get
824 // another one.
825 assert(EQT->getAddressSpace() == 0 &&
826 "Type cannot be in multiple addr spaces!");
827 GCAttr = EQT->getObjCGCAttr();
828 TypeNode = EQT->getBaseType();
829 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000830
Chris Lattnerb7d25532009-02-18 22:53:11 +0000831 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000832 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000833 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000834 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000835 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000836 return QualType(EXTQy, CVRQuals);
837
Christopher Lambebb97e92008-02-04 02:31:56 +0000838 // If the base type isn't canonical, this won't be a canonical type either,
839 // so fill in the canonical type field.
840 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000841 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000842 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000843
Chris Lattnerb7d25532009-02-18 22:53:11 +0000844 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000845 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000846 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000847 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000848 ExtQualType *New =
849 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000850 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000851 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000852 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000853}
854
Chris Lattnerb7d25532009-02-18 22:53:11 +0000855QualType ASTContext::getObjCGCQualType(QualType T,
856 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000857 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000858 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000859 return T;
860
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000861 if (T->isPointerType()) {
862 QualType Pointee = T->getAsPointerType()->getPointeeType();
863 if (Pointee->isPointerType()) {
864 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
865 return getPointerType(ResultType);
866 }
867 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000868 // If we are composing extended qualifiers together, merge together into one
869 // ExtQualType node.
870 unsigned CVRQuals = T.getCVRQualifiers();
871 Type *TypeNode = T.getTypePtr();
872 unsigned AddressSpace = 0;
873
874 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
875 // If this type already has an address space specified, it cannot get
876 // another one.
877 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
878 "Type cannot be in multiple addr spaces!");
879 AddressSpace = EQT->getAddressSpace();
880 TypeNode = EQT->getBaseType();
881 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000882
883 // Check if we've already instantiated an gc qual'd type of this type.
884 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000885 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000886 void *InsertPos = 0;
887 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000888 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000889
890 // If the base type isn't canonical, this won't be a canonical type either,
891 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000892 // FIXME: Isn't this also not canonical if the base type is a array
893 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000894 QualType Canonical;
895 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000896 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000897
Chris Lattnerb7d25532009-02-18 22:53:11 +0000898 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000899 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
900 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
901 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000902 ExtQualType *New =
903 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000904 ExtQualTypes.InsertNode(New, InsertPos);
905 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000906 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000907}
Chris Lattnera7674d82007-07-13 22:13:22 +0000908
Reid Spencer5f016e22007-07-11 17:01:13 +0000909/// getComplexType - Return the uniqued reference to the type for a complex
910/// number with the specified element type.
911QualType ASTContext::getComplexType(QualType T) {
912 // Unique pointers, to guarantee there is only one pointer of a particular
913 // structure.
914 llvm::FoldingSetNodeID ID;
915 ComplexType::Profile(ID, T);
916
917 void *InsertPos = 0;
918 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
919 return QualType(CT, 0);
920
921 // If the pointee type isn't canonical, this won't be a canonical type either,
922 // so fill in the canonical type field.
923 QualType Canonical;
924 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000925 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000926
927 // Get the new insert position for the node we care about.
928 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000929 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 }
Steve Narofff83820b2009-01-27 22:08:43 +0000931 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 Types.push_back(New);
933 ComplexTypes.InsertNode(New, InsertPos);
934 return QualType(New, 0);
935}
936
Eli Friedmanf98aba32009-02-13 02:31:07 +0000937QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
938 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
939 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
940 FixedWidthIntType *&Entry = Map[Width];
941 if (!Entry)
942 Entry = new FixedWidthIntType(Width, Signed);
943 return QualType(Entry, 0);
944}
Reid Spencer5f016e22007-07-11 17:01:13 +0000945
946/// getPointerType - Return the uniqued reference to the type for a pointer to
947/// the specified type.
948QualType ASTContext::getPointerType(QualType T) {
949 // Unique pointers, to guarantee there is only one pointer of a particular
950 // structure.
951 llvm::FoldingSetNodeID ID;
952 PointerType::Profile(ID, T);
953
954 void *InsertPos = 0;
955 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
956 return QualType(PT, 0);
957
958 // If the pointee type isn't canonical, this won't be a canonical type either,
959 // so fill in the canonical type field.
960 QualType Canonical;
961 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000962 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000963
964 // Get the new insert position for the node we care about.
965 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000966 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 }
Steve Narofff83820b2009-01-27 22:08:43 +0000968 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 Types.push_back(New);
970 PointerTypes.InsertNode(New, InsertPos);
971 return QualType(New, 0);
972}
973
Steve Naroff5618bd42008-08-27 16:04:49 +0000974/// getBlockPointerType - Return the uniqued reference to the type for
975/// a pointer to the specified block.
976QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000977 assert(T->isFunctionType() && "block of function types only");
978 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000979 // structure.
980 llvm::FoldingSetNodeID ID;
981 BlockPointerType::Profile(ID, T);
982
983 void *InsertPos = 0;
984 if (BlockPointerType *PT =
985 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
986 return QualType(PT, 0);
987
Steve Naroff296e8d52008-08-28 19:20:44 +0000988 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000989 // type either so fill in the canonical type field.
990 QualType Canonical;
991 if (!T->isCanonical()) {
992 Canonical = getBlockPointerType(getCanonicalType(T));
993
994 // Get the new insert position for the node we care about.
995 BlockPointerType *NewIP =
996 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000997 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +0000998 }
Steve Narofff83820b2009-01-27 22:08:43 +0000999 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001000 Types.push_back(New);
1001 BlockPointerTypes.InsertNode(New, InsertPos);
1002 return QualType(New, 0);
1003}
1004
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001005/// getLValueReferenceType - Return the uniqued reference to the type for an
1006/// lvalue reference to the specified type.
1007QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 // Unique pointers, to guarantee there is only one pointer of a particular
1009 // structure.
1010 llvm::FoldingSetNodeID ID;
1011 ReferenceType::Profile(ID, T);
1012
1013 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001014 if (LValueReferenceType *RT =
1015 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001017
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 // If the referencee type isn't canonical, this won't be a canonical type
1019 // either, so fill in the canonical type field.
1020 QualType Canonical;
1021 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001022 Canonical = getLValueReferenceType(getCanonicalType(T));
1023
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001025 LValueReferenceType *NewIP =
1026 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001027 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 }
1029
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001030 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001032 LValueReferenceTypes.InsertNode(New, InsertPos);
1033 return QualType(New, 0);
1034}
1035
1036/// getRValueReferenceType - Return the uniqued reference to the type for an
1037/// rvalue reference to the specified type.
1038QualType ASTContext::getRValueReferenceType(QualType T) {
1039 // Unique pointers, to guarantee there is only one pointer of a particular
1040 // structure.
1041 llvm::FoldingSetNodeID ID;
1042 ReferenceType::Profile(ID, T);
1043
1044 void *InsertPos = 0;
1045 if (RValueReferenceType *RT =
1046 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1047 return QualType(RT, 0);
1048
1049 // If the referencee type isn't canonical, this won't be a canonical type
1050 // either, so fill in the canonical type field.
1051 QualType Canonical;
1052 if (!T->isCanonical()) {
1053 Canonical = getRValueReferenceType(getCanonicalType(T));
1054
1055 // Get the new insert position for the node we care about.
1056 RValueReferenceType *NewIP =
1057 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1058 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1059 }
1060
1061 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1062 Types.push_back(New);
1063 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 return QualType(New, 0);
1065}
1066
Sebastian Redlf30208a2009-01-24 21:16:55 +00001067/// getMemberPointerType - Return the uniqued reference to the type for a
1068/// member pointer to the specified type, in the specified class.
1069QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1070{
1071 // Unique pointers, to guarantee there is only one pointer of a particular
1072 // structure.
1073 llvm::FoldingSetNodeID ID;
1074 MemberPointerType::Profile(ID, T, Cls);
1075
1076 void *InsertPos = 0;
1077 if (MemberPointerType *PT =
1078 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1079 return QualType(PT, 0);
1080
1081 // If the pointee or class type isn't canonical, this won't be a canonical
1082 // type either, so fill in the canonical type field.
1083 QualType Canonical;
1084 if (!T->isCanonical()) {
1085 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1086
1087 // Get the new insert position for the node we care about.
1088 MemberPointerType *NewIP =
1089 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1090 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1091 }
Steve Narofff83820b2009-01-27 22:08:43 +00001092 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001093 Types.push_back(New);
1094 MemberPointerTypes.InsertNode(New, InsertPos);
1095 return QualType(New, 0);
1096}
1097
Steve Narofffb22d962007-08-30 01:06:46 +00001098/// getConstantArrayType - Return the unique reference to the type for an
1099/// array of the specified element type.
1100QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001101 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001102 ArrayType::ArraySizeModifier ASM,
1103 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001104 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1105 "Constant array of VLAs is illegal!");
1106
Chris Lattner38aeec72009-05-13 04:12:56 +00001107 // Convert the array size into a canonical width matching the pointer size for
1108 // the target.
1109 llvm::APInt ArySize(ArySizeIn);
1110 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1111
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001113 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001114
1115 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001116 if (ConstantArrayType *ATP =
1117 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 return QualType(ATP, 0);
1119
1120 // If the element type isn't canonical, this won't be a canonical type either,
1121 // so fill in the canonical type field.
1122 QualType Canonical;
1123 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001124 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001125 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001127 ConstantArrayType *NewIP =
1128 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001129 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 }
1131
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001132 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001133 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001134 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 Types.push_back(New);
1136 return QualType(New, 0);
1137}
1138
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001139/// getVariableArrayType - Returns a non-unique reference to the type for a
1140/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001141QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1142 ArrayType::ArraySizeModifier ASM,
1143 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001144 // Since we don't unique expressions, it isn't possible to unique VLA's
1145 // that have an expression provided for their size.
1146
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001147 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001148 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001149
1150 VariableArrayTypes.push_back(New);
1151 Types.push_back(New);
1152 return QualType(New, 0);
1153}
1154
Douglas Gregor898574e2008-12-05 23:32:09 +00001155/// getDependentSizedArrayType - Returns a non-unique reference to
1156/// the type for a dependently-sized array of the specified element
1157/// type. FIXME: We will need these to be uniqued, or at least
1158/// comparable, at some point.
1159QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1160 ArrayType::ArraySizeModifier ASM,
1161 unsigned EltTypeQuals) {
1162 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1163 "Size must be type- or value-dependent!");
1164
1165 // Since we don't unique expressions, it isn't possible to unique
1166 // dependently-sized array types.
1167
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001168 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001169 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1170 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001171
1172 DependentSizedArrayTypes.push_back(New);
1173 Types.push_back(New);
1174 return QualType(New, 0);
1175}
1176
Eli Friedmanc5773c42008-02-15 18:16:39 +00001177QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1178 ArrayType::ArraySizeModifier ASM,
1179 unsigned EltTypeQuals) {
1180 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001181 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001182
1183 void *InsertPos = 0;
1184 if (IncompleteArrayType *ATP =
1185 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1186 return QualType(ATP, 0);
1187
1188 // If the element type isn't canonical, this won't be a canonical type
1189 // either, so fill in the canonical type field.
1190 QualType Canonical;
1191
1192 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001193 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001194 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001195
1196 // Get the new insert position for the node we care about.
1197 IncompleteArrayType *NewIP =
1198 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001199 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001200 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001201
Steve Narofff83820b2009-01-27 22:08:43 +00001202 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001203 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001204
1205 IncompleteArrayTypes.InsertNode(New, InsertPos);
1206 Types.push_back(New);
1207 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001208}
1209
Steve Naroff73322922007-07-18 18:00:27 +00001210/// getVectorType - Return the unique reference to a vector type of
1211/// the specified element type and size. VectorType must be a built-in type.
1212QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 BuiltinType *baseType;
1214
Chris Lattnerf52ab252008-04-06 22:59:24 +00001215 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001216 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001217
1218 // Check if we've already instantiated a vector of this type.
1219 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001220 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 void *InsertPos = 0;
1222 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1223 return QualType(VTP, 0);
1224
1225 // If the element type isn't canonical, this won't be a canonical type either,
1226 // so fill in the canonical type field.
1227 QualType Canonical;
1228 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001229 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001230
1231 // Get the new insert position for the node we care about.
1232 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001233 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 }
Steve Narofff83820b2009-01-27 22:08:43 +00001235 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 VectorTypes.InsertNode(New, InsertPos);
1237 Types.push_back(New);
1238 return QualType(New, 0);
1239}
1240
Nate Begeman213541a2008-04-18 23:10:10 +00001241/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001242/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001243QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001244 BuiltinType *baseType;
1245
Chris Lattnerf52ab252008-04-06 22:59:24 +00001246 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001247 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001248
1249 // Check if we've already instantiated a vector of this type.
1250 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001251 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001252 void *InsertPos = 0;
1253 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1254 return QualType(VTP, 0);
1255
1256 // If the element type isn't canonical, this won't be a canonical type either,
1257 // so fill in the canonical type field.
1258 QualType Canonical;
1259 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001260 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001261
1262 // Get the new insert position for the node we care about.
1263 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001264 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001265 }
Steve Narofff83820b2009-01-27 22:08:43 +00001266 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001267 VectorTypes.InsertNode(New, InsertPos);
1268 Types.push_back(New);
1269 return QualType(New, 0);
1270}
1271
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001272QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1273 Expr *SizeExpr,
1274 SourceLocation AttrLoc) {
1275 DependentSizedExtVectorType *New =
1276 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1277 SizeExpr, AttrLoc);
1278
1279 DependentSizedExtVectorTypes.push_back(New);
1280 Types.push_back(New);
1281 return QualType(New, 0);
1282}
1283
Douglas Gregor72564e72009-02-26 23:50:07 +00001284/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001285///
Douglas Gregor72564e72009-02-26 23:50:07 +00001286QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 // Unique functions, to guarantee there is only one function of a particular
1288 // structure.
1289 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001290 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001291
1292 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001293 if (FunctionNoProtoType *FT =
1294 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 return QualType(FT, 0);
1296
1297 QualType Canonical;
1298 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001299 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001300
1301 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001302 FunctionNoProtoType *NewIP =
1303 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001304 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 }
1306
Douglas Gregor72564e72009-02-26 23:50:07 +00001307 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001309 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 return QualType(New, 0);
1311}
1312
1313/// getFunctionType - Return a normal function type with a typed argument
1314/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001315QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001316 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001317 unsigned TypeQuals, bool hasExceptionSpec,
1318 bool hasAnyExceptionSpec, unsigned NumExs,
1319 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 // Unique functions, to guarantee there is only one function of a particular
1321 // structure.
1322 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001323 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001324 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1325 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
1327 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001328 if (FunctionProtoType *FTP =
1329 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001331
1332 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001334 if (hasExceptionSpec)
1335 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1337 if (!ArgArray[i]->isCanonical())
1338 isCanonical = false;
1339
1340 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001341 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 QualType Canonical;
1343 if (!isCanonical) {
1344 llvm::SmallVector<QualType, 16> CanonicalArgs;
1345 CanonicalArgs.reserve(NumArgs);
1346 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001347 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001348
Chris Lattnerf52ab252008-04-06 22:59:24 +00001349 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001350 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001351 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001354 FunctionProtoType *NewIP =
1355 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001356 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001358
Douglas Gregor72564e72009-02-26 23:50:07 +00001359 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001360 // for two variable size arrays (for parameter and exception types) at the
1361 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001362 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001363 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1364 NumArgs*sizeof(QualType) +
1365 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001366 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001367 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1368 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001370 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 return QualType(FTP, 0);
1372}
1373
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001374/// getTypeDeclType - Return the unique reference to the type for the
1375/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001376QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001377 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001378 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1379
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001380 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001381 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001382 else if (isa<TemplateTypeParmDecl>(Decl)) {
1383 assert(false && "Template type parameter types are always available.");
1384 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001385 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001386
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001387 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001388 if (PrevDecl)
1389 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001390 else
1391 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001392 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001393 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1394 if (PrevDecl)
1395 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001396 else
1397 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001398 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001399 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001400 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001401
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001402 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001403 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001404}
1405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406/// getTypedefType - Return the unique reference to the type for the
1407/// specified typename decl.
1408QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1409 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1410
Chris Lattnerf52ab252008-04-06 22:59:24 +00001411 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001412 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 Types.push_back(Decl->TypeForDecl);
1414 return QualType(Decl->TypeForDecl, 0);
1415}
1416
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001417/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001418/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001419QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001420 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1421
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001422 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1423 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001424 Types.push_back(Decl->TypeForDecl);
1425 return QualType(Decl->TypeForDecl, 0);
1426}
1427
Douglas Gregorfab9d672009-02-05 23:33:38 +00001428/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001429/// parameter or parameter pack with the given depth, index, and (optionally)
1430/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001431QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001432 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001433 IdentifierInfo *Name) {
1434 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001435 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001436 void *InsertPos = 0;
1437 TemplateTypeParmType *TypeParm
1438 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1439
1440 if (TypeParm)
1441 return QualType(TypeParm, 0);
1442
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001443 if (Name) {
1444 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1445 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1446 Name, Canon);
1447 } else
1448 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001449
1450 Types.push_back(TypeParm);
1451 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1452
1453 return QualType(TypeParm, 0);
1454}
1455
Douglas Gregor55f6b142009-02-09 18:46:07 +00001456QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001457ASTContext::getTemplateSpecializationType(TemplateName Template,
1458 const TemplateArgument *Args,
1459 unsigned NumArgs,
1460 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001461 if (!Canon.isNull())
1462 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001463
Douglas Gregor55f6b142009-02-09 18:46:07 +00001464 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001465 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001466
Douglas Gregor55f6b142009-02-09 18:46:07 +00001467 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001468 TemplateSpecializationType *Spec
1469 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001470
1471 if (Spec)
1472 return QualType(Spec, 0);
1473
Douglas Gregor7532dc62009-03-30 22:58:21 +00001474 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001475 sizeof(TemplateArgument) * NumArgs),
1476 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001477 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001478 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001479 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001480
1481 return QualType(Spec, 0);
1482}
1483
Douglas Gregore4e5b052009-03-19 00:18:19 +00001484QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001485ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001486 QualType NamedType) {
1487 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001488 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001489
1490 void *InsertPos = 0;
1491 QualifiedNameType *T
1492 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1493 if (T)
1494 return QualType(T, 0);
1495
Douglas Gregorab452ba2009-03-26 23:50:42 +00001496 T = new (*this) QualifiedNameType(NNS, NamedType,
1497 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001498 Types.push_back(T);
1499 QualifiedNameTypes.InsertNode(T, InsertPos);
1500 return QualType(T, 0);
1501}
1502
Douglas Gregord57959a2009-03-27 23:10:48 +00001503QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1504 const IdentifierInfo *Name,
1505 QualType Canon) {
1506 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1507
1508 if (Canon.isNull()) {
1509 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1510 if (CanonNNS != NNS)
1511 Canon = getTypenameType(CanonNNS, Name);
1512 }
1513
1514 llvm::FoldingSetNodeID ID;
1515 TypenameType::Profile(ID, NNS, Name);
1516
1517 void *InsertPos = 0;
1518 TypenameType *T
1519 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1520 if (T)
1521 return QualType(T, 0);
1522
1523 T = new (*this) TypenameType(NNS, Name, Canon);
1524 Types.push_back(T);
1525 TypenameTypes.InsertNode(T, InsertPos);
1526 return QualType(T, 0);
1527}
1528
Douglas Gregor17343172009-04-01 00:28:59 +00001529QualType
1530ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1531 const TemplateSpecializationType *TemplateId,
1532 QualType Canon) {
1533 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1534
1535 if (Canon.isNull()) {
1536 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1537 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1538 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1539 const TemplateSpecializationType *CanonTemplateId
1540 = CanonType->getAsTemplateSpecializationType();
1541 assert(CanonTemplateId &&
1542 "Canonical type must also be a template specialization type");
1543 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1544 }
1545 }
1546
1547 llvm::FoldingSetNodeID ID;
1548 TypenameType::Profile(ID, NNS, TemplateId);
1549
1550 void *InsertPos = 0;
1551 TypenameType *T
1552 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1553 if (T)
1554 return QualType(T, 0);
1555
1556 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1557 Types.push_back(T);
1558 TypenameTypes.InsertNode(T, InsertPos);
1559 return QualType(T, 0);
1560}
1561
Chris Lattner88cb27a2008-04-07 04:56:42 +00001562/// CmpProtocolNames - Comparison predicate for sorting protocols
1563/// alphabetically.
1564static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1565 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001566 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001567}
1568
1569static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1570 unsigned &NumProtocols) {
1571 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1572
1573 // Sort protocols, keyed by name.
1574 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1575
1576 // Remove duplicates.
1577 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1578 NumProtocols = ProtocolsEnd-Protocols;
1579}
1580
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001581/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1582/// the given interface decl and the conforming protocol list.
1583QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1584 ObjCProtocolDecl **Protocols,
1585 unsigned NumProtocols) {
1586 // Sort the protocol list alphabetically to canonicalize it.
1587 if (NumProtocols)
1588 SortAndUniqueProtocols(Protocols, NumProtocols);
1589
1590 llvm::FoldingSetNodeID ID;
1591 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1592
1593 void *InsertPos = 0;
1594 if (ObjCObjectPointerType *QT =
1595 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1596 return QualType(QT, 0);
1597
1598 // No Match;
1599 ObjCObjectPointerType *QType =
1600 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1601
1602 Types.push_back(QType);
1603 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1604 return QualType(QType, 0);
1605}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001606
Chris Lattner065f0d72008-04-07 04:44:08 +00001607/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1608/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001609QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1610 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001611 // Sort the protocol list alphabetically to canonicalize it.
1612 SortAndUniqueProtocols(Protocols, NumProtocols);
1613
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001614 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001615 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001616
1617 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001618 if (ObjCQualifiedInterfaceType *QT =
1619 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001620 return QualType(QT, 0);
1621
1622 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001623 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001624 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001625
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001626 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001627 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001628 return QualType(QType, 0);
1629}
1630
Chris Lattner88cb27a2008-04-07 04:56:42 +00001631/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1632/// and the conforming protocol list.
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001633QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001634 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001635 return getObjCObjectPointerType(0, Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001636}
1637
Douglas Gregor72564e72009-02-26 23:50:07 +00001638/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1639/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001640/// multiple declarations that refer to "typeof(x)" all contain different
1641/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1642/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001643QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001644 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001645 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001646 Types.push_back(toe);
1647 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001648}
1649
Steve Naroff9752f252007-08-01 18:02:17 +00001650/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1651/// TypeOfType AST's. The only motivation to unique these nodes would be
1652/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1653/// an issue. This doesn't effect the type checker, since it operates
1654/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001655QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001656 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001657 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001658 Types.push_back(tot);
1659 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001660}
1661
Reid Spencer5f016e22007-07-11 17:01:13 +00001662/// getTagDeclType - Return the unique reference to the type for the
1663/// specified TagDecl (struct/union/class/enum) decl.
1664QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001665 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001666 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001667}
1668
1669/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1670/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1671/// needs to agree with the definition in <stddef.h>.
1672QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001673 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001674}
1675
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001676/// getSignedWCharType - Return the type of "signed wchar_t".
1677/// Used when in C++, as a GCC extension.
1678QualType ASTContext::getSignedWCharType() const {
1679 // FIXME: derive from "Target" ?
1680 return WCharTy;
1681}
1682
1683/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1684/// Used when in C++, as a GCC extension.
1685QualType ASTContext::getUnsignedWCharType() const {
1686 // FIXME: derive from "Target" ?
1687 return UnsignedIntTy;
1688}
1689
Chris Lattner8b9023b2007-07-13 03:05:23 +00001690/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1691/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1692QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001693 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001694}
1695
Chris Lattnere6327742008-04-02 05:18:44 +00001696//===----------------------------------------------------------------------===//
1697// Type Operators
1698//===----------------------------------------------------------------------===//
1699
Chris Lattner77c96472008-04-06 22:41:35 +00001700/// getCanonicalType - Return the canonical (structural) type corresponding to
1701/// the specified potentially non-canonical type. The non-canonical version
1702/// of a type may have many "decorated" versions of types. Decorators can
1703/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1704/// to be free of any of these, allowing two canonical types to be compared
1705/// for exact equality with a simple pointer comparison.
1706QualType ASTContext::getCanonicalType(QualType T) {
1707 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001708
1709 // If the result has type qualifiers, make sure to canonicalize them as well.
1710 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1711 if (TypeQuals == 0) return CanType;
1712
1713 // If the type qualifiers are on an array type, get the canonical type of the
1714 // array with the qualifiers applied to the element type.
1715 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1716 if (!AT)
1717 return CanType.getQualifiedType(TypeQuals);
1718
1719 // Get the canonical version of the element with the extra qualifiers on it.
1720 // This can recursively sink qualifiers through multiple levels of arrays.
1721 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1722 NewEltTy = getCanonicalType(NewEltTy);
1723
1724 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1725 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1726 CAT->getIndexTypeQualifier());
1727 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1728 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1729 IAT->getIndexTypeQualifier());
1730
Douglas Gregor898574e2008-12-05 23:32:09 +00001731 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1732 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1733 DSAT->getSizeModifier(),
1734 DSAT->getIndexTypeQualifier());
1735
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001736 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1737 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1738 VAT->getSizeModifier(),
1739 VAT->getIndexTypeQualifier());
1740}
1741
Douglas Gregor7da97d02009-05-10 22:57:19 +00001742Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001743 if (!D)
1744 return 0;
1745
Douglas Gregor7da97d02009-05-10 22:57:19 +00001746 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1747 QualType T = getTagDeclType(Tag);
1748 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1749 ->getDecl());
1750 }
1751
1752 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1753 while (Template->getPreviousDeclaration())
1754 Template = Template->getPreviousDeclaration();
1755 return Template;
1756 }
1757
1758 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1759 while (Function->getPreviousDeclaration())
1760 Function = Function->getPreviousDeclaration();
1761 return const_cast<FunctionDecl *>(Function);
1762 }
1763
1764 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1765 while (Var->getPreviousDeclaration())
1766 Var = Var->getPreviousDeclaration();
1767 return const_cast<VarDecl *>(Var);
1768 }
1769
1770 return D;
1771}
1772
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001773TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1774 // If this template name refers to a template, the canonical
1775 // template name merely stores the template itself.
1776 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001777 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001778
1779 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1780 assert(DTN && "Non-dependent template names must refer to template decls.");
1781 return DTN->CanonicalTemplateName;
1782}
1783
Douglas Gregord57959a2009-03-27 23:10:48 +00001784NestedNameSpecifier *
1785ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1786 if (!NNS)
1787 return 0;
1788
1789 switch (NNS->getKind()) {
1790 case NestedNameSpecifier::Identifier:
1791 // Canonicalize the prefix but keep the identifier the same.
1792 return NestedNameSpecifier::Create(*this,
1793 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1794 NNS->getAsIdentifier());
1795
1796 case NestedNameSpecifier::Namespace:
1797 // A namespace is canonical; build a nested-name-specifier with
1798 // this namespace and no prefix.
1799 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1800
1801 case NestedNameSpecifier::TypeSpec:
1802 case NestedNameSpecifier::TypeSpecWithTemplate: {
1803 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1804 NestedNameSpecifier *Prefix = 0;
1805
1806 // FIXME: This isn't the right check!
1807 if (T->isDependentType())
1808 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1809
1810 return NestedNameSpecifier::Create(*this, Prefix,
1811 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1812 T.getTypePtr());
1813 }
1814
1815 case NestedNameSpecifier::Global:
1816 // The global specifier is canonical and unique.
1817 return NNS;
1818 }
1819
1820 // Required to silence a GCC warning
1821 return 0;
1822}
1823
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001824
1825const ArrayType *ASTContext::getAsArrayType(QualType T) {
1826 // Handle the non-qualified case efficiently.
1827 if (T.getCVRQualifiers() == 0) {
1828 // Handle the common positive case fast.
1829 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1830 return AT;
1831 }
1832
1833 // Handle the common negative case fast, ignoring CVR qualifiers.
1834 QualType CType = T->getCanonicalTypeInternal();
1835
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001836 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001837 // test.
1838 if (!isa<ArrayType>(CType) &&
1839 !isa<ArrayType>(CType.getUnqualifiedType()))
1840 return 0;
1841
1842 // Apply any CVR qualifiers from the array type to the element type. This
1843 // implements C99 6.7.3p8: "If the specification of an array type includes
1844 // any type qualifiers, the element type is so qualified, not the array type."
1845
1846 // If we get here, we either have type qualifiers on the type, or we have
1847 // sugar such as a typedef in the way. If we have type qualifiers on the type
1848 // we must propagate them down into the elemeng type.
1849 unsigned CVRQuals = T.getCVRQualifiers();
1850 unsigned AddrSpace = 0;
1851 Type *Ty = T.getTypePtr();
1852
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001853 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001854 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001855 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1856 AddrSpace = EXTQT->getAddressSpace();
1857 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001858 } else {
1859 T = Ty->getDesugaredType();
1860 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1861 break;
1862 CVRQuals |= T.getCVRQualifiers();
1863 Ty = T.getTypePtr();
1864 }
1865 }
1866
1867 // If we have a simple case, just return now.
1868 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1869 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1870 return ATy;
1871
1872 // Otherwise, we have an array and we have qualifiers on it. Push the
1873 // qualifiers into the array element type and return a new array type.
1874 // Get the canonical version of the element with the extra qualifiers on it.
1875 // This can recursively sink qualifiers through multiple levels of arrays.
1876 QualType NewEltTy = ATy->getElementType();
1877 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001878 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001879 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1880
1881 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1882 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1883 CAT->getSizeModifier(),
1884 CAT->getIndexTypeQualifier()));
1885 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1886 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1887 IAT->getSizeModifier(),
1888 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001889
Douglas Gregor898574e2008-12-05 23:32:09 +00001890 if (const DependentSizedArrayType *DSAT
1891 = dyn_cast<DependentSizedArrayType>(ATy))
1892 return cast<ArrayType>(
1893 getDependentSizedArrayType(NewEltTy,
1894 DSAT->getSizeExpr(),
1895 DSAT->getSizeModifier(),
1896 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001897
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001898 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1899 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1900 VAT->getSizeModifier(),
1901 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001902}
1903
1904
Chris Lattnere6327742008-04-02 05:18:44 +00001905/// getArrayDecayedType - Return the properly qualified result of decaying the
1906/// specified array type to a pointer. This operation is non-trivial when
1907/// handling typedefs etc. The canonical type of "T" must be an array type,
1908/// this returns a pointer to a properly qualified element of the array.
1909///
1910/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1911QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001912 // Get the element type with 'getAsArrayType' so that we don't lose any
1913 // typedefs in the element type of the array. This also handles propagation
1914 // of type qualifiers from the array type into the element type if present
1915 // (C99 6.7.3p8).
1916 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1917 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001918
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001919 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001920
1921 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001922 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001923}
1924
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001925QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001926 QualType ElemTy = VAT->getElementType();
1927
1928 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1929 return getBaseElementType(VAT);
1930
1931 return ElemTy;
1932}
1933
Reid Spencer5f016e22007-07-11 17:01:13 +00001934/// getFloatingRank - Return a relative rank for floating point types.
1935/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001936static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001937 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001939
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001940 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001941 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001942 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 case BuiltinType::Float: return FloatRank;
1944 case BuiltinType::Double: return DoubleRank;
1945 case BuiltinType::LongDouble: return LongDoubleRank;
1946 }
1947}
1948
Steve Naroff716c7302007-08-27 01:41:48 +00001949/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1950/// point or a complex type (based on typeDomain/typeSize).
1951/// 'typeDomain' is a real floating point or complex type.
1952/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00001953QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1954 QualType Domain) const {
1955 FloatingRank EltRank = getFloatingRank(Size);
1956 if (Domain->isComplexType()) {
1957 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00001958 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00001959 case FloatRank: return FloatComplexTy;
1960 case DoubleRank: return DoubleComplexTy;
1961 case LongDoubleRank: return LongDoubleComplexTy;
1962 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 }
Chris Lattner1361b112008-04-06 23:58:54 +00001964
1965 assert(Domain->isRealFloatingType() && "Unknown domain!");
1966 switch (EltRank) {
1967 default: assert(0 && "getFloatingRank(): illegal value for rank");
1968 case FloatRank: return FloatTy;
1969 case DoubleRank: return DoubleTy;
1970 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00001971 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001972}
1973
Chris Lattner7cfeb082008-04-06 23:55:33 +00001974/// getFloatingTypeOrder - Compare the rank of the two specified floating
1975/// point types, ignoring the domain of the type (i.e. 'double' ==
1976/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1977/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00001978int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1979 FloatingRank LHSR = getFloatingRank(LHS);
1980 FloatingRank RHSR = getFloatingRank(RHS);
1981
1982 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001983 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00001984 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001985 return 1;
1986 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001987}
1988
Chris Lattnerf52ab252008-04-06 22:59:24 +00001989/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1990/// routine will assert if passed a built-in type that isn't an integer or enum,
1991/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00001992unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001993 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00001994 if (EnumType* ET = dyn_cast<EnumType>(T))
1995 T = ET->getDecl()->getIntegerType().getTypePtr();
1996
1997 // There are two things which impact the integer rank: the width, and
1998 // the ordering of builtins. The builtin ordering is encoded in the
1999 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002000 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002001 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002002
Chris Lattnerf52ab252008-04-06 22:59:24 +00002003 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002004 default: assert(0 && "getIntegerRank(): not a built-in integer");
2005 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002006 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002007 case BuiltinType::Char_S:
2008 case BuiltinType::Char_U:
2009 case BuiltinType::SChar:
2010 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002011 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002012 case BuiltinType::Short:
2013 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002014 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002015 case BuiltinType::Int:
2016 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002017 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002018 case BuiltinType::Long:
2019 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002020 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002021 case BuiltinType::LongLong:
2022 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002023 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002024 case BuiltinType::Int128:
2025 case BuiltinType::UInt128:
2026 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002027 }
2028}
2029
Chris Lattner7cfeb082008-04-06 23:55:33 +00002030/// getIntegerTypeOrder - Returns the highest ranked integer type:
2031/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2032/// LHS < RHS, return -1.
2033int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002034 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2035 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002036 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002037
Chris Lattnerf52ab252008-04-06 22:59:24 +00002038 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2039 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002040
Chris Lattner7cfeb082008-04-06 23:55:33 +00002041 unsigned LHSRank = getIntegerRank(LHSC);
2042 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002043
Chris Lattner7cfeb082008-04-06 23:55:33 +00002044 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2045 if (LHSRank == RHSRank) return 0;
2046 return LHSRank > RHSRank ? 1 : -1;
2047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002048
Chris Lattner7cfeb082008-04-06 23:55:33 +00002049 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2050 if (LHSUnsigned) {
2051 // If the unsigned [LHS] type is larger, return it.
2052 if (LHSRank >= RHSRank)
2053 return 1;
2054
2055 // If the signed type can represent all values of the unsigned type, it
2056 // wins. Because we are dealing with 2's complement and types that are
2057 // powers of two larger than each other, this is always safe.
2058 return -1;
2059 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002060
Chris Lattner7cfeb082008-04-06 23:55:33 +00002061 // If the unsigned [RHS] type is larger, return it.
2062 if (RHSRank >= LHSRank)
2063 return -1;
2064
2065 // If the signed type can represent all values of the unsigned type, it
2066 // wins. Because we are dealing with 2's complement and types that are
2067 // powers of two larger than each other, this is always safe.
2068 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002069}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002070
2071// getCFConstantStringType - Return the type used for constant CFStrings.
2072QualType ASTContext::getCFConstantStringType() {
2073 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002074 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002075 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002076 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002077 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002078
2079 // const int *isa;
2080 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002081 // int flags;
2082 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002083 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002084 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002085 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002086 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002087
Anders Carlsson71993dd2007-08-17 05:31:46 +00002088 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002089 for (unsigned i = 0; i < 4; ++i) {
2090 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2091 SourceLocation(), 0,
2092 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002093 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002094 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002095 }
2096
2097 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002098 }
2099
2100 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002101}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002102
Douglas Gregor319ac892009-04-23 22:29:11 +00002103void ASTContext::setCFConstantStringType(QualType T) {
2104 const RecordType *Rec = T->getAsRecordType();
2105 assert(Rec && "Invalid CFConstantStringType");
2106 CFConstantStringTypeDecl = Rec->getDecl();
2107}
2108
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002109QualType ASTContext::getObjCFastEnumerationStateType()
2110{
2111 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002112 ObjCFastEnumerationStateTypeDecl =
2113 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2114 &Idents.get("__objcFastEnumerationState"));
2115
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002116 QualType FieldTypes[] = {
2117 UnsignedLongTy,
2118 getPointerType(ObjCIdType),
2119 getPointerType(UnsignedLongTy),
2120 getConstantArrayType(UnsignedLongTy,
2121 llvm::APInt(32, 5), ArrayType::Normal, 0)
2122 };
2123
Douglas Gregor44b43212008-12-11 16:49:14 +00002124 for (size_t i = 0; i < 4; ++i) {
2125 FieldDecl *Field = FieldDecl::Create(*this,
2126 ObjCFastEnumerationStateTypeDecl,
2127 SourceLocation(), 0,
2128 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002129 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002130 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002131 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002132
Douglas Gregor44b43212008-12-11 16:49:14 +00002133 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002134 }
2135
2136 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2137}
2138
Douglas Gregor319ac892009-04-23 22:29:11 +00002139void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2140 const RecordType *Rec = T->getAsRecordType();
2141 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2142 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2143}
2144
Anders Carlssone8c49532007-10-29 06:33:42 +00002145// This returns true if a type has been typedefed to BOOL:
2146// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002147static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002148 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002149 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2150 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002151
2152 return false;
2153}
2154
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002155/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002156/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002157int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002158 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002159
2160 // Make all integer and enum types at least as large as an int
2161 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002162 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002163 // Treat arrays as pointers, since that's how they're passed in.
2164 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002165 sz = getTypeSize(VoidPtrTy);
2166 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002167}
2168
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002170/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002171void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002172 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002173 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002174 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002175 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002176 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002177 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002178 // Compute size of all parameters.
2179 // Start with computing size of a pointer in number of bytes.
2180 // FIXME: There might(should) be a better way of doing this computation!
2181 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002182 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002183 // The first two arguments (self and _cmd) are pointers; account for
2184 // their size.
2185 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002186 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2187 E = Decl->param_end(); PI != E; ++PI) {
2188 QualType PType = (*PI)->getType();
2189 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002191 ParmOffset += sz;
2192 }
2193 S += llvm::utostr(ParmOffset);
2194 S += "@0:";
2195 S += llvm::utostr(PtrSize);
2196
2197 // Argument types.
2198 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002199 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2200 E = Decl->param_end(); PI != E; ++PI) {
2201 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002202 QualType PType = PVDecl->getOriginalType();
2203 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002204 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2205 // Use array's original type only if it has known number of
2206 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002207 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002208 PType = PVDecl->getType();
2209 } else if (PType->isFunctionType())
2210 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002211 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002212 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002213 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002214 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002215 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002216 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002217 }
2218}
2219
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002220/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002221/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002222/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2223/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002224/// Property attributes are stored as a comma-delimited C string. The simple
2225/// attributes readonly and bycopy are encoded as single characters. The
2226/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2227/// encoded as single characters, followed by an identifier. Property types
2228/// are also encoded as a parametrized attribute. The characters used to encode
2229/// these attributes are defined by the following enumeration:
2230/// @code
2231/// enum PropertyAttributes {
2232/// kPropertyReadOnly = 'R', // property is read-only.
2233/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2234/// kPropertyByref = '&', // property is a reference to the value last assigned
2235/// kPropertyDynamic = 'D', // property is dynamic
2236/// kPropertyGetter = 'G', // followed by getter selector name
2237/// kPropertySetter = 'S', // followed by setter selector name
2238/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2239/// kPropertyType = 't' // followed by old-style type encoding.
2240/// kPropertyWeak = 'W' // 'weak' property
2241/// kPropertyStrong = 'P' // property GC'able
2242/// kPropertyNonAtomic = 'N' // property non-atomic
2243/// };
2244/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002245void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2246 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002247 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002248 // Collect information from the property implementation decl(s).
2249 bool Dynamic = false;
2250 ObjCPropertyImplDecl *SynthesizePID = 0;
2251
2252 // FIXME: Duplicated code due to poor abstraction.
2253 if (Container) {
2254 if (const ObjCCategoryImplDecl *CID =
2255 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2256 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002257 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2258 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002259 ObjCPropertyImplDecl *PID = *i;
2260 if (PID->getPropertyDecl() == PD) {
2261 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2262 Dynamic = true;
2263 } else {
2264 SynthesizePID = PID;
2265 }
2266 }
2267 }
2268 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002269 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002270 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002271 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2272 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002273 ObjCPropertyImplDecl *PID = *i;
2274 if (PID->getPropertyDecl() == PD) {
2275 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2276 Dynamic = true;
2277 } else {
2278 SynthesizePID = PID;
2279 }
2280 }
2281 }
2282 }
2283 }
2284
2285 // FIXME: This is not very efficient.
2286 S = "T";
2287
2288 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002289 // GCC has some special rules regarding encoding of properties which
2290 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002291 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002292 true /* outermost type */,
2293 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002294
2295 if (PD->isReadOnly()) {
2296 S += ",R";
2297 } else {
2298 switch (PD->getSetterKind()) {
2299 case ObjCPropertyDecl::Assign: break;
2300 case ObjCPropertyDecl::Copy: S += ",C"; break;
2301 case ObjCPropertyDecl::Retain: S += ",&"; break;
2302 }
2303 }
2304
2305 // It really isn't clear at all what this means, since properties
2306 // are "dynamic by default".
2307 if (Dynamic)
2308 S += ",D";
2309
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002310 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2311 S += ",N";
2312
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002313 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2314 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002315 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002316 }
2317
2318 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2319 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002320 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002321 }
2322
2323 if (SynthesizePID) {
2324 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2325 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002326 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002327 }
2328
2329 // FIXME: OBJCGC: weak & strong
2330}
2331
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002332/// getLegacyIntegralTypeEncoding -
2333/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002334/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002335/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2336///
2337void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2338 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2339 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002340 if (BT->getKind() == BuiltinType::ULong &&
2341 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002342 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002343 else
2344 if (BT->getKind() == BuiltinType::Long &&
2345 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002346 PointeeTy = IntTy;
2347 }
2348 }
2349}
2350
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002351void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002352 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002353 // We follow the behavior of gcc, expanding structures which are
2354 // directly pointed to, and expanding embedded structures. Note that
2355 // these rules are sufficient to prevent recursive encoding of the
2356 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002357 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2358 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002359}
2360
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002361static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002362 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002363 const Expr *E = FD->getBitWidth();
2364 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2365 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002366 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002367 S += 'b';
2368 S += llvm::utostr(N);
2369}
2370
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002371void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2372 bool ExpandPointedToStructures,
2373 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002374 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002375 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002376 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002377 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002378 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002379 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002380 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002381 else {
2382 char encoding;
2383 switch (BT->getKind()) {
2384 default: assert(0 && "Unhandled builtin type kind");
2385 case BuiltinType::Void: encoding = 'v'; break;
2386 case BuiltinType::Bool: encoding = 'B'; break;
2387 case BuiltinType::Char_U:
2388 case BuiltinType::UChar: encoding = 'C'; break;
2389 case BuiltinType::UShort: encoding = 'S'; break;
2390 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002391 case BuiltinType::ULong:
2392 encoding =
2393 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2394 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002395 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002396 case BuiltinType::ULongLong: encoding = 'Q'; break;
2397 case BuiltinType::Char_S:
2398 case BuiltinType::SChar: encoding = 'c'; break;
2399 case BuiltinType::Short: encoding = 's'; break;
2400 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002401 case BuiltinType::Long:
2402 encoding =
2403 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2404 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002405 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002406 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002407 case BuiltinType::Float: encoding = 'f'; break;
2408 case BuiltinType::Double: encoding = 'd'; break;
2409 case BuiltinType::LongDouble: encoding = 'd'; break;
2410 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002411
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002412 S += encoding;
2413 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002414 } else if (const ComplexType *CT = T->getAsComplexType()) {
2415 S += 'j';
2416 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2417 false);
2418 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002419 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2420 ExpandPointedToStructures,
2421 ExpandStructures, FD);
2422 if (FD || EncodingProperty) {
2423 // Note that we do extended encoding of protocol qualifer list
2424 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002425 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002426 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002427 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002428 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002429 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002430 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002431 S += '>';
2432 }
2433 S += '"';
2434 }
2435 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002436 }
2437 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002438 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002439 bool isReadOnly = false;
2440 // For historical/compatibility reasons, the read-only qualifier of the
2441 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2442 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2443 // Also, do not emit the 'r' for anything but the outermost type!
2444 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2445 if (OutermostType && T.isConstQualified()) {
2446 isReadOnly = true;
2447 S += 'r';
2448 }
2449 }
2450 else if (OutermostType) {
2451 QualType P = PointeeTy;
2452 while (P->getAsPointerType())
2453 P = P->getAsPointerType()->getPointeeType();
2454 if (P.isConstQualified()) {
2455 isReadOnly = true;
2456 S += 'r';
2457 }
2458 }
2459 if (isReadOnly) {
2460 // Another legacy compatibility encoding. Some ObjC qualifier and type
2461 // combinations need to be rearranged.
2462 // Rewrite "in const" from "nr" to "rn"
2463 const char * s = S.c_str();
2464 int len = S.length();
2465 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2466 std::string replace = "rn";
2467 S.replace(S.end()-2, S.end(), replace);
2468 }
2469 }
Steve Naroff389bf462009-02-12 17:52:19 +00002470 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002471 S += '@';
2472 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002473 }
2474 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002475 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002476 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002477 // Another historical/compatibility reason.
2478 // We encode the underlying type which comes out as
2479 // {...};
2480 S += '^';
2481 getObjCEncodingForTypeImpl(PointeeTy, S,
2482 false, ExpandPointedToStructures,
2483 NULL);
2484 return;
2485 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002486 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002487 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002488 const ObjCInterfaceType *OIT =
2489 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002490 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002491 S += '"';
2492 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002493 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2494 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002495 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002496 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002497 S += '>';
2498 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002499 S += '"';
2500 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002501 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002502 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002503 S += '#';
2504 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002506 S += ':';
2507 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002508 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002509
2510 if (PointeeTy->isCharType()) {
2511 // char pointer types should be encoded as '*' unless it is a
2512 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002513 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002514 S += '*';
2515 return;
2516 }
2517 }
2518
2519 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002520 getLegacyIntegralTypeEncoding(PointeeTy);
2521
2522 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002523 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002524 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002525 } else if (const ArrayType *AT =
2526 // Ignore type qualifiers etc.
2527 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002528 if (isa<IncompleteArrayType>(AT)) {
2529 // Incomplete arrays are encoded as a pointer to the array element.
2530 S += '^';
2531
2532 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2533 false, ExpandStructures, FD);
2534 } else {
2535 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002536
Anders Carlsson559a8332009-02-22 01:38:57 +00002537 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2538 S += llvm::utostr(CAT->getSize().getZExtValue());
2539 else {
2540 //Variable length arrays are encoded as a regular array with 0 elements.
2541 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2542 S += '0';
2543 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002544
Anders Carlsson559a8332009-02-22 01:38:57 +00002545 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2546 false, ExpandStructures, FD);
2547 S += ']';
2548 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002549 } else if (T->getAsFunctionType()) {
2550 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002551 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002552 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002553 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002554 // Anonymous structures print as '?'
2555 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2556 S += II->getName();
2557 } else {
2558 S += '?';
2559 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002560 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002561 S += '=';
Douglas Gregor6ab35242009-04-09 21:40:53 +00002562 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2563 FieldEnd = RDecl->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +00002564 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002565 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002566 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002567 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002568 S += '"';
2569 }
2570
2571 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002572 if (Field->isBitField()) {
2573 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2574 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002575 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002576 QualType qt = Field->getType();
2577 getLegacyIntegralTypeEncoding(qt);
2578 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002579 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002580 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002581 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002582 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002583 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002584 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002585 if (FD && FD->isBitField())
2586 EncodeBitField(this, S, FD);
2587 else
2588 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002589 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002590 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002591 } else if (T->isObjCInterfaceType()) {
2592 // @encode(class_name)
2593 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2594 S += '{';
2595 const IdentifierInfo *II = OI->getIdentifier();
2596 S += II->getName();
2597 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002598 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002599 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002600 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002601 if (RecFields[i]->isBitField())
2602 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2603 RecFields[i]);
2604 else
2605 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2606 FD);
2607 }
2608 S += '}';
2609 }
2610 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002611 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002612}
2613
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002614void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002615 std::string& S) const {
2616 if (QT & Decl::OBJC_TQ_In)
2617 S += 'n';
2618 if (QT & Decl::OBJC_TQ_Inout)
2619 S += 'N';
2620 if (QT & Decl::OBJC_TQ_Out)
2621 S += 'o';
2622 if (QT & Decl::OBJC_TQ_Bycopy)
2623 S += 'O';
2624 if (QT & Decl::OBJC_TQ_Byref)
2625 S += 'R';
2626 if (QT & Decl::OBJC_TQ_Oneway)
2627 S += 'V';
2628}
2629
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002630void ASTContext::setBuiltinVaListType(QualType T)
2631{
2632 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2633
2634 BuiltinVaListType = T;
2635}
2636
Douglas Gregor319ac892009-04-23 22:29:11 +00002637void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002638{
Douglas Gregor319ac892009-04-23 22:29:11 +00002639 ObjCIdType = T;
2640
2641 const TypedefType *TT = T->getAsTypedefType();
2642 if (!TT)
2643 return;
2644
2645 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002646
2647 // typedef struct objc_object *id;
2648 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002649 // User error - caller will issue diagnostics.
2650 if (!ptr)
2651 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002652 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002653 // User error - caller will issue diagnostics.
2654 if (!rec)
2655 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002656 IdStructType = rec;
2657}
2658
Douglas Gregor319ac892009-04-23 22:29:11 +00002659void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002660{
Douglas Gregor319ac892009-04-23 22:29:11 +00002661 ObjCSelType = T;
2662
2663 const TypedefType *TT = T->getAsTypedefType();
2664 if (!TT)
2665 return;
2666 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002667
2668 // typedef struct objc_selector *SEL;
2669 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002670 if (!ptr)
2671 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002672 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002673 if (!rec)
2674 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002675 SelStructType = rec;
2676}
2677
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002678void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002679{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002680 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002681}
2682
Douglas Gregor319ac892009-04-23 22:29:11 +00002683void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002684{
Douglas Gregor319ac892009-04-23 22:29:11 +00002685 ObjCClassType = T;
2686
2687 const TypedefType *TT = T->getAsTypedefType();
2688 if (!TT)
2689 return;
2690 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002691
2692 // typedef struct objc_class *Class;
2693 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2694 assert(ptr && "'Class' incorrectly typed");
2695 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2696 assert(rec && "'Class' incorrectly typed");
2697 ClassStructType = rec;
2698}
2699
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002700void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2701 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002702 "'NSConstantString' type already set!");
2703
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002704 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002705}
2706
Douglas Gregor7532dc62009-03-30 22:58:21 +00002707/// \brief Retrieve the template name that represents a qualified
2708/// template name such as \c std::vector.
2709TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2710 bool TemplateKeyword,
2711 TemplateDecl *Template) {
2712 llvm::FoldingSetNodeID ID;
2713 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2714
2715 void *InsertPos = 0;
2716 QualifiedTemplateName *QTN =
2717 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2718 if (!QTN) {
2719 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2720 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2721 }
2722
2723 return TemplateName(QTN);
2724}
2725
2726/// \brief Retrieve the template name that represents a dependent
2727/// template name such as \c MetaFun::template apply.
2728TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2729 const IdentifierInfo *Name) {
2730 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2731
2732 llvm::FoldingSetNodeID ID;
2733 DependentTemplateName::Profile(ID, NNS, Name);
2734
2735 void *InsertPos = 0;
2736 DependentTemplateName *QTN =
2737 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2738
2739 if (QTN)
2740 return TemplateName(QTN);
2741
2742 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2743 if (CanonNNS == NNS) {
2744 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2745 } else {
2746 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2747 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2748 }
2749
2750 DependentTemplateNames.InsertNode(QTN, InsertPos);
2751 return TemplateName(QTN);
2752}
2753
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002754/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002755/// TargetInfo, produce the corresponding type. The unsigned @p Type
2756/// is actually a value of type @c TargetInfo::IntType.
2757QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002758 switch (Type) {
2759 case TargetInfo::NoInt: return QualType();
2760 case TargetInfo::SignedShort: return ShortTy;
2761 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2762 case TargetInfo::SignedInt: return IntTy;
2763 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2764 case TargetInfo::SignedLong: return LongTy;
2765 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2766 case TargetInfo::SignedLongLong: return LongLongTy;
2767 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2768 }
2769
2770 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002771 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002772}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002773
2774//===----------------------------------------------------------------------===//
2775// Type Predicates.
2776//===----------------------------------------------------------------------===//
2777
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002778/// isObjCNSObjectType - Return true if this is an NSObject object using
2779/// NSObject attribute on a c-style pointer type.
2780/// FIXME - Make it work directly on types.
2781///
2782bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2783 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2784 if (TypedefDecl *TD = TDT->getDecl())
2785 if (TD->getAttr<ObjCNSObjectAttr>())
2786 return true;
2787 }
2788 return false;
2789}
2790
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002791/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2792/// to an object type. This includes "id" and "Class" (two 'special' pointers
2793/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2794/// ID type).
2795bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002796 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002797 return true;
2798
Steve Naroff6ae98502008-10-21 18:24:04 +00002799 // Blocks are objects.
2800 if (Ty->isBlockPointerType())
2801 return true;
2802
2803 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002804 const PointerType *PT = Ty->getAsPointerType();
2805 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002806 return false;
2807
Chris Lattner16ede0e2009-04-12 23:51:02 +00002808 // If this a pointer to an interface (e.g. NSString*), it is ok.
2809 if (PT->getPointeeType()->isObjCInterfaceType() ||
2810 // If is has NSObject attribute, OK as well.
2811 isObjCNSObjectType(Ty))
2812 return true;
2813
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002814 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2815 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002816 // underlying type. Iteratively strip off typedefs so that we can handle
2817 // typedefs of typedefs.
2818 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2819 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2820 Ty.getUnqualifiedType() == getObjCClassType())
2821 return true;
2822
2823 Ty = TDT->getDecl()->getUnderlyingType();
2824 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002825
Chris Lattner16ede0e2009-04-12 23:51:02 +00002826 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002827}
2828
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002829/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2830/// garbage collection attribute.
2831///
2832QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002833 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002834 if (getLangOptions().ObjC1 &&
2835 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002836 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002837 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002838 // (or pointers to them) be treated as though they were declared
2839 // as __strong.
2840 if (GCAttrs == QualType::GCNone) {
2841 if (isObjCObjectPointerType(Ty))
2842 GCAttrs = QualType::Strong;
2843 else if (Ty->isPointerType())
2844 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2845 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002846 // Non-pointers have none gc'able attribute regardless of the attribute
2847 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00002848 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002849 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002850 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002851 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002852}
2853
Chris Lattner6ac46a42008-04-07 06:51:04 +00002854//===----------------------------------------------------------------------===//
2855// Type Compatibility Testing
2856//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002857
Chris Lattner6ac46a42008-04-07 06:51:04 +00002858/// areCompatVectorTypes - Return true if the two specified vector types are
2859/// compatible.
2860static bool areCompatVectorTypes(const VectorType *LHS,
2861 const VectorType *RHS) {
2862 assert(LHS->isCanonical() && RHS->isCanonical());
2863 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002864 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002865}
2866
Eli Friedman3d815e72008-08-22 00:56:42 +00002867/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002868/// compatible for assignment from RHS to LHS. This handles validation of any
2869/// protocol qualifiers on the LHS or RHS.
2870///
Eli Friedman3d815e72008-08-22 00:56:42 +00002871bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2872 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002873 // Verify that the base decls are compatible: the RHS must be a subclass of
2874 // the LHS.
2875 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2876 return false;
2877
2878 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2879 // protocol qualified at all, then we are good.
2880 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2881 return true;
2882
2883 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2884 // isn't a superset.
2885 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2886 return true; // FIXME: should return false!
2887
2888 // Finally, we must have two protocol-qualified interfaces.
2889 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2890 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002891
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002892 // All LHS protocols must have a presence on the RHS.
2893 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002894
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002895 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2896 LHSPE = LHSP->qual_end();
2897 LHSPI != LHSPE; LHSPI++) {
2898 bool RHSImplementsProtocol = false;
2899
2900 // If the RHS doesn't implement the protocol on the left, the types
2901 // are incompatible.
2902 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2903 RHSPE = RHSP->qual_end();
2904 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2905 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2906 RHSImplementsProtocol = true;
2907 }
2908 // FIXME: For better diagnostics, consider passing back the protocol name.
2909 if (!RHSImplementsProtocol)
2910 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002911 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002912 // The RHS implements all protocols listed on the LHS.
2913 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002914}
2915
Steve Naroff389bf462009-02-12 17:52:19 +00002916bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2917 // get the "pointed to" types
2918 const PointerType *LHSPT = LHS->getAsPointerType();
2919 const PointerType *RHSPT = RHS->getAsPointerType();
2920
2921 if (!LHSPT || !RHSPT)
2922 return false;
2923
2924 QualType lhptee = LHSPT->getPointeeType();
2925 QualType rhptee = RHSPT->getPointeeType();
2926 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2927 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2928 // ID acts sort of like void* for ObjC interfaces
2929 if (LHSIface && isObjCIdStructType(rhptee))
2930 return true;
2931 if (RHSIface && isObjCIdStructType(lhptee))
2932 return true;
2933 if (!LHSIface || !RHSIface)
2934 return false;
2935 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2936 canAssignObjCInterfaces(RHSIface, LHSIface);
2937}
2938
Steve Naroffec0550f2007-10-15 20:41:53 +00002939/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2940/// both shall have the identically qualified version of a compatible type.
2941/// C99 6.2.7p1: Two types have compatible types if their types are the
2942/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002943bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2944 return !mergeTypes(LHS, RHS).isNull();
2945}
2946
2947QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2948 const FunctionType *lbase = lhs->getAsFunctionType();
2949 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002950 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2951 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00002952 bool allLTypes = true;
2953 bool allRTypes = true;
2954
2955 // Check return type
2956 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2957 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00002958 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2959 allLTypes = false;
2960 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2961 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002962
2963 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00002964 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
2965 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00002966 unsigned lproto_nargs = lproto->getNumArgs();
2967 unsigned rproto_nargs = rproto->getNumArgs();
2968
2969 // Compatible functions must have the same number of arguments
2970 if (lproto_nargs != rproto_nargs)
2971 return QualType();
2972
2973 // Variadic and non-variadic functions aren't compatible
2974 if (lproto->isVariadic() != rproto->isVariadic())
2975 return QualType();
2976
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002977 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2978 return QualType();
2979
Eli Friedman3d815e72008-08-22 00:56:42 +00002980 // Check argument compatibility
2981 llvm::SmallVector<QualType, 10> types;
2982 for (unsigned i = 0; i < lproto_nargs; i++) {
2983 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2984 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2985 QualType argtype = mergeTypes(largtype, rargtype);
2986 if (argtype.isNull()) return QualType();
2987 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00002988 if (getCanonicalType(argtype) != getCanonicalType(largtype))
2989 allLTypes = false;
2990 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2991 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002992 }
2993 if (allLTypes) return lhs;
2994 if (allRTypes) return rhs;
2995 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002996 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00002997 }
2998
2999 if (lproto) allRTypes = false;
3000 if (rproto) allLTypes = false;
3001
Douglas Gregor72564e72009-02-26 23:50:07 +00003002 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003003 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003004 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003005 if (proto->isVariadic()) return QualType();
3006 // Check that the types are compatible with the types that
3007 // would result from default argument promotions (C99 6.7.5.3p15).
3008 // The only types actually affected are promotable integer
3009 // types and floats, which would be passed as a different
3010 // type depending on whether the prototype is visible.
3011 unsigned proto_nargs = proto->getNumArgs();
3012 for (unsigned i = 0; i < proto_nargs; ++i) {
3013 QualType argTy = proto->getArgType(i);
3014 if (argTy->isPromotableIntegerType() ||
3015 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3016 return QualType();
3017 }
3018
3019 if (allLTypes) return lhs;
3020 if (allRTypes) return rhs;
3021 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003022 proto->getNumArgs(), lproto->isVariadic(),
3023 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003024 }
3025
3026 if (allLTypes) return lhs;
3027 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003028 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003029}
3030
3031QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003032 // C++ [expr]: If an expression initially has the type "reference to T", the
3033 // type is adjusted to "T" prior to any further analysis, the expression
3034 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003035 // expression is an lvalue unless the reference is an rvalue reference and
3036 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003037 // FIXME: C++ shouldn't be going through here! The rules are different
3038 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003039 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3040 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003041 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003042 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003043 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003044 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003045
Eli Friedman3d815e72008-08-22 00:56:42 +00003046 QualType LHSCan = getCanonicalType(LHS),
3047 RHSCan = getCanonicalType(RHS);
3048
3049 // If two types are identical, they are compatible.
3050 if (LHSCan == RHSCan)
3051 return LHS;
3052
3053 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003054 // Note that we handle extended qualifiers later, in the
3055 // case for ExtQualType.
3056 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003057 return QualType();
3058
Eli Friedman852d63b2009-06-01 01:22:52 +00003059 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3060 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003061
Chris Lattner1adb8832008-01-14 05:45:46 +00003062 // We want to consider the two function types to be the same for these
3063 // comparisons, just force one to the other.
3064 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3065 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003066
Eli Friedman07d25872009-06-02 05:28:56 +00003067 // Strip off objc_gc attributes off the top level so they can be merged.
3068 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003069 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003070 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3071 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003072 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003073 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003074 // __strong attribue is redundant if other decl is an objective-c
3075 // object pointer (or decorated with __strong attribute); otherwise
3076 // issue error.
3077 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3078 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3079 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3080 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003081 return QualType();
3082
Eli Friedman07d25872009-06-02 05:28:56 +00003083 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3084 RHS.getCVRQualifiers());
3085 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003086 if (!Result.isNull()) {
3087 if (Result.getObjCGCAttr() == QualType::GCNone)
3088 Result = getObjCGCQualType(Result, GCAttr);
3089 else if (Result.getObjCGCAttr() != GCAttr)
3090 Result = QualType();
3091 }
Eli Friedman07d25872009-06-02 05:28:56 +00003092 return Result;
3093 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003094 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003095 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003096 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3097 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003098 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3099 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003100 // __strong attribue is redundant if other decl is an objective-c
3101 // object pointer (or decorated with __strong attribute); otherwise
3102 // issue error.
3103 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3104 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3105 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3106 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003107 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003108
Eli Friedman07d25872009-06-02 05:28:56 +00003109 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3110 LHS.getCVRQualifiers());
3111 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003112 if (!Result.isNull()) {
3113 if (Result.getObjCGCAttr() == QualType::GCNone)
3114 Result = getObjCGCQualType(Result, GCAttr);
3115 else if (Result.getObjCGCAttr() != GCAttr)
3116 Result = QualType();
3117 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003118 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003119 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003120 }
3121
Eli Friedman4c721d32008-02-12 08:23:06 +00003122 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003123 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3124 LHSClass = Type::ConstantArray;
3125 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3126 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003127
Nate Begeman213541a2008-04-18 23:10:10 +00003128 // Canonicalize ExtVector -> Vector.
3129 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3130 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003131
Chris Lattnerb0489812008-04-07 06:38:24 +00003132 // Consider qualified interfaces and interfaces the same.
3133 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3134 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003135
Chris Lattnera36a61f2008-04-07 05:43:21 +00003136 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003137 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003138 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3139 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003140
Steve Naroffd824c9c2009-04-14 15:11:46 +00003141 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3142 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003143 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003144 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003145 return RHS;
3146
Steve Naroffbc76dd02008-12-10 22:14:21 +00003147 // ID is compatible with all qualified id types.
3148 if (LHS->isObjCQualifiedIdType()) {
3149 if (const PointerType *PT = RHS->getAsPointerType()) {
3150 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003151 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003152 return LHS;
3153 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3154 // Unfortunately, this API is part of Sema (which we don't have access
3155 // to. Need to refactor. The following check is insufficient, since we
3156 // need to make sure the class implements the protocol.
3157 if (pType->isObjCInterfaceType())
3158 return LHS;
3159 }
3160 }
3161 if (RHS->isObjCQualifiedIdType()) {
3162 if (const PointerType *PT = LHS->getAsPointerType()) {
3163 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003164 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003165 return RHS;
3166 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3167 // Unfortunately, this API is part of Sema (which we don't have access
3168 // to. Need to refactor. The following check is insufficient, since we
3169 // need to make sure the class implements the protocol.
3170 if (pType->isObjCInterfaceType())
3171 return RHS;
3172 }
3173 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003174 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3175 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003176 if (const EnumType* ETy = LHS->getAsEnumType()) {
3177 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3178 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003179 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003180 if (const EnumType* ETy = RHS->getAsEnumType()) {
3181 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3182 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003183 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003184
Eli Friedman3d815e72008-08-22 00:56:42 +00003185 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003186 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003187
Steve Naroff4a746782008-01-09 22:43:08 +00003188 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003189 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003190#define TYPE(Class, Base)
3191#define ABSTRACT_TYPE(Class, Base)
3192#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3193#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3194#include "clang/AST/TypeNodes.def"
3195 assert(false && "Non-canonical and dependent types shouldn't get here");
3196 return QualType();
3197
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003198 case Type::LValueReference:
3199 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003200 case Type::MemberPointer:
3201 assert(false && "C++ should never be in mergeTypes");
3202 return QualType();
3203
3204 case Type::IncompleteArray:
3205 case Type::VariableArray:
3206 case Type::FunctionProto:
3207 case Type::ExtVector:
3208 case Type::ObjCQualifiedInterface:
3209 assert(false && "Types are eliminated above");
3210 return QualType();
3211
Chris Lattner1adb8832008-01-14 05:45:46 +00003212 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003213 {
3214 // Merge two pointer types, while trying to preserve typedef info
3215 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3216 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3217 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3218 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003219 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003220 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003221 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003222 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003223 return getPointerType(ResultType);
3224 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003225 case Type::BlockPointer:
3226 {
3227 // Merge two block pointer types, while trying to preserve typedef info
3228 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3229 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3230 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3231 if (ResultType.isNull()) return QualType();
3232 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3233 return LHS;
3234 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3235 return RHS;
3236 return getBlockPointerType(ResultType);
3237 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003238 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003239 {
3240 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3241 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3242 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3243 return QualType();
3244
3245 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3246 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3247 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3248 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003249 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3250 return LHS;
3251 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3252 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003253 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3254 ArrayType::ArraySizeModifier(), 0);
3255 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3256 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003257 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3258 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003259 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3260 return LHS;
3261 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3262 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003263 if (LVAT) {
3264 // FIXME: This isn't correct! But tricky to implement because
3265 // the array's size has to be the size of LHS, but the type
3266 // has to be different.
3267 return LHS;
3268 }
3269 if (RVAT) {
3270 // FIXME: This isn't correct! But tricky to implement because
3271 // the array's size has to be the size of RHS, but the type
3272 // has to be different.
3273 return RHS;
3274 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003275 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3276 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003277 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003278 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003279 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003280 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003281 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003282 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003283 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003284 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3285 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003286 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003287 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003288 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003289 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003290 case Type::Complex:
3291 // Distinct complex types are incompatible.
3292 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003293 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003294 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003295 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3296 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003297 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003298 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003299 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003300 // FIXME: This should be type compatibility, e.g. whether
3301 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003302 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3303 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3304 if (LHSIface && RHSIface &&
3305 canAssignObjCInterfaces(LHSIface, RHSIface))
3306 return LHS;
3307
Eli Friedman3d815e72008-08-22 00:56:42 +00003308 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003309 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003310 case Type::ObjCObjectPointer:
3311 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003312 // Distinct qualified id's are not compatible.
3313 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003314 case Type::FixedWidthInt:
3315 // Distinct fixed-width integers are not compatible.
3316 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003317 case Type::ExtQual:
3318 // FIXME: ExtQual types can be compatible even if they're not
3319 // identical!
3320 return QualType();
3321 // First attempt at an implementation, but I'm not really sure it's
3322 // right...
3323#if 0
3324 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3325 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3326 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3327 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3328 return QualType();
3329 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3330 LHSBase = QualType(LQual->getBaseType(), 0);
3331 RHSBase = QualType(RQual->getBaseType(), 0);
3332 ResultType = mergeTypes(LHSBase, RHSBase);
3333 if (ResultType.isNull()) return QualType();
3334 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3335 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3336 return LHS;
3337 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3338 return RHS;
3339 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3340 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3341 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3342 return ResultType;
3343#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003344
3345 case Type::TemplateSpecialization:
3346 assert(false && "Dependent types have no size");
3347 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003348 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003349
3350 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003351}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003352
Chris Lattner5426bf62008-04-07 07:01:58 +00003353//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003354// Integer Predicates
3355//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003356
Eli Friedmanad74a752008-06-28 06:23:08 +00003357unsigned ASTContext::getIntWidth(QualType T) {
3358 if (T == BoolTy)
3359 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003360 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3361 return FWIT->getWidth();
3362 }
3363 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003364 return (unsigned)getTypeSize(T);
3365}
3366
3367QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3368 assert(T->isSignedIntegerType() && "Unexpected type");
3369 if (const EnumType* ETy = T->getAsEnumType())
3370 T = ETy->getDecl()->getIntegerType();
3371 const BuiltinType* BTy = T->getAsBuiltinType();
3372 assert (BTy && "Unexpected signed integer type");
3373 switch (BTy->getKind()) {
3374 case BuiltinType::Char_S:
3375 case BuiltinType::SChar:
3376 return UnsignedCharTy;
3377 case BuiltinType::Short:
3378 return UnsignedShortTy;
3379 case BuiltinType::Int:
3380 return UnsignedIntTy;
3381 case BuiltinType::Long:
3382 return UnsignedLongTy;
3383 case BuiltinType::LongLong:
3384 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003385 case BuiltinType::Int128:
3386 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003387 default:
3388 assert(0 && "Unexpected signed integer type");
3389 return QualType();
3390 }
3391}
3392
Douglas Gregor2cf26342009-04-09 22:27:44 +00003393ExternalASTSource::~ExternalASTSource() { }
3394
3395void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003396
3397
3398//===----------------------------------------------------------------------===//
3399// Builtin Type Computation
3400//===----------------------------------------------------------------------===//
3401
3402/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3403/// pointer over the consumed characters. This returns the resultant type.
3404static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3405 ASTContext::GetBuiltinTypeError &Error,
3406 bool AllowTypeModifiers = true) {
3407 // Modifiers.
3408 int HowLong = 0;
3409 bool Signed = false, Unsigned = false;
3410
3411 // Read the modifiers first.
3412 bool Done = false;
3413 while (!Done) {
3414 switch (*Str++) {
3415 default: Done = true; --Str; break;
3416 case 'S':
3417 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3418 assert(!Signed && "Can't use 'S' modifier multiple times!");
3419 Signed = true;
3420 break;
3421 case 'U':
3422 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3423 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3424 Unsigned = true;
3425 break;
3426 case 'L':
3427 assert(HowLong <= 2 && "Can't have LLLL modifier");
3428 ++HowLong;
3429 break;
3430 }
3431 }
3432
3433 QualType Type;
3434
3435 // Read the base type.
3436 switch (*Str++) {
3437 default: assert(0 && "Unknown builtin type letter!");
3438 case 'v':
3439 assert(HowLong == 0 && !Signed && !Unsigned &&
3440 "Bad modifiers used with 'v'!");
3441 Type = Context.VoidTy;
3442 break;
3443 case 'f':
3444 assert(HowLong == 0 && !Signed && !Unsigned &&
3445 "Bad modifiers used with 'f'!");
3446 Type = Context.FloatTy;
3447 break;
3448 case 'd':
3449 assert(HowLong < 2 && !Signed && !Unsigned &&
3450 "Bad modifiers used with 'd'!");
3451 if (HowLong)
3452 Type = Context.LongDoubleTy;
3453 else
3454 Type = Context.DoubleTy;
3455 break;
3456 case 's':
3457 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3458 if (Unsigned)
3459 Type = Context.UnsignedShortTy;
3460 else
3461 Type = Context.ShortTy;
3462 break;
3463 case 'i':
3464 if (HowLong == 3)
3465 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3466 else if (HowLong == 2)
3467 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3468 else if (HowLong == 1)
3469 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3470 else
3471 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3472 break;
3473 case 'c':
3474 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3475 if (Signed)
3476 Type = Context.SignedCharTy;
3477 else if (Unsigned)
3478 Type = Context.UnsignedCharTy;
3479 else
3480 Type = Context.CharTy;
3481 break;
3482 case 'b': // boolean
3483 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3484 Type = Context.BoolTy;
3485 break;
3486 case 'z': // size_t.
3487 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3488 Type = Context.getSizeType();
3489 break;
3490 case 'F':
3491 Type = Context.getCFConstantStringType();
3492 break;
3493 case 'a':
3494 Type = Context.getBuiltinVaListType();
3495 assert(!Type.isNull() && "builtin va list type not initialized!");
3496 break;
3497 case 'A':
3498 // This is a "reference" to a va_list; however, what exactly
3499 // this means depends on how va_list is defined. There are two
3500 // different kinds of va_list: ones passed by value, and ones
3501 // passed by reference. An example of a by-value va_list is
3502 // x86, where va_list is a char*. An example of by-ref va_list
3503 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3504 // we want this argument to be a char*&; for x86-64, we want
3505 // it to be a __va_list_tag*.
3506 Type = Context.getBuiltinVaListType();
3507 assert(!Type.isNull() && "builtin va list type not initialized!");
3508 if (Type->isArrayType()) {
3509 Type = Context.getArrayDecayedType(Type);
3510 } else {
3511 Type = Context.getLValueReferenceType(Type);
3512 }
3513 break;
3514 case 'V': {
3515 char *End;
3516
3517 unsigned NumElements = strtoul(Str, &End, 10);
3518 assert(End != Str && "Missing vector size");
3519
3520 Str = End;
3521
3522 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3523 Type = Context.getVectorType(ElementType, NumElements);
3524 break;
3525 }
3526 case 'P': {
3527 IdentifierInfo *II = &Context.Idents.get("FILE");
3528 DeclContext::lookup_result Lookup
3529 = Context.getTranslationUnitDecl()->lookup(Context, II);
3530 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3531 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3532 break;
3533 }
3534 else {
3535 Error = ASTContext::GE_Missing_FILE;
3536 return QualType();
3537 }
3538 }
3539 }
3540
3541 if (!AllowTypeModifiers)
3542 return Type;
3543
3544 Done = false;
3545 while (!Done) {
3546 switch (*Str++) {
3547 default: Done = true; --Str; break;
3548 case '*':
3549 Type = Context.getPointerType(Type);
3550 break;
3551 case '&':
3552 Type = Context.getLValueReferenceType(Type);
3553 break;
3554 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3555 case 'C':
3556 Type = Type.getQualifiedType(QualType::Const);
3557 break;
3558 }
3559 }
3560
3561 return Type;
3562}
3563
3564/// GetBuiltinType - Return the type for the specified builtin.
3565QualType ASTContext::GetBuiltinType(unsigned id,
3566 GetBuiltinTypeError &Error) {
3567 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3568
3569 llvm::SmallVector<QualType, 8> ArgTypes;
3570
3571 Error = GE_None;
3572 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3573 if (Error != GE_None)
3574 return QualType();
3575 while (TypeStr[0] && TypeStr[0] != '.') {
3576 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3577 if (Error != GE_None)
3578 return QualType();
3579
3580 // Do array -> pointer decay. The builtin should use the decayed type.
3581 if (Ty->isArrayType())
3582 Ty = getArrayDecayedType(Ty);
3583
3584 ArgTypes.push_back(Ty);
3585 }
3586
3587 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3588 "'.' should only occur at end of builtin type list!");
3589
3590 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3591 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3592 return getFunctionNoProtoType(ResType);
3593 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3594 TypeStr[0] == '.', 0);
3595}