blob: d97d2155c0470a4c70fa1225084ef1cbac933b15 [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));
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000372 case Type::ObjCQualifiedId:
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 Gregor72564e72009-02-26 23:50:07 +00001272/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001273///
Douglas Gregor72564e72009-02-26 23:50:07 +00001274QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 // Unique functions, to guarantee there is only one function of a particular
1276 // structure.
1277 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001278 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001279
1280 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001281 if (FunctionNoProtoType *FT =
1282 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 return QualType(FT, 0);
1284
1285 QualType Canonical;
1286 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001287 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001288
1289 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001290 FunctionNoProtoType *NewIP =
1291 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001292 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 }
1294
Douglas Gregor72564e72009-02-26 23:50:07 +00001295 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001297 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 return QualType(New, 0);
1299}
1300
1301/// getFunctionType - Return a normal function type with a typed argument
1302/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001303QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001304 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001305 unsigned TypeQuals, bool hasExceptionSpec,
1306 bool hasAnyExceptionSpec, unsigned NumExs,
1307 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 // Unique functions, to guarantee there is only one function of a particular
1309 // structure.
1310 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001311 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001312 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1313 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314
1315 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001316 if (FunctionProtoType *FTP =
1317 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001319
1320 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001322 if (hasExceptionSpec)
1323 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1325 if (!ArgArray[i]->isCanonical())
1326 isCanonical = false;
1327
1328 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001329 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 QualType Canonical;
1331 if (!isCanonical) {
1332 llvm::SmallVector<QualType, 16> CanonicalArgs;
1333 CanonicalArgs.reserve(NumArgs);
1334 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001335 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001336
Chris Lattnerf52ab252008-04-06 22:59:24 +00001337 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001338 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001339 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001340
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001342 FunctionProtoType *NewIP =
1343 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001344 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001346
Douglas Gregor72564e72009-02-26 23:50:07 +00001347 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001348 // for two variable size arrays (for parameter and exception types) at the
1349 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001350 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001351 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1352 NumArgs*sizeof(QualType) +
1353 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001354 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001355 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1356 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001358 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 return QualType(FTP, 0);
1360}
1361
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001362/// getTypeDeclType - Return the unique reference to the type for the
1363/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001364QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001365 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001366 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1367
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001368 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001369 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001370 else if (isa<TemplateTypeParmDecl>(Decl)) {
1371 assert(false && "Template type parameter types are always available.");
1372 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001373 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001374
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001375 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001376 if (PrevDecl)
1377 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001378 else
1379 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001380 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001381 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1382 if (PrevDecl)
1383 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001384 else
1385 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001386 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001387 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001388 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001389
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001390 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001391 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001392}
1393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394/// getTypedefType - Return the unique reference to the type for the
1395/// specified typename decl.
1396QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1397 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1398
Chris Lattnerf52ab252008-04-06 22:59:24 +00001399 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001400 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 Types.push_back(Decl->TypeForDecl);
1402 return QualType(Decl->TypeForDecl, 0);
1403}
1404
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001405/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001406/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001407QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001408 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1409
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001410 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1411 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001412 Types.push_back(Decl->TypeForDecl);
1413 return QualType(Decl->TypeForDecl, 0);
1414}
1415
Douglas Gregorfab9d672009-02-05 23:33:38 +00001416/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001417/// parameter or parameter pack with the given depth, index, and (optionally)
1418/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001419QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001420 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001421 IdentifierInfo *Name) {
1422 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001423 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001424 void *InsertPos = 0;
1425 TemplateTypeParmType *TypeParm
1426 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1427
1428 if (TypeParm)
1429 return QualType(TypeParm, 0);
1430
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001431 if (Name) {
1432 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1433 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1434 Name, Canon);
1435 } else
1436 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001437
1438 Types.push_back(TypeParm);
1439 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1440
1441 return QualType(TypeParm, 0);
1442}
1443
Douglas Gregor55f6b142009-02-09 18:46:07 +00001444QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001445ASTContext::getTemplateSpecializationType(TemplateName Template,
1446 const TemplateArgument *Args,
1447 unsigned NumArgs,
1448 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001449 if (!Canon.isNull())
1450 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001451
Douglas Gregor55f6b142009-02-09 18:46:07 +00001452 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001453 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001454
Douglas Gregor55f6b142009-02-09 18:46:07 +00001455 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001456 TemplateSpecializationType *Spec
1457 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001458
1459 if (Spec)
1460 return QualType(Spec, 0);
1461
Douglas Gregor7532dc62009-03-30 22:58:21 +00001462 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001463 sizeof(TemplateArgument) * NumArgs),
1464 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001465 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001466 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001467 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001468
1469 return QualType(Spec, 0);
1470}
1471
Douglas Gregore4e5b052009-03-19 00:18:19 +00001472QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001473ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001474 QualType NamedType) {
1475 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001476 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001477
1478 void *InsertPos = 0;
1479 QualifiedNameType *T
1480 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1481 if (T)
1482 return QualType(T, 0);
1483
Douglas Gregorab452ba2009-03-26 23:50:42 +00001484 T = new (*this) QualifiedNameType(NNS, NamedType,
1485 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001486 Types.push_back(T);
1487 QualifiedNameTypes.InsertNode(T, InsertPos);
1488 return QualType(T, 0);
1489}
1490
Douglas Gregord57959a2009-03-27 23:10:48 +00001491QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1492 const IdentifierInfo *Name,
1493 QualType Canon) {
1494 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1495
1496 if (Canon.isNull()) {
1497 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1498 if (CanonNNS != NNS)
1499 Canon = getTypenameType(CanonNNS, Name);
1500 }
1501
1502 llvm::FoldingSetNodeID ID;
1503 TypenameType::Profile(ID, NNS, Name);
1504
1505 void *InsertPos = 0;
1506 TypenameType *T
1507 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1508 if (T)
1509 return QualType(T, 0);
1510
1511 T = new (*this) TypenameType(NNS, Name, Canon);
1512 Types.push_back(T);
1513 TypenameTypes.InsertNode(T, InsertPos);
1514 return QualType(T, 0);
1515}
1516
Douglas Gregor17343172009-04-01 00:28:59 +00001517QualType
1518ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1519 const TemplateSpecializationType *TemplateId,
1520 QualType Canon) {
1521 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1522
1523 if (Canon.isNull()) {
1524 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1525 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1526 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1527 const TemplateSpecializationType *CanonTemplateId
1528 = CanonType->getAsTemplateSpecializationType();
1529 assert(CanonTemplateId &&
1530 "Canonical type must also be a template specialization type");
1531 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1532 }
1533 }
1534
1535 llvm::FoldingSetNodeID ID;
1536 TypenameType::Profile(ID, NNS, TemplateId);
1537
1538 void *InsertPos = 0;
1539 TypenameType *T
1540 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1541 if (T)
1542 return QualType(T, 0);
1543
1544 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1545 Types.push_back(T);
1546 TypenameTypes.InsertNode(T, InsertPos);
1547 return QualType(T, 0);
1548}
1549
Chris Lattner88cb27a2008-04-07 04:56:42 +00001550/// CmpProtocolNames - Comparison predicate for sorting protocols
1551/// alphabetically.
1552static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1553 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001554 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001555}
1556
1557static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1558 unsigned &NumProtocols) {
1559 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1560
1561 // Sort protocols, keyed by name.
1562 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1563
1564 // Remove duplicates.
1565 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1566 NumProtocols = ProtocolsEnd-Protocols;
1567}
1568
1569
Chris Lattner065f0d72008-04-07 04:44:08 +00001570/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1571/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001572QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1573 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001574 // Sort the protocol list alphabetically to canonicalize it.
1575 SortAndUniqueProtocols(Protocols, NumProtocols);
1576
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001577 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001578 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001579
1580 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001581 if (ObjCQualifiedInterfaceType *QT =
1582 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001583 return QualType(QT, 0);
1584
1585 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001586 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001587 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001588
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001589 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001590 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001591 return QualType(QType, 0);
1592}
1593
Chris Lattner88cb27a2008-04-07 04:56:42 +00001594/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1595/// and the conforming protocol list.
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001596QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001597 unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001598 // Sort the protocol list alphabetically to canonicalize it.
1599 SortAndUniqueProtocols(Protocols, NumProtocols);
1600
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001601 llvm::FoldingSetNodeID ID;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001602 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001603
1604 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001605 if (ObjCQualifiedIdType *QT =
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001606 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001607 return QualType(QT, 0);
1608
1609 // No Match;
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001610 ObjCQualifiedIdType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001611 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001612 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001613 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001614 return QualType(QType, 0);
1615}
1616
Douglas Gregor72564e72009-02-26 23:50:07 +00001617/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1618/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001619/// multiple declarations that refer to "typeof(x)" all contain different
1620/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1621/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001622QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001623 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001624 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001625 Types.push_back(toe);
1626 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001627}
1628
Steve Naroff9752f252007-08-01 18:02:17 +00001629/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1630/// TypeOfType AST's. The only motivation to unique these nodes would be
1631/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1632/// an issue. This doesn't effect the type checker, since it operates
1633/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001634QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001635 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001636 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001637 Types.push_back(tot);
1638 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001639}
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641/// getTagDeclType - Return the unique reference to the type for the
1642/// specified TagDecl (struct/union/class/enum) decl.
1643QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001644 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001645 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001646}
1647
1648/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1649/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1650/// needs to agree with the definition in <stddef.h>.
1651QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001652 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001653}
1654
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001655/// getSignedWCharType - Return the type of "signed wchar_t".
1656/// Used when in C++, as a GCC extension.
1657QualType ASTContext::getSignedWCharType() const {
1658 // FIXME: derive from "Target" ?
1659 return WCharTy;
1660}
1661
1662/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1663/// Used when in C++, as a GCC extension.
1664QualType ASTContext::getUnsignedWCharType() const {
1665 // FIXME: derive from "Target" ?
1666 return UnsignedIntTy;
1667}
1668
Chris Lattner8b9023b2007-07-13 03:05:23 +00001669/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1670/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1671QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001672 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001673}
1674
Chris Lattnere6327742008-04-02 05:18:44 +00001675//===----------------------------------------------------------------------===//
1676// Type Operators
1677//===----------------------------------------------------------------------===//
1678
Chris Lattner77c96472008-04-06 22:41:35 +00001679/// getCanonicalType - Return the canonical (structural) type corresponding to
1680/// the specified potentially non-canonical type. The non-canonical version
1681/// of a type may have many "decorated" versions of types. Decorators can
1682/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1683/// to be free of any of these, allowing two canonical types to be compared
1684/// for exact equality with a simple pointer comparison.
1685QualType ASTContext::getCanonicalType(QualType T) {
1686 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001687
1688 // If the result has type qualifiers, make sure to canonicalize them as well.
1689 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1690 if (TypeQuals == 0) return CanType;
1691
1692 // If the type qualifiers are on an array type, get the canonical type of the
1693 // array with the qualifiers applied to the element type.
1694 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1695 if (!AT)
1696 return CanType.getQualifiedType(TypeQuals);
1697
1698 // Get the canonical version of the element with the extra qualifiers on it.
1699 // This can recursively sink qualifiers through multiple levels of arrays.
1700 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1701 NewEltTy = getCanonicalType(NewEltTy);
1702
1703 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1704 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1705 CAT->getIndexTypeQualifier());
1706 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1707 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1708 IAT->getIndexTypeQualifier());
1709
Douglas Gregor898574e2008-12-05 23:32:09 +00001710 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1711 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1712 DSAT->getSizeModifier(),
1713 DSAT->getIndexTypeQualifier());
1714
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001715 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1716 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1717 VAT->getSizeModifier(),
1718 VAT->getIndexTypeQualifier());
1719}
1720
Douglas Gregor7da97d02009-05-10 22:57:19 +00001721Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001722 if (!D)
1723 return 0;
1724
Douglas Gregor7da97d02009-05-10 22:57:19 +00001725 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1726 QualType T = getTagDeclType(Tag);
1727 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1728 ->getDecl());
1729 }
1730
1731 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1732 while (Template->getPreviousDeclaration())
1733 Template = Template->getPreviousDeclaration();
1734 return Template;
1735 }
1736
1737 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1738 while (Function->getPreviousDeclaration())
1739 Function = Function->getPreviousDeclaration();
1740 return const_cast<FunctionDecl *>(Function);
1741 }
1742
1743 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1744 while (Var->getPreviousDeclaration())
1745 Var = Var->getPreviousDeclaration();
1746 return const_cast<VarDecl *>(Var);
1747 }
1748
1749 return D;
1750}
1751
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001752TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1753 // If this template name refers to a template, the canonical
1754 // template name merely stores the template itself.
1755 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001756 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001757
1758 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1759 assert(DTN && "Non-dependent template names must refer to template decls.");
1760 return DTN->CanonicalTemplateName;
1761}
1762
Douglas Gregord57959a2009-03-27 23:10:48 +00001763NestedNameSpecifier *
1764ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1765 if (!NNS)
1766 return 0;
1767
1768 switch (NNS->getKind()) {
1769 case NestedNameSpecifier::Identifier:
1770 // Canonicalize the prefix but keep the identifier the same.
1771 return NestedNameSpecifier::Create(*this,
1772 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1773 NNS->getAsIdentifier());
1774
1775 case NestedNameSpecifier::Namespace:
1776 // A namespace is canonical; build a nested-name-specifier with
1777 // this namespace and no prefix.
1778 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1779
1780 case NestedNameSpecifier::TypeSpec:
1781 case NestedNameSpecifier::TypeSpecWithTemplate: {
1782 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1783 NestedNameSpecifier *Prefix = 0;
1784
1785 // FIXME: This isn't the right check!
1786 if (T->isDependentType())
1787 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1788
1789 return NestedNameSpecifier::Create(*this, Prefix,
1790 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1791 T.getTypePtr());
1792 }
1793
1794 case NestedNameSpecifier::Global:
1795 // The global specifier is canonical and unique.
1796 return NNS;
1797 }
1798
1799 // Required to silence a GCC warning
1800 return 0;
1801}
1802
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001803
1804const ArrayType *ASTContext::getAsArrayType(QualType T) {
1805 // Handle the non-qualified case efficiently.
1806 if (T.getCVRQualifiers() == 0) {
1807 // Handle the common positive case fast.
1808 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1809 return AT;
1810 }
1811
1812 // Handle the common negative case fast, ignoring CVR qualifiers.
1813 QualType CType = T->getCanonicalTypeInternal();
1814
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001815 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001816 // test.
1817 if (!isa<ArrayType>(CType) &&
1818 !isa<ArrayType>(CType.getUnqualifiedType()))
1819 return 0;
1820
1821 // Apply any CVR qualifiers from the array type to the element type. This
1822 // implements C99 6.7.3p8: "If the specification of an array type includes
1823 // any type qualifiers, the element type is so qualified, not the array type."
1824
1825 // If we get here, we either have type qualifiers on the type, or we have
1826 // sugar such as a typedef in the way. If we have type qualifiers on the type
1827 // we must propagate them down into the elemeng type.
1828 unsigned CVRQuals = T.getCVRQualifiers();
1829 unsigned AddrSpace = 0;
1830 Type *Ty = T.getTypePtr();
1831
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001832 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001833 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001834 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1835 AddrSpace = EXTQT->getAddressSpace();
1836 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001837 } else {
1838 T = Ty->getDesugaredType();
1839 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1840 break;
1841 CVRQuals |= T.getCVRQualifiers();
1842 Ty = T.getTypePtr();
1843 }
1844 }
1845
1846 // If we have a simple case, just return now.
1847 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1848 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1849 return ATy;
1850
1851 // Otherwise, we have an array and we have qualifiers on it. Push the
1852 // qualifiers into the array element type and return a new array type.
1853 // Get the canonical version of the element with the extra qualifiers on it.
1854 // This can recursively sink qualifiers through multiple levels of arrays.
1855 QualType NewEltTy = ATy->getElementType();
1856 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001857 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001858 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1859
1860 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1861 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1862 CAT->getSizeModifier(),
1863 CAT->getIndexTypeQualifier()));
1864 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1865 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1866 IAT->getSizeModifier(),
1867 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001868
Douglas Gregor898574e2008-12-05 23:32:09 +00001869 if (const DependentSizedArrayType *DSAT
1870 = dyn_cast<DependentSizedArrayType>(ATy))
1871 return cast<ArrayType>(
1872 getDependentSizedArrayType(NewEltTy,
1873 DSAT->getSizeExpr(),
1874 DSAT->getSizeModifier(),
1875 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001876
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001877 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1878 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1879 VAT->getSizeModifier(),
1880 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001881}
1882
1883
Chris Lattnere6327742008-04-02 05:18:44 +00001884/// getArrayDecayedType - Return the properly qualified result of decaying the
1885/// specified array type to a pointer. This operation is non-trivial when
1886/// handling typedefs etc. The canonical type of "T" must be an array type,
1887/// this returns a pointer to a properly qualified element of the array.
1888///
1889/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1890QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001891 // Get the element type with 'getAsArrayType' so that we don't lose any
1892 // typedefs in the element type of the array. This also handles propagation
1893 // of type qualifiers from the array type into the element type if present
1894 // (C99 6.7.3p8).
1895 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1896 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001897
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001898 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001899
1900 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001901 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001902}
1903
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001904QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001905 QualType ElemTy = VAT->getElementType();
1906
1907 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1908 return getBaseElementType(VAT);
1909
1910 return ElemTy;
1911}
1912
Reid Spencer5f016e22007-07-11 17:01:13 +00001913/// getFloatingRank - Return a relative rank for floating point types.
1914/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001915static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001916 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001918
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001919 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001920 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001921 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 case BuiltinType::Float: return FloatRank;
1923 case BuiltinType::Double: return DoubleRank;
1924 case BuiltinType::LongDouble: return LongDoubleRank;
1925 }
1926}
1927
Steve Naroff716c7302007-08-27 01:41:48 +00001928/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1929/// point or a complex type (based on typeDomain/typeSize).
1930/// 'typeDomain' is a real floating point or complex type.
1931/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00001932QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1933 QualType Domain) const {
1934 FloatingRank EltRank = getFloatingRank(Size);
1935 if (Domain->isComplexType()) {
1936 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00001937 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00001938 case FloatRank: return FloatComplexTy;
1939 case DoubleRank: return DoubleComplexTy;
1940 case LongDoubleRank: return LongDoubleComplexTy;
1941 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 }
Chris Lattner1361b112008-04-06 23:58:54 +00001943
1944 assert(Domain->isRealFloatingType() && "Unknown domain!");
1945 switch (EltRank) {
1946 default: assert(0 && "getFloatingRank(): illegal value for rank");
1947 case FloatRank: return FloatTy;
1948 case DoubleRank: return DoubleTy;
1949 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00001950 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001951}
1952
Chris Lattner7cfeb082008-04-06 23:55:33 +00001953/// getFloatingTypeOrder - Compare the rank of the two specified floating
1954/// point types, ignoring the domain of the type (i.e. 'double' ==
1955/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1956/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00001957int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1958 FloatingRank LHSR = getFloatingRank(LHS);
1959 FloatingRank RHSR = getFloatingRank(RHS);
1960
1961 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001962 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00001963 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001964 return 1;
1965 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001966}
1967
Chris Lattnerf52ab252008-04-06 22:59:24 +00001968/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1969/// routine will assert if passed a built-in type that isn't an integer or enum,
1970/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00001971unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001972 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00001973 if (EnumType* ET = dyn_cast<EnumType>(T))
1974 T = ET->getDecl()->getIntegerType().getTypePtr();
1975
1976 // There are two things which impact the integer rank: the width, and
1977 // the ordering of builtins. The builtin ordering is encoded in the
1978 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001979 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00001980 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00001981
Chris Lattnerf52ab252008-04-06 22:59:24 +00001982 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00001983 default: assert(0 && "getIntegerRank(): not a built-in integer");
1984 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001985 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001986 case BuiltinType::Char_S:
1987 case BuiltinType::Char_U:
1988 case BuiltinType::SChar:
1989 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001990 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001991 case BuiltinType::Short:
1992 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001993 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001994 case BuiltinType::Int:
1995 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001996 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001997 case BuiltinType::Long:
1998 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001999 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002000 case BuiltinType::LongLong:
2001 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002002 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002003 case BuiltinType::Int128:
2004 case BuiltinType::UInt128:
2005 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002006 }
2007}
2008
Chris Lattner7cfeb082008-04-06 23:55:33 +00002009/// getIntegerTypeOrder - Returns the highest ranked integer type:
2010/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2011/// LHS < RHS, return -1.
2012int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002013 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2014 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002015 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002016
Chris Lattnerf52ab252008-04-06 22:59:24 +00002017 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2018 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002019
Chris Lattner7cfeb082008-04-06 23:55:33 +00002020 unsigned LHSRank = getIntegerRank(LHSC);
2021 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002022
Chris Lattner7cfeb082008-04-06 23:55:33 +00002023 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2024 if (LHSRank == RHSRank) return 0;
2025 return LHSRank > RHSRank ? 1 : -1;
2026 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002027
Chris Lattner7cfeb082008-04-06 23:55:33 +00002028 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2029 if (LHSUnsigned) {
2030 // If the unsigned [LHS] type is larger, return it.
2031 if (LHSRank >= RHSRank)
2032 return 1;
2033
2034 // If the signed type can represent all values of the unsigned type, it
2035 // wins. Because we are dealing with 2's complement and types that are
2036 // powers of two larger than each other, this is always safe.
2037 return -1;
2038 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002039
Chris Lattner7cfeb082008-04-06 23:55:33 +00002040 // If the unsigned [RHS] type is larger, return it.
2041 if (RHSRank >= LHSRank)
2042 return -1;
2043
2044 // If the signed type can represent all values of the unsigned type, it
2045 // wins. Because we are dealing with 2's complement and types that are
2046 // powers of two larger than each other, this is always safe.
2047 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002048}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002049
2050// getCFConstantStringType - Return the type used for constant CFStrings.
2051QualType ASTContext::getCFConstantStringType() {
2052 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002053 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002054 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002055 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002056 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002057
2058 // const int *isa;
2059 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002060 // int flags;
2061 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002062 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002063 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002064 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002065 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002066
Anders Carlsson71993dd2007-08-17 05:31:46 +00002067 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002068 for (unsigned i = 0; i < 4; ++i) {
2069 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2070 SourceLocation(), 0,
2071 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002072 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002073 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002074 }
2075
2076 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002077 }
2078
2079 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002080}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002081
Douglas Gregor319ac892009-04-23 22:29:11 +00002082void ASTContext::setCFConstantStringType(QualType T) {
2083 const RecordType *Rec = T->getAsRecordType();
2084 assert(Rec && "Invalid CFConstantStringType");
2085 CFConstantStringTypeDecl = Rec->getDecl();
2086}
2087
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002088QualType ASTContext::getObjCFastEnumerationStateType()
2089{
2090 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002091 ObjCFastEnumerationStateTypeDecl =
2092 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2093 &Idents.get("__objcFastEnumerationState"));
2094
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002095 QualType FieldTypes[] = {
2096 UnsignedLongTy,
2097 getPointerType(ObjCIdType),
2098 getPointerType(UnsignedLongTy),
2099 getConstantArrayType(UnsignedLongTy,
2100 llvm::APInt(32, 5), ArrayType::Normal, 0)
2101 };
2102
Douglas Gregor44b43212008-12-11 16:49:14 +00002103 for (size_t i = 0; i < 4; ++i) {
2104 FieldDecl *Field = FieldDecl::Create(*this,
2105 ObjCFastEnumerationStateTypeDecl,
2106 SourceLocation(), 0,
2107 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002108 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002109 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002110 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002111
Douglas Gregor44b43212008-12-11 16:49:14 +00002112 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002113 }
2114
2115 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2116}
2117
Douglas Gregor319ac892009-04-23 22:29:11 +00002118void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2119 const RecordType *Rec = T->getAsRecordType();
2120 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2121 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2122}
2123
Anders Carlssone8c49532007-10-29 06:33:42 +00002124// This returns true if a type has been typedefed to BOOL:
2125// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002126static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002127 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002128 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2129 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002130
2131 return false;
2132}
2133
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002134/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002135/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002136int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002137 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002138
2139 // Make all integer and enum types at least as large as an int
2140 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002141 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002142 // Treat arrays as pointers, since that's how they're passed in.
2143 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002144 sz = getTypeSize(VoidPtrTy);
2145 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002146}
2147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002148/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002149/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002150void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002151 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002152 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002153 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002154 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002155 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002156 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002157 // Compute size of all parameters.
2158 // Start with computing size of a pointer in number of bytes.
2159 // FIXME: There might(should) be a better way of doing this computation!
2160 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002161 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002162 // The first two arguments (self and _cmd) are pointers; account for
2163 // their size.
2164 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002165 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2166 E = Decl->param_end(); PI != E; ++PI) {
2167 QualType PType = (*PI)->getType();
2168 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002170 ParmOffset += sz;
2171 }
2172 S += llvm::utostr(ParmOffset);
2173 S += "@0:";
2174 S += llvm::utostr(PtrSize);
2175
2176 // Argument types.
2177 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002178 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2179 E = Decl->param_end(); PI != E; ++PI) {
2180 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002181 QualType PType = PVDecl->getOriginalType();
2182 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002183 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2184 // Use array's original type only if it has known number of
2185 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002186 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002187 PType = PVDecl->getType();
2188 } else if (PType->isFunctionType())
2189 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002190 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002191 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002192 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002193 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002194 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002195 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002196 }
2197}
2198
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002199/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002200/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002201/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2202/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002203/// Property attributes are stored as a comma-delimited C string. The simple
2204/// attributes readonly and bycopy are encoded as single characters. The
2205/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2206/// encoded as single characters, followed by an identifier. Property types
2207/// are also encoded as a parametrized attribute. The characters used to encode
2208/// these attributes are defined by the following enumeration:
2209/// @code
2210/// enum PropertyAttributes {
2211/// kPropertyReadOnly = 'R', // property is read-only.
2212/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2213/// kPropertyByref = '&', // property is a reference to the value last assigned
2214/// kPropertyDynamic = 'D', // property is dynamic
2215/// kPropertyGetter = 'G', // followed by getter selector name
2216/// kPropertySetter = 'S', // followed by setter selector name
2217/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2218/// kPropertyType = 't' // followed by old-style type encoding.
2219/// kPropertyWeak = 'W' // 'weak' property
2220/// kPropertyStrong = 'P' // property GC'able
2221/// kPropertyNonAtomic = 'N' // property non-atomic
2222/// };
2223/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002224void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2225 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002226 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002227 // Collect information from the property implementation decl(s).
2228 bool Dynamic = false;
2229 ObjCPropertyImplDecl *SynthesizePID = 0;
2230
2231 // FIXME: Duplicated code due to poor abstraction.
2232 if (Container) {
2233 if (const ObjCCategoryImplDecl *CID =
2234 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2235 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002236 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2237 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002238 ObjCPropertyImplDecl *PID = *i;
2239 if (PID->getPropertyDecl() == PD) {
2240 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2241 Dynamic = true;
2242 } else {
2243 SynthesizePID = PID;
2244 }
2245 }
2246 }
2247 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002248 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002249 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002250 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2251 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002252 ObjCPropertyImplDecl *PID = *i;
2253 if (PID->getPropertyDecl() == PD) {
2254 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2255 Dynamic = true;
2256 } else {
2257 SynthesizePID = PID;
2258 }
2259 }
2260 }
2261 }
2262 }
2263
2264 // FIXME: This is not very efficient.
2265 S = "T";
2266
2267 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002268 // GCC has some special rules regarding encoding of properties which
2269 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002270 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002271 true /* outermost type */,
2272 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002273
2274 if (PD->isReadOnly()) {
2275 S += ",R";
2276 } else {
2277 switch (PD->getSetterKind()) {
2278 case ObjCPropertyDecl::Assign: break;
2279 case ObjCPropertyDecl::Copy: S += ",C"; break;
2280 case ObjCPropertyDecl::Retain: S += ",&"; break;
2281 }
2282 }
2283
2284 // It really isn't clear at all what this means, since properties
2285 // are "dynamic by default".
2286 if (Dynamic)
2287 S += ",D";
2288
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002289 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2290 S += ",N";
2291
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002292 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2293 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002294 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002295 }
2296
2297 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2298 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002299 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002300 }
2301
2302 if (SynthesizePID) {
2303 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2304 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002305 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002306 }
2307
2308 // FIXME: OBJCGC: weak & strong
2309}
2310
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002311/// getLegacyIntegralTypeEncoding -
2312/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002313/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002314/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2315///
2316void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2317 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2318 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002319 if (BT->getKind() == BuiltinType::ULong &&
2320 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002321 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002322 else
2323 if (BT->getKind() == BuiltinType::Long &&
2324 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002325 PointeeTy = IntTy;
2326 }
2327 }
2328}
2329
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002330void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002331 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002332 // We follow the behavior of gcc, expanding structures which are
2333 // directly pointed to, and expanding embedded structures. Note that
2334 // these rules are sufficient to prevent recursive encoding of the
2335 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002336 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2337 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002338}
2339
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002340static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002341 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002342 const Expr *E = FD->getBitWidth();
2343 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2344 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002345 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002346 S += 'b';
2347 S += llvm::utostr(N);
2348}
2349
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002350void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2351 bool ExpandPointedToStructures,
2352 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002353 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002354 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002355 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002356 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002357 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002358 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002359 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002360 else {
2361 char encoding;
2362 switch (BT->getKind()) {
2363 default: assert(0 && "Unhandled builtin type kind");
2364 case BuiltinType::Void: encoding = 'v'; break;
2365 case BuiltinType::Bool: encoding = 'B'; break;
2366 case BuiltinType::Char_U:
2367 case BuiltinType::UChar: encoding = 'C'; break;
2368 case BuiltinType::UShort: encoding = 'S'; break;
2369 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002370 case BuiltinType::ULong:
2371 encoding =
2372 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2373 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002374 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002375 case BuiltinType::ULongLong: encoding = 'Q'; break;
2376 case BuiltinType::Char_S:
2377 case BuiltinType::SChar: encoding = 'c'; break;
2378 case BuiltinType::Short: encoding = 's'; break;
2379 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002380 case BuiltinType::Long:
2381 encoding =
2382 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2383 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002384 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002385 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002386 case BuiltinType::Float: encoding = 'f'; break;
2387 case BuiltinType::Double: encoding = 'd'; break;
2388 case BuiltinType::LongDouble: encoding = 'd'; break;
2389 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002390
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002391 S += encoding;
2392 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002393 } else if (const ComplexType *CT = T->getAsComplexType()) {
2394 S += 'j';
2395 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2396 false);
2397 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002398 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2399 ExpandPointedToStructures,
2400 ExpandStructures, FD);
2401 if (FD || EncodingProperty) {
2402 // Note that we do extended encoding of protocol qualifer list
2403 // Only when doing ivar or property encoding.
2404 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2405 S += '"';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002406 for (ObjCQualifiedIdType::qual_iterator I = QIDT->qual_begin(),
2407 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002408 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002409 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002410 S += '>';
2411 }
2412 S += '"';
2413 }
2414 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002415 }
2416 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002417 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002418 bool isReadOnly = false;
2419 // For historical/compatibility reasons, the read-only qualifier of the
2420 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2421 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2422 // Also, do not emit the 'r' for anything but the outermost type!
2423 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2424 if (OutermostType && T.isConstQualified()) {
2425 isReadOnly = true;
2426 S += 'r';
2427 }
2428 }
2429 else if (OutermostType) {
2430 QualType P = PointeeTy;
2431 while (P->getAsPointerType())
2432 P = P->getAsPointerType()->getPointeeType();
2433 if (P.isConstQualified()) {
2434 isReadOnly = true;
2435 S += 'r';
2436 }
2437 }
2438 if (isReadOnly) {
2439 // Another legacy compatibility encoding. Some ObjC qualifier and type
2440 // combinations need to be rearranged.
2441 // Rewrite "in const" from "nr" to "rn"
2442 const char * s = S.c_str();
2443 int len = S.length();
2444 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2445 std::string replace = "rn";
2446 S.replace(S.end()-2, S.end(), replace);
2447 }
2448 }
Steve Naroff389bf462009-02-12 17:52:19 +00002449 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002450 S += '@';
2451 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002452 }
2453 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002454 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002455 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002456 // Another historical/compatibility reason.
2457 // We encode the underlying type which comes out as
2458 // {...};
2459 S += '^';
2460 getObjCEncodingForTypeImpl(PointeeTy, S,
2461 false, ExpandPointedToStructures,
2462 NULL);
2463 return;
2464 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002465 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002466 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002467 const ObjCInterfaceType *OIT =
2468 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002469 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002470 S += '"';
2471 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002472 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2473 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002474 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002475 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002476 S += '>';
2477 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002478 S += '"';
2479 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002480 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002481 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002482 S += '#';
2483 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002485 S += ':';
2486 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002487 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002488
2489 if (PointeeTy->isCharType()) {
2490 // char pointer types should be encoded as '*' unless it is a
2491 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002492 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002493 S += '*';
2494 return;
2495 }
2496 }
2497
2498 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002499 getLegacyIntegralTypeEncoding(PointeeTy);
2500
2501 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002502 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002503 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002504 } else if (const ArrayType *AT =
2505 // Ignore type qualifiers etc.
2506 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002507 if (isa<IncompleteArrayType>(AT)) {
2508 // Incomplete arrays are encoded as a pointer to the array element.
2509 S += '^';
2510
2511 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2512 false, ExpandStructures, FD);
2513 } else {
2514 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002515
Anders Carlsson559a8332009-02-22 01:38:57 +00002516 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2517 S += llvm::utostr(CAT->getSize().getZExtValue());
2518 else {
2519 //Variable length arrays are encoded as a regular array with 0 elements.
2520 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2521 S += '0';
2522 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002523
Anders Carlsson559a8332009-02-22 01:38:57 +00002524 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2525 false, ExpandStructures, FD);
2526 S += ']';
2527 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002528 } else if (T->getAsFunctionType()) {
2529 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002530 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002531 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002532 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002533 // Anonymous structures print as '?'
2534 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2535 S += II->getName();
2536 } else {
2537 S += '?';
2538 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002539 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002540 S += '=';
Douglas Gregor6ab35242009-04-09 21:40:53 +00002541 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2542 FieldEnd = RDecl->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +00002543 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002544 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002545 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002546 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002547 S += '"';
2548 }
2549
2550 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002551 if (Field->isBitField()) {
2552 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2553 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002554 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002555 QualType qt = Field->getType();
2556 getLegacyIntegralTypeEncoding(qt);
2557 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002558 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002559 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002560 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002561 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002562 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002563 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002564 if (FD && FD->isBitField())
2565 EncodeBitField(this, S, FD);
2566 else
2567 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002568 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002569 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002570 } else if (T->isObjCInterfaceType()) {
2571 // @encode(class_name)
2572 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2573 S += '{';
2574 const IdentifierInfo *II = OI->getIdentifier();
2575 S += II->getName();
2576 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002577 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002578 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002579 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002580 if (RecFields[i]->isBitField())
2581 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2582 RecFields[i]);
2583 else
2584 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2585 FD);
2586 }
2587 S += '}';
2588 }
2589 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002590 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002591}
2592
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002593void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002594 std::string& S) const {
2595 if (QT & Decl::OBJC_TQ_In)
2596 S += 'n';
2597 if (QT & Decl::OBJC_TQ_Inout)
2598 S += 'N';
2599 if (QT & Decl::OBJC_TQ_Out)
2600 S += 'o';
2601 if (QT & Decl::OBJC_TQ_Bycopy)
2602 S += 'O';
2603 if (QT & Decl::OBJC_TQ_Byref)
2604 S += 'R';
2605 if (QT & Decl::OBJC_TQ_Oneway)
2606 S += 'V';
2607}
2608
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002609void ASTContext::setBuiltinVaListType(QualType T)
2610{
2611 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2612
2613 BuiltinVaListType = T;
2614}
2615
Douglas Gregor319ac892009-04-23 22:29:11 +00002616void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002617{
Douglas Gregor319ac892009-04-23 22:29:11 +00002618 ObjCIdType = T;
2619
2620 const TypedefType *TT = T->getAsTypedefType();
2621 if (!TT)
2622 return;
2623
2624 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002625
2626 // typedef struct objc_object *id;
2627 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002628 // User error - caller will issue diagnostics.
2629 if (!ptr)
2630 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002631 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002632 // User error - caller will issue diagnostics.
2633 if (!rec)
2634 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002635 IdStructType = rec;
2636}
2637
Douglas Gregor319ac892009-04-23 22:29:11 +00002638void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002639{
Douglas Gregor319ac892009-04-23 22:29:11 +00002640 ObjCSelType = T;
2641
2642 const TypedefType *TT = T->getAsTypedefType();
2643 if (!TT)
2644 return;
2645 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002646
2647 // typedef struct objc_selector *SEL;
2648 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002649 if (!ptr)
2650 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002651 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002652 if (!rec)
2653 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002654 SelStructType = rec;
2655}
2656
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002657void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002658{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002659 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002660}
2661
Douglas Gregor319ac892009-04-23 22:29:11 +00002662void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002663{
Douglas Gregor319ac892009-04-23 22:29:11 +00002664 ObjCClassType = T;
2665
2666 const TypedefType *TT = T->getAsTypedefType();
2667 if (!TT)
2668 return;
2669 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002670
2671 // typedef struct objc_class *Class;
2672 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2673 assert(ptr && "'Class' incorrectly typed");
2674 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2675 assert(rec && "'Class' incorrectly typed");
2676 ClassStructType = rec;
2677}
2678
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002679void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2680 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002681 "'NSConstantString' type already set!");
2682
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002683 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002684}
2685
Douglas Gregor7532dc62009-03-30 22:58:21 +00002686/// \brief Retrieve the template name that represents a qualified
2687/// template name such as \c std::vector.
2688TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2689 bool TemplateKeyword,
2690 TemplateDecl *Template) {
2691 llvm::FoldingSetNodeID ID;
2692 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2693
2694 void *InsertPos = 0;
2695 QualifiedTemplateName *QTN =
2696 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2697 if (!QTN) {
2698 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2699 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2700 }
2701
2702 return TemplateName(QTN);
2703}
2704
2705/// \brief Retrieve the template name that represents a dependent
2706/// template name such as \c MetaFun::template apply.
2707TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2708 const IdentifierInfo *Name) {
2709 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2710
2711 llvm::FoldingSetNodeID ID;
2712 DependentTemplateName::Profile(ID, NNS, Name);
2713
2714 void *InsertPos = 0;
2715 DependentTemplateName *QTN =
2716 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2717
2718 if (QTN)
2719 return TemplateName(QTN);
2720
2721 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2722 if (CanonNNS == NNS) {
2723 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2724 } else {
2725 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2726 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2727 }
2728
2729 DependentTemplateNames.InsertNode(QTN, InsertPos);
2730 return TemplateName(QTN);
2731}
2732
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002733/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002734/// TargetInfo, produce the corresponding type. The unsigned @p Type
2735/// is actually a value of type @c TargetInfo::IntType.
2736QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002737 switch (Type) {
2738 case TargetInfo::NoInt: return QualType();
2739 case TargetInfo::SignedShort: return ShortTy;
2740 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2741 case TargetInfo::SignedInt: return IntTy;
2742 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2743 case TargetInfo::SignedLong: return LongTy;
2744 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2745 case TargetInfo::SignedLongLong: return LongLongTy;
2746 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2747 }
2748
2749 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002750 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002751}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002752
2753//===----------------------------------------------------------------------===//
2754// Type Predicates.
2755//===----------------------------------------------------------------------===//
2756
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002757/// isObjCNSObjectType - Return true if this is an NSObject object using
2758/// NSObject attribute on a c-style pointer type.
2759/// FIXME - Make it work directly on types.
2760///
2761bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2762 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2763 if (TypedefDecl *TD = TDT->getDecl())
2764 if (TD->getAttr<ObjCNSObjectAttr>())
2765 return true;
2766 }
2767 return false;
2768}
2769
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002770/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2771/// to an object type. This includes "id" and "Class" (two 'special' pointers
2772/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2773/// ID type).
2774bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002775 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002776 return true;
2777
Steve Naroff6ae98502008-10-21 18:24:04 +00002778 // Blocks are objects.
2779 if (Ty->isBlockPointerType())
2780 return true;
2781
2782 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002783 const PointerType *PT = Ty->getAsPointerType();
2784 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002785 return false;
2786
Chris Lattner16ede0e2009-04-12 23:51:02 +00002787 // If this a pointer to an interface (e.g. NSString*), it is ok.
2788 if (PT->getPointeeType()->isObjCInterfaceType() ||
2789 // If is has NSObject attribute, OK as well.
2790 isObjCNSObjectType(Ty))
2791 return true;
2792
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002793 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2794 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002795 // underlying type. Iteratively strip off typedefs so that we can handle
2796 // typedefs of typedefs.
2797 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2798 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2799 Ty.getUnqualifiedType() == getObjCClassType())
2800 return true;
2801
2802 Ty = TDT->getDecl()->getUnderlyingType();
2803 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002804
Chris Lattner16ede0e2009-04-12 23:51:02 +00002805 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002806}
2807
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002808/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2809/// garbage collection attribute.
2810///
2811QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002812 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002813 if (getLangOptions().ObjC1 &&
2814 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002815 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002816 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002817 // (or pointers to them) be treated as though they were declared
2818 // as __strong.
2819 if (GCAttrs == QualType::GCNone) {
2820 if (isObjCObjectPointerType(Ty))
2821 GCAttrs = QualType::Strong;
2822 else if (Ty->isPointerType())
2823 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2824 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002825 // Non-pointers have none gc'able attribute regardless of the attribute
2826 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00002827 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002828 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002829 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002830 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002831}
2832
Chris Lattner6ac46a42008-04-07 06:51:04 +00002833//===----------------------------------------------------------------------===//
2834// Type Compatibility Testing
2835//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002836
Chris Lattner6ac46a42008-04-07 06:51:04 +00002837/// areCompatVectorTypes - Return true if the two specified vector types are
2838/// compatible.
2839static bool areCompatVectorTypes(const VectorType *LHS,
2840 const VectorType *RHS) {
2841 assert(LHS->isCanonical() && RHS->isCanonical());
2842 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002843 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002844}
2845
Eli Friedman3d815e72008-08-22 00:56:42 +00002846/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002847/// compatible for assignment from RHS to LHS. This handles validation of any
2848/// protocol qualifiers on the LHS or RHS.
2849///
Eli Friedman3d815e72008-08-22 00:56:42 +00002850bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2851 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002852 // Verify that the base decls are compatible: the RHS must be a subclass of
2853 // the LHS.
2854 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2855 return false;
2856
2857 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2858 // protocol qualified at all, then we are good.
2859 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2860 return true;
2861
2862 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2863 // isn't a superset.
2864 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2865 return true; // FIXME: should return false!
2866
2867 // Finally, we must have two protocol-qualified interfaces.
2868 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2869 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002870
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002871 // All LHS protocols must have a presence on the RHS.
2872 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002873
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002874 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2875 LHSPE = LHSP->qual_end();
2876 LHSPI != LHSPE; LHSPI++) {
2877 bool RHSImplementsProtocol = false;
2878
2879 // If the RHS doesn't implement the protocol on the left, the types
2880 // are incompatible.
2881 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2882 RHSPE = RHSP->qual_end();
2883 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2884 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2885 RHSImplementsProtocol = true;
2886 }
2887 // FIXME: For better diagnostics, consider passing back the protocol name.
2888 if (!RHSImplementsProtocol)
2889 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002890 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002891 // The RHS implements all protocols listed on the LHS.
2892 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002893}
2894
Steve Naroff389bf462009-02-12 17:52:19 +00002895bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2896 // get the "pointed to" types
2897 const PointerType *LHSPT = LHS->getAsPointerType();
2898 const PointerType *RHSPT = RHS->getAsPointerType();
2899
2900 if (!LHSPT || !RHSPT)
2901 return false;
2902
2903 QualType lhptee = LHSPT->getPointeeType();
2904 QualType rhptee = RHSPT->getPointeeType();
2905 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2906 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2907 // ID acts sort of like void* for ObjC interfaces
2908 if (LHSIface && isObjCIdStructType(rhptee))
2909 return true;
2910 if (RHSIface && isObjCIdStructType(lhptee))
2911 return true;
2912 if (!LHSIface || !RHSIface)
2913 return false;
2914 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2915 canAssignObjCInterfaces(RHSIface, LHSIface);
2916}
2917
Steve Naroffec0550f2007-10-15 20:41:53 +00002918/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2919/// both shall have the identically qualified version of a compatible type.
2920/// C99 6.2.7p1: Two types have compatible types if their types are the
2921/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002922bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2923 return !mergeTypes(LHS, RHS).isNull();
2924}
2925
2926QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2927 const FunctionType *lbase = lhs->getAsFunctionType();
2928 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002929 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2930 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00002931 bool allLTypes = true;
2932 bool allRTypes = true;
2933
2934 // Check return type
2935 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2936 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00002937 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2938 allLTypes = false;
2939 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2940 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002941
2942 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00002943 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
2944 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00002945 unsigned lproto_nargs = lproto->getNumArgs();
2946 unsigned rproto_nargs = rproto->getNumArgs();
2947
2948 // Compatible functions must have the same number of arguments
2949 if (lproto_nargs != rproto_nargs)
2950 return QualType();
2951
2952 // Variadic and non-variadic functions aren't compatible
2953 if (lproto->isVariadic() != rproto->isVariadic())
2954 return QualType();
2955
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002956 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2957 return QualType();
2958
Eli Friedman3d815e72008-08-22 00:56:42 +00002959 // Check argument compatibility
2960 llvm::SmallVector<QualType, 10> types;
2961 for (unsigned i = 0; i < lproto_nargs; i++) {
2962 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2963 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2964 QualType argtype = mergeTypes(largtype, rargtype);
2965 if (argtype.isNull()) return QualType();
2966 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00002967 if (getCanonicalType(argtype) != getCanonicalType(largtype))
2968 allLTypes = false;
2969 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2970 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002971 }
2972 if (allLTypes) return lhs;
2973 if (allRTypes) return rhs;
2974 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002975 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00002976 }
2977
2978 if (lproto) allRTypes = false;
2979 if (rproto) allLTypes = false;
2980
Douglas Gregor72564e72009-02-26 23:50:07 +00002981 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00002982 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00002983 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00002984 if (proto->isVariadic()) return QualType();
2985 // Check that the types are compatible with the types that
2986 // would result from default argument promotions (C99 6.7.5.3p15).
2987 // The only types actually affected are promotable integer
2988 // types and floats, which would be passed as a different
2989 // type depending on whether the prototype is visible.
2990 unsigned proto_nargs = proto->getNumArgs();
2991 for (unsigned i = 0; i < proto_nargs; ++i) {
2992 QualType argTy = proto->getArgType(i);
2993 if (argTy->isPromotableIntegerType() ||
2994 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2995 return QualType();
2996 }
2997
2998 if (allLTypes) return lhs;
2999 if (allRTypes) return rhs;
3000 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003001 proto->getNumArgs(), lproto->isVariadic(),
3002 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003003 }
3004
3005 if (allLTypes) return lhs;
3006 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003007 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003008}
3009
3010QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003011 // C++ [expr]: If an expression initially has the type "reference to T", the
3012 // type is adjusted to "T" prior to any further analysis, the expression
3013 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003014 // expression is an lvalue unless the reference is an rvalue reference and
3015 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003016 // FIXME: C++ shouldn't be going through here! The rules are different
3017 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003018 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3019 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003020 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003021 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003022 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003023 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003024
Eli Friedman3d815e72008-08-22 00:56:42 +00003025 QualType LHSCan = getCanonicalType(LHS),
3026 RHSCan = getCanonicalType(RHS);
3027
3028 // If two types are identical, they are compatible.
3029 if (LHSCan == RHSCan)
3030 return LHS;
3031
3032 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003033 // Note that we handle extended qualifiers later, in the
3034 // case for ExtQualType.
3035 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003036 return QualType();
3037
Eli Friedman852d63b2009-06-01 01:22:52 +00003038 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3039 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003040
Chris Lattner1adb8832008-01-14 05:45:46 +00003041 // We want to consider the two function types to be the same for these
3042 // comparisons, just force one to the other.
3043 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3044 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003045
Eli Friedman07d25872009-06-02 05:28:56 +00003046 // Strip off objc_gc attributes off the top level so they can be merged.
3047 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003048 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003049 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3050 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003051 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003052 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003053 // __strong attribue is redundant if other decl is an objective-c
3054 // object pointer (or decorated with __strong attribute); otherwise
3055 // issue error.
3056 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3057 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3058 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3059 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003060 return QualType();
3061
Eli Friedman07d25872009-06-02 05:28:56 +00003062 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3063 RHS.getCVRQualifiers());
3064 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003065 if (!Result.isNull()) {
3066 if (Result.getObjCGCAttr() == QualType::GCNone)
3067 Result = getObjCGCQualType(Result, GCAttr);
3068 else if (Result.getObjCGCAttr() != GCAttr)
3069 Result = QualType();
3070 }
Eli Friedman07d25872009-06-02 05:28:56 +00003071 return Result;
3072 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003073 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003074 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003075 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3076 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003077 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3078 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003079 // __strong attribue is redundant if other decl is an objective-c
3080 // object pointer (or decorated with __strong attribute); otherwise
3081 // issue error.
3082 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3083 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3084 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3085 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003086 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003087
Eli Friedman07d25872009-06-02 05:28:56 +00003088 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3089 LHS.getCVRQualifiers());
3090 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003091 if (!Result.isNull()) {
3092 if (Result.getObjCGCAttr() == QualType::GCNone)
3093 Result = getObjCGCQualType(Result, GCAttr);
3094 else if (Result.getObjCGCAttr() != GCAttr)
3095 Result = QualType();
3096 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003097 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003098 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003099 }
3100
Eli Friedman4c721d32008-02-12 08:23:06 +00003101 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003102 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3103 LHSClass = Type::ConstantArray;
3104 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3105 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003106
Nate Begeman213541a2008-04-18 23:10:10 +00003107 // Canonicalize ExtVector -> Vector.
3108 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3109 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003110
Chris Lattnerb0489812008-04-07 06:38:24 +00003111 // Consider qualified interfaces and interfaces the same.
3112 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3113 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003114
Chris Lattnera36a61f2008-04-07 05:43:21 +00003115 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003116 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003117 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3118 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003119
Steve Naroffd824c9c2009-04-14 15:11:46 +00003120 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3121 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003122 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003123 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003124 return RHS;
3125
Steve Naroffbc76dd02008-12-10 22:14:21 +00003126 // ID is compatible with all qualified id types.
3127 if (LHS->isObjCQualifiedIdType()) {
3128 if (const PointerType *PT = RHS->getAsPointerType()) {
3129 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003130 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003131 return LHS;
3132 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3133 // Unfortunately, this API is part of Sema (which we don't have access
3134 // to. Need to refactor. The following check is insufficient, since we
3135 // need to make sure the class implements the protocol.
3136 if (pType->isObjCInterfaceType())
3137 return LHS;
3138 }
3139 }
3140 if (RHS->isObjCQualifiedIdType()) {
3141 if (const PointerType *PT = LHS->getAsPointerType()) {
3142 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003143 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003144 return RHS;
3145 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3146 // Unfortunately, this API is part of Sema (which we don't have access
3147 // to. Need to refactor. The following check is insufficient, since we
3148 // need to make sure the class implements the protocol.
3149 if (pType->isObjCInterfaceType())
3150 return RHS;
3151 }
3152 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003153 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3154 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003155 if (const EnumType* ETy = LHS->getAsEnumType()) {
3156 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3157 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003158 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003159 if (const EnumType* ETy = RHS->getAsEnumType()) {
3160 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3161 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003162 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003163
Eli Friedman3d815e72008-08-22 00:56:42 +00003164 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003165 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003166
Steve Naroff4a746782008-01-09 22:43:08 +00003167 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003168 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003169#define TYPE(Class, Base)
3170#define ABSTRACT_TYPE(Class, Base)
3171#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3172#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3173#include "clang/AST/TypeNodes.def"
3174 assert(false && "Non-canonical and dependent types shouldn't get here");
3175 return QualType();
3176
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003177 case Type::LValueReference:
3178 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003179 case Type::MemberPointer:
3180 assert(false && "C++ should never be in mergeTypes");
3181 return QualType();
3182
3183 case Type::IncompleteArray:
3184 case Type::VariableArray:
3185 case Type::FunctionProto:
3186 case Type::ExtVector:
3187 case Type::ObjCQualifiedInterface:
3188 assert(false && "Types are eliminated above");
3189 return QualType();
3190
Chris Lattner1adb8832008-01-14 05:45:46 +00003191 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003192 {
3193 // Merge two pointer types, while trying to preserve typedef info
3194 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3195 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3196 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3197 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003198 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003199 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003200 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003201 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003202 return getPointerType(ResultType);
3203 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003204 case Type::BlockPointer:
3205 {
3206 // Merge two block pointer types, while trying to preserve typedef info
3207 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3208 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3209 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3210 if (ResultType.isNull()) return QualType();
3211 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3212 return LHS;
3213 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3214 return RHS;
3215 return getBlockPointerType(ResultType);
3216 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003217 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003218 {
3219 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3220 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3221 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3222 return QualType();
3223
3224 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3225 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3226 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3227 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003228 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3229 return LHS;
3230 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3231 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003232 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3233 ArrayType::ArraySizeModifier(), 0);
3234 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3235 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003236 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3237 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003238 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3239 return LHS;
3240 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3241 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003242 if (LVAT) {
3243 // FIXME: This isn't correct! But tricky to implement because
3244 // the array's size has to be the size of LHS, but the type
3245 // has to be different.
3246 return LHS;
3247 }
3248 if (RVAT) {
3249 // FIXME: This isn't correct! But tricky to implement because
3250 // the array's size has to be the size of RHS, but the type
3251 // has to be different.
3252 return RHS;
3253 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003254 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3255 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003256 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003257 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003258 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003259 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003260 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003261 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003262 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003263 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3264 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003265 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003266 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003267 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003268 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003269 case Type::Complex:
3270 // Distinct complex types are incompatible.
3271 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003272 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003273 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003274 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3275 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003276 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003277 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003278 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003279 // FIXME: This should be type compatibility, e.g. whether
3280 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003281 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3282 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3283 if (LHSIface && RHSIface &&
3284 canAssignObjCInterfaces(LHSIface, RHSIface))
3285 return LHS;
3286
Eli Friedman3d815e72008-08-22 00:56:42 +00003287 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003288 }
Steve Naroffbc76dd02008-12-10 22:14:21 +00003289 case Type::ObjCQualifiedId:
3290 // Distinct qualified id's are not compatible.
3291 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003292 case Type::FixedWidthInt:
3293 // Distinct fixed-width integers are not compatible.
3294 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003295 case Type::ExtQual:
3296 // FIXME: ExtQual types can be compatible even if they're not
3297 // identical!
3298 return QualType();
3299 // First attempt at an implementation, but I'm not really sure it's
3300 // right...
3301#if 0
3302 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3303 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3304 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3305 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3306 return QualType();
3307 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3308 LHSBase = QualType(LQual->getBaseType(), 0);
3309 RHSBase = QualType(RQual->getBaseType(), 0);
3310 ResultType = mergeTypes(LHSBase, RHSBase);
3311 if (ResultType.isNull()) return QualType();
3312 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3313 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3314 return LHS;
3315 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3316 return RHS;
3317 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3318 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3319 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3320 return ResultType;
3321#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003322
3323 case Type::TemplateSpecialization:
3324 assert(false && "Dependent types have no size");
3325 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003326 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003327
3328 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003329}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003330
Chris Lattner5426bf62008-04-07 07:01:58 +00003331//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003332// Integer Predicates
3333//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003334
Eli Friedmanad74a752008-06-28 06:23:08 +00003335unsigned ASTContext::getIntWidth(QualType T) {
3336 if (T == BoolTy)
3337 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003338 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3339 return FWIT->getWidth();
3340 }
3341 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003342 return (unsigned)getTypeSize(T);
3343}
3344
3345QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3346 assert(T->isSignedIntegerType() && "Unexpected type");
3347 if (const EnumType* ETy = T->getAsEnumType())
3348 T = ETy->getDecl()->getIntegerType();
3349 const BuiltinType* BTy = T->getAsBuiltinType();
3350 assert (BTy && "Unexpected signed integer type");
3351 switch (BTy->getKind()) {
3352 case BuiltinType::Char_S:
3353 case BuiltinType::SChar:
3354 return UnsignedCharTy;
3355 case BuiltinType::Short:
3356 return UnsignedShortTy;
3357 case BuiltinType::Int:
3358 return UnsignedIntTy;
3359 case BuiltinType::Long:
3360 return UnsignedLongTy;
3361 case BuiltinType::LongLong:
3362 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003363 case BuiltinType::Int128:
3364 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003365 default:
3366 assert(0 && "Unexpected signed integer type");
3367 return QualType();
3368 }
3369}
3370
Douglas Gregor2cf26342009-04-09 22:27:44 +00003371ExternalASTSource::~ExternalASTSource() { }
3372
3373void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003374
3375
3376//===----------------------------------------------------------------------===//
3377// Builtin Type Computation
3378//===----------------------------------------------------------------------===//
3379
3380/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3381/// pointer over the consumed characters. This returns the resultant type.
3382static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3383 ASTContext::GetBuiltinTypeError &Error,
3384 bool AllowTypeModifiers = true) {
3385 // Modifiers.
3386 int HowLong = 0;
3387 bool Signed = false, Unsigned = false;
3388
3389 // Read the modifiers first.
3390 bool Done = false;
3391 while (!Done) {
3392 switch (*Str++) {
3393 default: Done = true; --Str; break;
3394 case 'S':
3395 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3396 assert(!Signed && "Can't use 'S' modifier multiple times!");
3397 Signed = true;
3398 break;
3399 case 'U':
3400 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3401 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3402 Unsigned = true;
3403 break;
3404 case 'L':
3405 assert(HowLong <= 2 && "Can't have LLLL modifier");
3406 ++HowLong;
3407 break;
3408 }
3409 }
3410
3411 QualType Type;
3412
3413 // Read the base type.
3414 switch (*Str++) {
3415 default: assert(0 && "Unknown builtin type letter!");
3416 case 'v':
3417 assert(HowLong == 0 && !Signed && !Unsigned &&
3418 "Bad modifiers used with 'v'!");
3419 Type = Context.VoidTy;
3420 break;
3421 case 'f':
3422 assert(HowLong == 0 && !Signed && !Unsigned &&
3423 "Bad modifiers used with 'f'!");
3424 Type = Context.FloatTy;
3425 break;
3426 case 'd':
3427 assert(HowLong < 2 && !Signed && !Unsigned &&
3428 "Bad modifiers used with 'd'!");
3429 if (HowLong)
3430 Type = Context.LongDoubleTy;
3431 else
3432 Type = Context.DoubleTy;
3433 break;
3434 case 's':
3435 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3436 if (Unsigned)
3437 Type = Context.UnsignedShortTy;
3438 else
3439 Type = Context.ShortTy;
3440 break;
3441 case 'i':
3442 if (HowLong == 3)
3443 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3444 else if (HowLong == 2)
3445 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3446 else if (HowLong == 1)
3447 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3448 else
3449 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3450 break;
3451 case 'c':
3452 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3453 if (Signed)
3454 Type = Context.SignedCharTy;
3455 else if (Unsigned)
3456 Type = Context.UnsignedCharTy;
3457 else
3458 Type = Context.CharTy;
3459 break;
3460 case 'b': // boolean
3461 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3462 Type = Context.BoolTy;
3463 break;
3464 case 'z': // size_t.
3465 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3466 Type = Context.getSizeType();
3467 break;
3468 case 'F':
3469 Type = Context.getCFConstantStringType();
3470 break;
3471 case 'a':
3472 Type = Context.getBuiltinVaListType();
3473 assert(!Type.isNull() && "builtin va list type not initialized!");
3474 break;
3475 case 'A':
3476 // This is a "reference" to a va_list; however, what exactly
3477 // this means depends on how va_list is defined. There are two
3478 // different kinds of va_list: ones passed by value, and ones
3479 // passed by reference. An example of a by-value va_list is
3480 // x86, where va_list is a char*. An example of by-ref va_list
3481 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3482 // we want this argument to be a char*&; for x86-64, we want
3483 // it to be a __va_list_tag*.
3484 Type = Context.getBuiltinVaListType();
3485 assert(!Type.isNull() && "builtin va list type not initialized!");
3486 if (Type->isArrayType()) {
3487 Type = Context.getArrayDecayedType(Type);
3488 } else {
3489 Type = Context.getLValueReferenceType(Type);
3490 }
3491 break;
3492 case 'V': {
3493 char *End;
3494
3495 unsigned NumElements = strtoul(Str, &End, 10);
3496 assert(End != Str && "Missing vector size");
3497
3498 Str = End;
3499
3500 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3501 Type = Context.getVectorType(ElementType, NumElements);
3502 break;
3503 }
3504 case 'P': {
3505 IdentifierInfo *II = &Context.Idents.get("FILE");
3506 DeclContext::lookup_result Lookup
3507 = Context.getTranslationUnitDecl()->lookup(Context, II);
3508 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3509 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3510 break;
3511 }
3512 else {
3513 Error = ASTContext::GE_Missing_FILE;
3514 return QualType();
3515 }
3516 }
3517 }
3518
3519 if (!AllowTypeModifiers)
3520 return Type;
3521
3522 Done = false;
3523 while (!Done) {
3524 switch (*Str++) {
3525 default: Done = true; --Str; break;
3526 case '*':
3527 Type = Context.getPointerType(Type);
3528 break;
3529 case '&':
3530 Type = Context.getLValueReferenceType(Type);
3531 break;
3532 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3533 case 'C':
3534 Type = Type.getQualifiedType(QualType::Const);
3535 break;
3536 }
3537 }
3538
3539 return Type;
3540}
3541
3542/// GetBuiltinType - Return the type for the specified builtin.
3543QualType ASTContext::GetBuiltinType(unsigned id,
3544 GetBuiltinTypeError &Error) {
3545 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3546
3547 llvm::SmallVector<QualType, 8> ArgTypes;
3548
3549 Error = GE_None;
3550 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3551 if (Error != GE_None)
3552 return QualType();
3553 while (TypeStr[0] && TypeStr[0] != '.') {
3554 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3555 if (Error != GE_None)
3556 return QualType();
3557
3558 // Do array -> pointer decay. The builtin should use the decayed type.
3559 if (Ty->isArrayType())
3560 Ty = getArrayDecayedType(Ty);
3561
3562 ArgTypes.push_back(Ty);
3563 }
3564
3565 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3566 "'.' should only occur at end of builtin type list!");
3567
3568 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3569 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3570 return getFunctionNoProtoType(ResType);
3571 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3572 TypeStr[0] == '.', 0);
3573}