blob: f3cf6b18eb0ad2a930021e1595d392da85d37a51 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff3fafa102007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
19#include "clang/AST/RecordLayout.h"
Chris Lattnerb09b31d2009-03-28 03:45:20 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000022#include "llvm/ADT/StringExtras.h"
Ted Kremenek738e6c02007-10-31 17:10:13 +000023#include "llvm/Bitcode/Serialize.h"
24#include "llvm/Bitcode/Deserialize.h"
Nate Begeman7903d052009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerf4fbc442009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner2fda0ed2008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbarde300732008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Steve Naroff207b9ec2009-01-27 23:20:32 +000036 bool FreeMem, unsigned size_reserve) :
Douglas Gregor1e589cc2009-03-26 23:50:42 +000037 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
38 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Chris Lattner9c18fde2009-03-28 01:44:40 +000039 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels) {
Daniel Dunbarde300732008-08-11 04:54:23 +000040 if (size_reserve > 0) Types.reserve(size_reserve);
41 InitBuiltinTypes();
Chris Lattner911b8672009-03-13 22:38:49 +000042 BuiltinInfo.InitializeBuiltins(idents, Target, LangOpts.NoBuiltin);
Daniel Dunbarde300732008-08-11 04:54:23 +000043 TUDecl = TranslationUnitDecl::Create(*this);
44}
45
Chris Lattner4b009652007-07-25 00:24:17 +000046ASTContext::~ASTContext() {
47 // Deallocate all the types.
48 while (!Types.empty()) {
Ted Kremenekdb4d5972008-05-21 16:38:54 +000049 Types.back()->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000050 Types.pop_back();
51 }
Eli Friedman65489b72008-05-27 03:08:09 +000052
Nuno Lopes355a8682008-12-17 22:30:25 +000053 {
54 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
55 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
56 while (I != E) {
57 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
58 delete R;
59 }
60 }
61
62 {
63 llvm::DenseMap<const ObjCInterfaceDecl*, const ASTRecordLayout*>::iterator
64 I = ASTObjCInterfaces.begin(), E = ASTObjCInterfaces.end();
65 while (I != E) {
66 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
67 delete R;
68 }
69 }
70
71 {
72 llvm::DenseMap<const ObjCInterfaceDecl*, const RecordDecl*>::iterator
73 I = ASTRecordForInterface.begin(), E = ASTRecordForInterface.end();
74 while (I != E) {
75 RecordDecl *R = const_cast<RecordDecl*>((I++)->second);
76 R->Destroy(*this);
77 }
78 }
79
Douglas Gregor1e589cc2009-03-26 23:50:42 +000080 // Destroy nested-name-specifiers.
Douglas Gregor3c4eae52009-03-27 23:54:10 +000081 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
82 NNS = NestedNameSpecifiers.begin(),
83 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregorbccd97c2009-03-27 23:25:45 +000084 NNS != NNSEnd;
Douglas Gregor3c4eae52009-03-27 23:54:10 +000085 /* Increment in loop */)
86 (*NNS++).Destroy(*this);
Douglas Gregor1e589cc2009-03-26 23:50:42 +000087
88 if (GlobalNestedNameSpecifier)
89 GlobalNestedNameSpecifier->Destroy(*this);
90
Eli Friedman65489b72008-05-27 03:08:09 +000091 TUDecl->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000092}
93
94void ASTContext::PrintStats() const {
95 fprintf(stderr, "*** AST Context Stats:\n");
96 fprintf(stderr, " %d types total.\n", (int)Types.size());
97 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
Daniel Dunbar47677342008-09-26 03:23:00 +000098 unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +000099 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0;
100 unsigned NumLValueReference = 0, NumRValueReference = 0, NumMemberPointer = 0;
101
Chris Lattner4b009652007-07-25 00:24:17 +0000102 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000103 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
104 unsigned NumObjCQualifiedIds = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000105 unsigned NumTypeOfTypes = 0, NumTypeOfExprTypes = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000106
107 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
108 Type *T = Types[i];
109 if (isa<BuiltinType>(T))
110 ++NumBuiltin;
111 else if (isa<PointerType>(T))
112 ++NumPointer;
Daniel Dunbar47677342008-09-26 03:23:00 +0000113 else if (isa<BlockPointerType>(T))
114 ++NumBlockPointer;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000115 else if (isa<LValueReferenceType>(T))
116 ++NumLValueReference;
117 else if (isa<RValueReferenceType>(T))
118 ++NumRValueReference;
Sebastian Redl75555032009-01-24 21:16:55 +0000119 else if (isa<MemberPointerType>(T))
120 ++NumMemberPointer;
Chris Lattner4b009652007-07-25 00:24:17 +0000121 else if (isa<ComplexType>(T))
122 ++NumComplex;
123 else if (isa<ArrayType>(T))
124 ++NumArray;
125 else if (isa<VectorType>(T))
126 ++NumVector;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000127 else if (isa<FunctionNoProtoType>(T))
Chris Lattner4b009652007-07-25 00:24:17 +0000128 ++NumFunctionNP;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000129 else if (isa<FunctionProtoType>(T))
Chris Lattner4b009652007-07-25 00:24:17 +0000130 ++NumFunctionP;
131 else if (isa<TypedefType>(T))
132 ++NumTypeName;
133 else if (TagType *TT = dyn_cast<TagType>(T)) {
134 ++NumTagged;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000135 switch (TT->getDecl()->getTagKind()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000136 default: assert(0 && "Unknown tagged type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000137 case TagDecl::TK_struct: ++NumTagStruct; break;
138 case TagDecl::TK_union: ++NumTagUnion; break;
139 case TagDecl::TK_class: ++NumTagClass; break;
140 case TagDecl::TK_enum: ++NumTagEnum; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000141 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000142 } else if (isa<ObjCInterfaceType>(T))
143 ++NumObjCInterfaces;
144 else if (isa<ObjCQualifiedInterfaceType>(T))
145 ++NumObjCQualifiedInterfaces;
146 else if (isa<ObjCQualifiedIdType>(T))
147 ++NumObjCQualifiedIds;
Steve Naroffe0430632008-05-21 15:59:22 +0000148 else if (isa<TypeOfType>(T))
149 ++NumTypeOfTypes;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000150 else if (isa<TypeOfExprType>(T))
151 ++NumTypeOfExprTypes;
Steve Naroff948fd372007-09-17 14:16:13 +0000152 else {
Chris Lattner8a35b462007-12-12 06:43:05 +0000153 QualType(T, 0).dump();
Chris Lattner4b009652007-07-25 00:24:17 +0000154 assert(0 && "Unknown type!");
155 }
156 }
157
158 fprintf(stderr, " %d builtin types\n", NumBuiltin);
159 fprintf(stderr, " %d pointer types\n", NumPointer);
Daniel Dunbar47677342008-09-26 03:23:00 +0000160 fprintf(stderr, " %d block pointer types\n", NumBlockPointer);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000161 fprintf(stderr, " %d lvalue reference types\n", NumLValueReference);
162 fprintf(stderr, " %d rvalue reference types\n", NumRValueReference);
Sebastian Redl75555032009-01-24 21:16:55 +0000163 fprintf(stderr, " %d member pointer types\n", NumMemberPointer);
Chris Lattner4b009652007-07-25 00:24:17 +0000164 fprintf(stderr, " %d complex types\n", NumComplex);
165 fprintf(stderr, " %d array types\n", NumArray);
166 fprintf(stderr, " %d vector types\n", NumVector);
167 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
168 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
169 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
170 fprintf(stderr, " %d tagged types\n", NumTagged);
171 fprintf(stderr, " %d struct types\n", NumTagStruct);
172 fprintf(stderr, " %d union types\n", NumTagUnion);
173 fprintf(stderr, " %d class types\n", NumTagClass);
174 fprintf(stderr, " %d enum types\n", NumTagEnum);
Ted Kremenek42730c52008-01-07 19:49:32 +0000175 fprintf(stderr, " %d interface types\n", NumObjCInterfaces);
Chris Lattner8a35b462007-12-12 06:43:05 +0000176 fprintf(stderr, " %d protocol qualified interface types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000177 NumObjCQualifiedInterfaces);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000178 fprintf(stderr, " %d protocol qualified id types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000179 NumObjCQualifiedIds);
Steve Naroffe0430632008-05-21 15:59:22 +0000180 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes);
Douglas Gregor4fa58902009-02-26 23:50:07 +0000181 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprTypes);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000182
Chris Lattner4b009652007-07-25 00:24:17 +0000183 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
184 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
185 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
Sebastian Redlce6fff02009-03-16 23:22:08 +0000186 NumLValueReference*sizeof(LValueReferenceType)+
187 NumRValueReference*sizeof(RValueReferenceType)+
Sebastian Redl75555032009-01-24 21:16:55 +0000188 NumMemberPointer*sizeof(MemberPointerType)+
Douglas Gregor4fa58902009-02-26 23:50:07 +0000189 NumFunctionP*sizeof(FunctionProtoType)+
190 NumFunctionNP*sizeof(FunctionNoProtoType)+
Steve Naroffe0430632008-05-21 15:59:22 +0000191 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
Douglas Gregor4fa58902009-02-26 23:50:07 +0000192 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprTypes*sizeof(TypeOfExprType)));
Chris Lattner4b009652007-07-25 00:24:17 +0000193}
194
195
196void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Naroff93fd2112009-01-27 22:08:43 +0000197 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +0000198}
199
Chris Lattner4b009652007-07-25 00:24:17 +0000200void ASTContext::InitBuiltinTypes() {
201 assert(VoidTy.isNull() && "Context reinitialized?");
202
203 // C99 6.2.5p19.
204 InitBuiltinType(VoidTy, BuiltinType::Void);
205
206 // C99 6.2.5p2.
207 InitBuiltinType(BoolTy, BuiltinType::Bool);
208 // C99 6.2.5p3.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000209 if (Target.isCharSigned())
Chris Lattner4b009652007-07-25 00:24:17 +0000210 InitBuiltinType(CharTy, BuiltinType::Char_S);
211 else
212 InitBuiltinType(CharTy, BuiltinType::Char_U);
213 // C99 6.2.5p4.
214 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
215 InitBuiltinType(ShortTy, BuiltinType::Short);
216 InitBuiltinType(IntTy, BuiltinType::Int);
217 InitBuiltinType(LongTy, BuiltinType::Long);
218 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
219
220 // C99 6.2.5p6.
221 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
222 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
223 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
224 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
225 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
226
227 // C99 6.2.5p10.
228 InitBuiltinType(FloatTy, BuiltinType::Float);
229 InitBuiltinType(DoubleTy, BuiltinType::Double);
230 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000231
Chris Lattnere1dafe72009-02-26 23:43:47 +0000232 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
233 InitBuiltinType(WCharTy, BuiltinType::WChar);
234 else // C99
235 WCharTy = getFromTargetType(Target.getWCharType());
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000236
Douglas Gregord2baafd2008-10-21 16:13:35 +0000237 // Placeholder type for functions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000238 InitBuiltinType(OverloadTy, BuiltinType::Overload);
239
240 // Placeholder type for type-dependent expressions whose type is
241 // completely unknown. No code should ever check a type against
242 // DependentTy and users should never see it; however, it is here to
243 // help diagnose failures to properly check for type-dependent
244 // expressions.
245 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000246
Chris Lattner4b009652007-07-25 00:24:17 +0000247 // C99 6.2.5p11.
248 FloatComplexTy = getComplexType(FloatTy);
249 DoubleComplexTy = getComplexType(DoubleTy);
250 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000251
Steve Naroff9d12c902007-10-15 14:41:52 +0000252 BuiltinVaListType = QualType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000253 ObjCIdType = QualType();
Steve Naroff9d12c902007-10-15 14:41:52 +0000254 IdStructType = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000255 ObjCClassType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000256 ClassStructType = 0;
257
Ted Kremenek42730c52008-01-07 19:49:32 +0000258 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000259
260 // void * type
261 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000262}
263
264//===----------------------------------------------------------------------===//
265// Type Sizing and Analysis
266//===----------------------------------------------------------------------===//
267
Chris Lattner2a674dc2008-06-30 18:32:54 +0000268/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
269/// scalar floating point type.
270const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
271 const BuiltinType *BT = T->getAsBuiltinType();
272 assert(BT && "Not a floating point type!");
273 switch (BT->getKind()) {
274 default: assert(0 && "Not a floating point type!");
275 case BuiltinType::Float: return Target.getFloatFormat();
276 case BuiltinType::Double: return Target.getDoubleFormat();
277 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
278 }
279}
280
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000281/// getDeclAlign - Return a conservative estimate of the alignment of the
282/// specified decl. Note that bitfields do not have a valid alignment, so
283/// this method will assert on them.
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000284unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedman0ee57322009-02-22 02:56:25 +0000285 unsigned Align = Target.getCharWidth();
286
287 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
288 Align = std::max(Align, AA->getAlignment());
289
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000290 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
291 QualType T = VD->getType();
292 // Incomplete or function types default to 1.
Eli Friedman0ee57322009-02-22 02:56:25 +0000293 if (!T->isIncompleteType() && !T->isFunctionType()) {
294 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
295 T = cast<ArrayType>(T)->getElementType();
296
297 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
298 }
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000299 }
Eli Friedman0ee57322009-02-22 02:56:25 +0000300
301 return Align / Target.getCharWidth();
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000302}
Chris Lattner2a674dc2008-06-30 18:32:54 +0000303
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// getTypeSize - Return the size of the specified type, in bits. This method
305/// does not work on incomplete types.
306std::pair<uint64_t, unsigned>
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000307ASTContext::getTypeInfo(const Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000308 T = getCanonicalType(T);
Mike Stump44d1f402009-02-27 18:32:39 +0000309 uint64_t Width=0;
310 unsigned Align=8;
Chris Lattner4b009652007-07-25 00:24:17 +0000311 switch (T->getTypeClass()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000312#define TYPE(Class, Base)
313#define ABSTRACT_TYPE(Class, Base)
314#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
315#define DEPENDENT_TYPE(Class, Base) case Type::Class:
316#include "clang/AST/TypeNodes.def"
317 assert(false && "Should not see non-canonical or dependent types");
318 break;
319
Chris Lattner4b009652007-07-25 00:24:17 +0000320 case Type::FunctionNoProto:
321 case Type::FunctionProto:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000322 case Type::IncompleteArray:
Chris Lattner4b009652007-07-25 00:24:17 +0000323 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000324 case Type::VariableArray:
325 assert(0 && "VLAs not implemented yet!");
326 case Type::ConstantArray: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000327 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Naroff83c13012007-08-30 01:06:46 +0000328
Chris Lattner8cd0e932008-03-05 18:54:05 +0000329 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000330 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000331 Align = EltInfo.second;
332 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000333 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000334 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000335 case Type::Vector: {
336 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000337 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000338 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000339 Align = Width;
Nate Begeman7903d052009-01-18 06:42:49 +0000340 // If the alignment is not a power of 2, round up to the next power of 2.
341 // This happens for non-power-of-2 length vectors.
342 // FIXME: this should probably be a target property.
343 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000344 break;
345 }
346
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000347 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000348 switch (cast<BuiltinType>(T)->getKind()) {
349 default: assert(0 && "Unknown builtin type!");
350 case BuiltinType::Void:
351 assert(0 && "Incomplete types have no size!");
Chris Lattnerb66237b2007-12-19 19:23:28 +0000352 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000353 Width = Target.getBoolWidth();
354 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000355 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000356 case BuiltinType::Char_S:
357 case BuiltinType::Char_U:
358 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000359 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000360 Width = Target.getCharWidth();
361 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000362 break;
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000363 case BuiltinType::WChar:
364 Width = Target.getWCharWidth();
365 Align = Target.getWCharAlign();
366 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000367 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000368 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000369 Width = Target.getShortWidth();
370 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000371 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000372 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000373 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000374 Width = Target.getIntWidth();
375 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000376 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000377 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000378 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000379 Width = Target.getLongWidth();
380 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000381 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000382 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000383 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000384 Width = Target.getLongLongWidth();
385 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000386 break;
387 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000388 Width = Target.getFloatWidth();
389 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000390 break;
391 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000392 Width = Target.getDoubleWidth();
393 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000394 break;
395 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000396 Width = Target.getLongDoubleWidth();
397 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000398 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000399 }
400 break;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000401 case Type::FixedWidthInt:
402 // FIXME: This isn't precisely correct; the width/alignment should depend
403 // on the available types for the target
404 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattnere9174982009-02-15 21:20:13 +0000405 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000406 Align = Width;
407 break;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000408 case Type::ExtQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000409 // FIXME: Pointers into different addr spaces could have different sizes and
410 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000411 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Ted Kremenek42730c52008-01-07 19:49:32 +0000412 case Type::ObjCQualifiedId:
Eli Friedman2f6d70d2009-02-22 04:02:33 +0000413 case Type::ObjCQualifiedClass:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000414 case Type::ObjCQualifiedInterface:
Chris Lattner1d78a862008-04-07 07:01:58 +0000415 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000416 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000417 break;
Steve Naroff62f09f52008-09-24 15:05:44 +0000418 case Type::BlockPointer: {
419 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
420 Width = Target.getPointerWidth(AS);
421 Align = Target.getPointerAlign(AS);
422 break;
423 }
Chris Lattner461a6c52008-03-08 08:34:58 +0000424 case Type::Pointer: {
425 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000426 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000427 Align = Target.getPointerAlign(AS);
428 break;
429 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000430 case Type::LValueReference:
431 case Type::RValueReference:
Chris Lattner4b009652007-07-25 00:24:17 +0000432 // "When applied to a reference or a reference type, the result is the size
433 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000434 // FIXME: This is wrong for struct layout: a reference in a struct has
435 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000436 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl75555032009-01-24 21:16:55 +0000437 case Type::MemberPointer: {
Sebastian Redl18cffee2009-01-24 23:29:36 +0000438 // FIXME: This is not only platform- but also ABI-dependent. We follow
Sebastian Redl75555032009-01-24 21:16:55 +0000439 // the GCC ABI, where pointers to data are one pointer large, pointers to
440 // functions two pointers. But if we want to support ABI compatibility with
Sebastian Redl18cffee2009-01-24 23:29:36 +0000441 // other compilers too, we need to delegate this completely to TargetInfo
442 // or some ABI abstraction layer.
Sebastian Redl75555032009-01-24 21:16:55 +0000443 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
444 unsigned AS = Pointee.getAddressSpace();
445 Width = Target.getPointerWidth(AS);
446 if (Pointee->isFunctionType())
447 Width *= 2;
448 Align = Target.getPointerAlign(AS);
449 // GCC aligns at single pointer width.
450 }
Chris Lattner4b009652007-07-25 00:24:17 +0000451 case Type::Complex: {
452 // Complex types have the same alignment as their elements, but twice the
453 // size.
454 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000455 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000456 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000457 Align = EltInfo.second;
458 break;
459 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000460 case Type::ObjCInterface: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000461 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel4b6bf702008-06-04 21:54:36 +0000462 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
463 Width = Layout.getSize();
464 Align = Layout.getAlignment();
465 break;
466 }
Douglas Gregor4fa58902009-02-26 23:50:07 +0000467 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000468 case Type::Enum: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000469 const TagType *TT = cast<TagType>(T);
470
471 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattnerfd799692008-08-09 21:35:13 +0000472 Width = 1;
473 Align = 1;
474 break;
475 }
476
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000477 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000478 return getTypeInfo(ET->getDecl()->getIntegerType());
479
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000480 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000481 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
482 Width = Layout.getSize();
483 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000484 break;
485 }
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000486 }
Chris Lattner4b009652007-07-25 00:24:17 +0000487
488 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000489 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000490}
491
Chris Lattner83165b52009-01-27 18:08:34 +0000492/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
493/// type for the current target in bits. This can be different than the ABI
494/// alignment in cases where it is beneficial for performance to overalign
495/// a data type.
496unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
497 unsigned ABIAlign = getTypeAlign(T);
498
499 // Doubles should be naturally aligned if possible.
Daniel Dunbarc61a8002009-02-18 19:59:32 +0000500 if (T->isSpecificBuiltinType(BuiltinType::Double))
501 return std::max(ABIAlign, 64U);
Chris Lattner83165b52009-01-27 18:08:34 +0000502
503 return ABIAlign;
504}
505
506
Devang Patelbfe323c2008-06-04 21:22:16 +0000507/// LayoutField - Field layout.
508void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000509 bool IsUnion, unsigned StructPacking,
Devang Patelbfe323c2008-06-04 21:22:16 +0000510 ASTContext &Context) {
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000511 unsigned FieldPacking = StructPacking;
Devang Patelbfe323c2008-06-04 21:22:16 +0000512 uint64_t FieldOffset = IsUnion ? 0 : Size;
513 uint64_t FieldSize;
514 unsigned FieldAlign;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000515
516 // FIXME: Should this override struct packing? Probably we want to
517 // take the minimum?
518 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
519 FieldPacking = PA->getAlignment();
Devang Patelbfe323c2008-06-04 21:22:16 +0000520
521 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
522 // TODO: Need to check this algorithm on other targets!
523 // (tested on Linux-X86)
Daniel Dunbar7cbcbf42008-08-13 23:47:13 +0000524 FieldSize =
525 BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue();
Devang Patelbfe323c2008-06-04 21:22:16 +0000526
527 std::pair<uint64_t, unsigned> FieldInfo =
528 Context.getTypeInfo(FD->getType());
529 uint64_t TypeSize = FieldInfo.first;
530
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000531 // Determine the alignment of this bitfield. The packing
532 // attributes define a maximum and the alignment attribute defines
533 // a minimum.
534 // FIXME: What is the right behavior when the specified alignment
535 // is smaller than the specified packing?
Devang Patelbfe323c2008-06-04 21:22:16 +0000536 FieldAlign = FieldInfo.second;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000537 if (FieldPacking)
538 FieldAlign = std::min(FieldAlign, FieldPacking);
Devang Patelbfe323c2008-06-04 21:22:16 +0000539 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
540 FieldAlign = std::max(FieldAlign, AA->getAlignment());
541
542 // Check if we need to add padding to give the field the correct
543 // alignment.
544 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
545 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
546
547 // Padding members don't affect overall alignment
548 if (!FD->getIdentifier())
549 FieldAlign = 1;
550 } else {
Chris Lattnerfd799692008-08-09 21:35:13 +0000551 if (FD->getType()->isIncompleteArrayType()) {
552 // This is a flexible array member; we can't directly
Devang Patelbfe323c2008-06-04 21:22:16 +0000553 // query getTypeInfo about these, so we figure it out here.
554 // Flexible array members don't have any size, but they
555 // have to be aligned appropriately for their element type.
556 FieldSize = 0;
Chris Lattnera1923f62008-08-04 07:31:14 +0000557 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patelbfe323c2008-06-04 21:22:16 +0000558 FieldAlign = Context.getTypeAlign(ATy->getElementType());
559 } else {
560 std::pair<uint64_t, unsigned> FieldInfo =
561 Context.getTypeInfo(FD->getType());
562 FieldSize = FieldInfo.first;
563 FieldAlign = FieldInfo.second;
564 }
565
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000566 // Determine the alignment of this bitfield. The packing
567 // attributes define a maximum and the alignment attribute defines
568 // a minimum. Additionally, the packing alignment must be at least
569 // a byte for non-bitfields.
570 //
571 // FIXME: What is the right behavior when the specified alignment
572 // is smaller than the specified packing?
573 if (FieldPacking)
574 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Devang Patelbfe323c2008-06-04 21:22:16 +0000575 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
576 FieldAlign = std::max(FieldAlign, AA->getAlignment());
577
578 // Round up the current record size to the field's alignment boundary.
579 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
580 }
581
582 // Place this field at the current location.
583 FieldOffsets[FieldNo] = FieldOffset;
584
585 // Reserve space for this field.
586 if (IsUnion) {
587 Size = std::max(Size, FieldSize);
588 } else {
589 Size = FieldOffset + FieldSize;
590 }
591
592 // Remember max struct/class alignment.
593 Alignment = std::max(Alignment, FieldAlign);
594}
595
Fariborz Jahaniana2c97df2009-03-05 20:08:48 +0000596void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
597 std::vector<FieldDecl*> &Fields) const {
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000598 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
599 if (SuperClass)
600 CollectObjCIvars(SuperClass, Fields);
601 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
602 E = OI->ivar_end(); I != E; ++I) {
603 ObjCIvarDecl *IVDecl = (*I);
604 if (!IVDecl->isInvalidDecl())
605 Fields.push_back(cast<FieldDecl>(IVDecl));
606 }
607}
608
609/// addRecordToClass - produces record info. for the class for its
610/// ivars and all those inherited.
611///
612const RecordDecl *ASTContext::addRecordToClass(const ObjCInterfaceDecl *D)
613{
614 const RecordDecl *&RD = ASTRecordForInterface[D];
615 if (RD)
616 return RD;
617 std::vector<FieldDecl*> RecFields;
618 CollectObjCIvars(D, RecFields);
619 RecordDecl *NewRD = RecordDecl::Create(*this, TagDecl::TK_struct, 0,
620 D->getLocation(),
621 D->getIdentifier());
622 /// FIXME! Can do collection of ivars and adding to the record while
623 /// doing it.
624 for (unsigned int i = 0; i != RecFields.size(); i++) {
625 FieldDecl *Field = FieldDecl::Create(*this, NewRD,
626 RecFields[i]->getLocation(),
627 RecFields[i]->getIdentifier(),
628 RecFields[i]->getType(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000629 RecFields[i]->getBitWidth(), false);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000630 NewRD->addDecl(Field);
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000631 }
632 NewRD->completeDefinition(*this);
633 RD = NewRD;
634 return RD;
635}
Devang Patel4b6bf702008-06-04 21:54:36 +0000636
Fariborz Jahanianea944842008-12-18 17:29:46 +0000637/// setFieldDecl - maps a field for the given Ivar reference node.
638//
639void ASTContext::setFieldDecl(const ObjCInterfaceDecl *OI,
640 const ObjCIvarDecl *Ivar,
641 const ObjCIvarRefExpr *MRef) {
642 FieldDecl *FD = (const_cast<ObjCInterfaceDecl *>(OI))->
643 lookupFieldDeclForIvar(*this, Ivar);
644 ASTFieldForIvarRef[MRef] = FD;
645}
646
Chris Lattner2fda0ed2008-10-05 17:34:18 +0000647/// getASTObjcInterfaceLayout - Get or compute information about the layout of
648/// the specified Objective C, which indicates its size and ivar
Devang Patel4b6bf702008-06-04 21:54:36 +0000649/// position information.
650const ASTRecordLayout &
651ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
652 // Look up this layout, if already laid out, return what we have.
653 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
654 if (Entry) return *Entry;
655
656 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
657 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
Devang Patel8682d882008-06-06 02:14:01 +0000658 ASTRecordLayout *NewEntry = NULL;
659 unsigned FieldCount = D->ivar_size();
660 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
661 FieldCount++;
662 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
663 unsigned Alignment = SL.getAlignment();
664 uint64_t Size = SL.getSize();
665 NewEntry = new ASTRecordLayout(Size, Alignment);
666 NewEntry->InitializeLayout(FieldCount);
Chris Lattner2fda0ed2008-10-05 17:34:18 +0000667 // Super class is at the beginning of the layout.
668 NewEntry->SetFieldOffset(0, 0);
Devang Patel8682d882008-06-06 02:14:01 +0000669 } else {
670 NewEntry = new ASTRecordLayout();
671 NewEntry->InitializeLayout(FieldCount);
672 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000673 Entry = NewEntry;
674
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000675 unsigned StructPacking = 0;
676 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
677 StructPacking = PA->getAlignment();
Devang Patel4b6bf702008-06-04 21:54:36 +0000678
679 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
680 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
681 AA->getAlignment()));
682
683 // Layout each ivar sequentially.
684 unsigned i = 0;
685 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
686 IVE = D->ivar_end(); IVI != IVE; ++IVI) {
687 const ObjCIvarDecl* Ivar = (*IVI);
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000688 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
Devang Patel4b6bf702008-06-04 21:54:36 +0000689 }
690
691 // Finally, round the size of the total struct up to the alignment of the
692 // struct itself.
693 NewEntry->FinalizeLayout();
694 return *NewEntry;
695}
696
Devang Patel7a78e432007-11-01 19:11:01 +0000697/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000698/// specified record (struct/union/class), which indicates its size and field
699/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000700const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek46a837c2008-09-05 17:16:31 +0000701 D = D->getDefinition(*this);
702 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000703
Chris Lattner4b009652007-07-25 00:24:17 +0000704 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000705 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000706 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000707
Devang Patel7a78e432007-11-01 19:11:01 +0000708 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
709 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
710 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000711 Entry = NewEntry;
Eli Friedman5949a022008-05-30 09:31:38 +0000712
Douglas Gregor39677622008-12-11 20:41:00 +0000713 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000714 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000715 bool IsUnion = D->isUnion();
Chris Lattner4b009652007-07-25 00:24:17 +0000716
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000717 unsigned StructPacking = 0;
718 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
719 StructPacking = PA->getAlignment();
720
Eli Friedman5949a022008-05-30 09:31:38 +0000721 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patelbfe323c2008-06-04 21:22:16 +0000722 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
723 AA->getAlignment()));
Anders Carlsson058237f2008-02-18 07:13:09 +0000724
Eli Friedman5949a022008-05-30 09:31:38 +0000725 // Layout each field, for now, just sequentially, respecting alignment. In
726 // the future, this will need to be tweakable by targets.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000727 unsigned FieldIdx = 0;
Douglas Gregor5d764842009-01-09 17:18:27 +0000728 for (RecordDecl::field_iterator Field = D->field_begin(),
729 FieldEnd = D->field_end();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000730 Field != FieldEnd; (void)++Field, ++FieldIdx)
731 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman5949a022008-05-30 09:31:38 +0000732
733 // Finally, round the size of the total struct up to the alignment of the
734 // struct itself.
Devang Patelbfe323c2008-06-04 21:22:16 +0000735 NewEntry->FinalizeLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000736 return *NewEntry;
737}
738
Chris Lattner4b009652007-07-25 00:24:17 +0000739//===----------------------------------------------------------------------===//
740// Type creation/memoization methods
741//===----------------------------------------------------------------------===//
742
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000743QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000744 QualType CanT = getCanonicalType(T);
745 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000746 return T;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000747
748 // If we are composing extended qualifiers together, merge together into one
749 // ExtQualType node.
750 unsigned CVRQuals = T.getCVRQualifiers();
751 QualType::GCAttrTypes GCAttr = QualType::GCNone;
752 Type *TypeNode = T.getTypePtr();
Chris Lattner35fef522008-02-20 20:55:12 +0000753
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000754 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
755 // If this type already has an address space specified, it cannot get
756 // another one.
757 assert(EQT->getAddressSpace() == 0 &&
758 "Type cannot be in multiple addr spaces!");
759 GCAttr = EQT->getObjCGCAttr();
760 TypeNode = EQT->getBaseType();
761 }
Chris Lattner35fef522008-02-20 20:55:12 +0000762
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000763 // Check if we've already instantiated this type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000764 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000765 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000766 void *InsertPos = 0;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000767 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000768 return QualType(EXTQy, CVRQuals);
769
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000770 // If the base type isn't canonical, this won't be a canonical type either,
771 // so fill in the canonical type field.
772 QualType Canonical;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000773 if (!TypeNode->isCanonical()) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000774 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000775
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000776 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000777 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000778 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000779 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000780 ExtQualType *New =
781 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000782 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000783 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000784 return QualType(New, CVRQuals);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000785}
786
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000787QualType ASTContext::getObjCGCQualType(QualType T,
788 QualType::GCAttrTypes GCAttr) {
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000789 QualType CanT = getCanonicalType(T);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000790 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000791 return T;
792
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000793 // If we are composing extended qualifiers together, merge together into one
794 // ExtQualType node.
795 unsigned CVRQuals = T.getCVRQualifiers();
796 Type *TypeNode = T.getTypePtr();
797 unsigned AddressSpace = 0;
798
799 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
800 // If this type already has an address space specified, it cannot get
801 // another one.
802 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
803 "Type cannot be in multiple addr spaces!");
804 AddressSpace = EQT->getAddressSpace();
805 TypeNode = EQT->getBaseType();
806 }
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000807
808 // Check if we've already instantiated an gc qual'd type of this type.
809 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000810 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000811 void *InsertPos = 0;
812 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000813 return QualType(EXTQy, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000814
815 // If the base type isn't canonical, this won't be a canonical type either,
816 // so fill in the canonical type field.
Eli Friedman94fcc9a2009-02-27 23:04:43 +0000817 // FIXME: Isn't this also not canonical if the base type is a array
818 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000819 QualType Canonical;
820 if (!T->isCanonical()) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000821 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000822
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000823 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000824 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
825 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
826 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000827 ExtQualType *New =
828 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000829 ExtQualTypes.InsertNode(New, InsertPos);
830 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000831 return QualType(New, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000832}
Chris Lattner4b009652007-07-25 00:24:17 +0000833
834/// getComplexType - Return the uniqued reference to the type for a complex
835/// number with the specified element type.
836QualType ASTContext::getComplexType(QualType T) {
837 // Unique pointers, to guarantee there is only one pointer of a particular
838 // structure.
839 llvm::FoldingSetNodeID ID;
840 ComplexType::Profile(ID, T);
841
842 void *InsertPos = 0;
843 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
844 return QualType(CT, 0);
845
846 // If the pointee type isn't canonical, this won't be a canonical type either,
847 // so fill in the canonical type field.
848 QualType Canonical;
849 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000850 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000851
852 // Get the new insert position for the node we care about.
853 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000854 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000855 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000856 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000857 Types.push_back(New);
858 ComplexTypes.InsertNode(New, InsertPos);
859 return QualType(New, 0);
860}
861
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000862QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
863 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
864 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
865 FixedWidthIntType *&Entry = Map[Width];
866 if (!Entry)
867 Entry = new FixedWidthIntType(Width, Signed);
868 return QualType(Entry, 0);
869}
Chris Lattner4b009652007-07-25 00:24:17 +0000870
871/// getPointerType - Return the uniqued reference to the type for a pointer to
872/// the specified type.
873QualType ASTContext::getPointerType(QualType T) {
874 // Unique pointers, to guarantee there is only one pointer of a particular
875 // structure.
876 llvm::FoldingSetNodeID ID;
877 PointerType::Profile(ID, T);
878
879 void *InsertPos = 0;
880 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
881 return QualType(PT, 0);
882
883 // If the pointee type isn't canonical, this won't be a canonical type either,
884 // so fill in the canonical type field.
885 QualType Canonical;
886 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000887 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000888
889 // Get the new insert position for the node we care about.
890 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000891 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000892 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000893 PointerType *New = new (*this,8) PointerType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000894 Types.push_back(New);
895 PointerTypes.InsertNode(New, InsertPos);
896 return QualType(New, 0);
897}
898
Steve Naroff7aa54752008-08-27 16:04:49 +0000899/// getBlockPointerType - Return the uniqued reference to the type for
900/// a pointer to the specified block.
901QualType ASTContext::getBlockPointerType(QualType T) {
Steve Narofffd5b19d2008-08-28 19:20:44 +0000902 assert(T->isFunctionType() && "block of function types only");
903 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff7aa54752008-08-27 16:04:49 +0000904 // structure.
905 llvm::FoldingSetNodeID ID;
906 BlockPointerType::Profile(ID, T);
907
908 void *InsertPos = 0;
909 if (BlockPointerType *PT =
910 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
911 return QualType(PT, 0);
912
Steve Narofffd5b19d2008-08-28 19:20:44 +0000913 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff7aa54752008-08-27 16:04:49 +0000914 // type either so fill in the canonical type field.
915 QualType Canonical;
916 if (!T->isCanonical()) {
917 Canonical = getBlockPointerType(getCanonicalType(T));
918
919 // Get the new insert position for the node we care about.
920 BlockPointerType *NewIP =
921 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000922 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff7aa54752008-08-27 16:04:49 +0000923 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000924 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff7aa54752008-08-27 16:04:49 +0000925 Types.push_back(New);
926 BlockPointerTypes.InsertNode(New, InsertPos);
927 return QualType(New, 0);
928}
929
Sebastian Redlce6fff02009-03-16 23:22:08 +0000930/// getLValueReferenceType - Return the uniqued reference to the type for an
931/// lvalue reference to the specified type.
932QualType ASTContext::getLValueReferenceType(QualType T) {
Chris Lattner4b009652007-07-25 00:24:17 +0000933 // Unique pointers, to guarantee there is only one pointer of a particular
934 // structure.
935 llvm::FoldingSetNodeID ID;
936 ReferenceType::Profile(ID, T);
937
938 void *InsertPos = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000939 if (LValueReferenceType *RT =
940 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000941 return QualType(RT, 0);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000942
Chris Lattner4b009652007-07-25 00:24:17 +0000943 // If the referencee type isn't canonical, this won't be a canonical type
944 // either, so fill in the canonical type field.
945 QualType Canonical;
946 if (!T->isCanonical()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +0000947 Canonical = getLValueReferenceType(getCanonicalType(T));
948
Chris Lattner4b009652007-07-25 00:24:17 +0000949 // Get the new insert position for the node we care about.
Sebastian Redlce6fff02009-03-16 23:22:08 +0000950 LValueReferenceType *NewIP =
951 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000952 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000953 }
954
Sebastian Redlce6fff02009-03-16 23:22:08 +0000955 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000956 Types.push_back(New);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000957 LValueReferenceTypes.InsertNode(New, InsertPos);
958 return QualType(New, 0);
959}
960
961/// getRValueReferenceType - Return the uniqued reference to the type for an
962/// rvalue reference to the specified type.
963QualType ASTContext::getRValueReferenceType(QualType T) {
964 // Unique pointers, to guarantee there is only one pointer of a particular
965 // structure.
966 llvm::FoldingSetNodeID ID;
967 ReferenceType::Profile(ID, T);
968
969 void *InsertPos = 0;
970 if (RValueReferenceType *RT =
971 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
972 return QualType(RT, 0);
973
974 // If the referencee type isn't canonical, this won't be a canonical type
975 // either, so fill in the canonical type field.
976 QualType Canonical;
977 if (!T->isCanonical()) {
978 Canonical = getRValueReferenceType(getCanonicalType(T));
979
980 // Get the new insert position for the node we care about.
981 RValueReferenceType *NewIP =
982 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
983 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
984 }
985
986 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
987 Types.push_back(New);
988 RValueReferenceTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000989 return QualType(New, 0);
990}
991
Sebastian Redl75555032009-01-24 21:16:55 +0000992/// getMemberPointerType - Return the uniqued reference to the type for a
993/// member pointer to the specified type, in the specified class.
994QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
995{
996 // Unique pointers, to guarantee there is only one pointer of a particular
997 // structure.
998 llvm::FoldingSetNodeID ID;
999 MemberPointerType::Profile(ID, T, Cls);
1000
1001 void *InsertPos = 0;
1002 if (MemberPointerType *PT =
1003 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1004 return QualType(PT, 0);
1005
1006 // If the pointee or class type isn't canonical, this won't be a canonical
1007 // type either, so fill in the canonical type field.
1008 QualType Canonical;
1009 if (!T->isCanonical()) {
1010 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1011
1012 // Get the new insert position for the node we care about.
1013 MemberPointerType *NewIP =
1014 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1015 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1016 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001017 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redl75555032009-01-24 21:16:55 +00001018 Types.push_back(New);
1019 MemberPointerTypes.InsertNode(New, InsertPos);
1020 return QualType(New, 0);
1021}
1022
Steve Naroff83c13012007-08-30 01:06:46 +00001023/// getConstantArrayType - Return the unique reference to the type for an
1024/// array of the specified element type.
1025QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +00001026 const llvm::APInt &ArySize,
1027 ArrayType::ArraySizeModifier ASM,
1028 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +00001029 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001030 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001031
1032 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +00001033 if (ConstantArrayType *ATP =
1034 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001035 return QualType(ATP, 0);
1036
1037 // If the element type isn't canonical, this won't be a canonical type either,
1038 // so fill in the canonical type field.
1039 QualType Canonical;
1040 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001041 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +00001042 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001043 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +00001044 ConstantArrayType *NewIP =
1045 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001046 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001047 }
1048
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001049 ConstantArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001050 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001051 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001052 Types.push_back(New);
1053 return QualType(New, 0);
1054}
1055
Steve Naroffe2579e32007-08-30 18:14:25 +00001056/// getVariableArrayType - Returns a non-unique reference to the type for a
1057/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +00001058QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1059 ArrayType::ArraySizeModifier ASM,
1060 unsigned EltTypeQuals) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001061 // Since we don't unique expressions, it isn't possible to unique VLA's
1062 // that have an expression provided for their size.
1063
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001064 VariableArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001065 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001066
1067 VariableArrayTypes.push_back(New);
1068 Types.push_back(New);
1069 return QualType(New, 0);
1070}
1071
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001072/// getDependentSizedArrayType - Returns a non-unique reference to
1073/// the type for a dependently-sized array of the specified element
1074/// type. FIXME: We will need these to be uniqued, or at least
1075/// comparable, at some point.
1076QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1077 ArrayType::ArraySizeModifier ASM,
1078 unsigned EltTypeQuals) {
1079 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1080 "Size must be type- or value-dependent!");
1081
1082 // Since we don't unique expressions, it isn't possible to unique
1083 // dependently-sized array types.
1084
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001085 DependentSizedArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001086 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1087 ASM, EltTypeQuals);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001088
1089 DependentSizedArrayTypes.push_back(New);
1090 Types.push_back(New);
1091 return QualType(New, 0);
1092}
1093
Eli Friedman8ff07782008-02-15 18:16:39 +00001094QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1095 ArrayType::ArraySizeModifier ASM,
1096 unsigned EltTypeQuals) {
1097 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001098 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001099
1100 void *InsertPos = 0;
1101 if (IncompleteArrayType *ATP =
1102 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1103 return QualType(ATP, 0);
1104
1105 // If the element type isn't canonical, this won't be a canonical type
1106 // either, so fill in the canonical type field.
1107 QualType Canonical;
1108
1109 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001110 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001111 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001112
1113 // Get the new insert position for the node we care about.
1114 IncompleteArrayType *NewIP =
1115 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001116 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001117 }
Eli Friedman8ff07782008-02-15 18:16:39 +00001118
Steve Naroff93fd2112009-01-27 22:08:43 +00001119 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001120 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001121
1122 IncompleteArrayTypes.InsertNode(New, InsertPos);
1123 Types.push_back(New);
1124 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +00001125}
1126
Chris Lattner4b009652007-07-25 00:24:17 +00001127/// getVectorType - Return the unique reference to a vector type of
1128/// the specified element type and size. VectorType must be a built-in type.
1129QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1130 BuiltinType *baseType;
1131
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001132 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +00001133 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1134
1135 // Check if we've already instantiated a vector of this type.
1136 llvm::FoldingSetNodeID ID;
1137 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1138 void *InsertPos = 0;
1139 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1140 return QualType(VTP, 0);
1141
1142 // If the element type isn't canonical, this won't be a canonical type either,
1143 // so fill in the canonical type field.
1144 QualType Canonical;
1145 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001146 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001147
1148 // Get the new insert position for the node we care about.
1149 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001150 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001151 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001152 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001153 VectorTypes.InsertNode(New, InsertPos);
1154 Types.push_back(New);
1155 return QualType(New, 0);
1156}
1157
Nate Begemanaf6ed502008-04-18 23:10:10 +00001158/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +00001159/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001160QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +00001161 BuiltinType *baseType;
1162
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001163 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +00001164 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +00001165
1166 // Check if we've already instantiated a vector of this type.
1167 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +00001168 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +00001169 void *InsertPos = 0;
1170 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1171 return QualType(VTP, 0);
1172
1173 // If the element type isn't canonical, this won't be a canonical type either,
1174 // so fill in the canonical type field.
1175 QualType Canonical;
1176 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001177 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001178
1179 // Get the new insert position for the node we care about.
1180 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001181 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001182 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001183 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001184 VectorTypes.InsertNode(New, InsertPos);
1185 Types.push_back(New);
1186 return QualType(New, 0);
1187}
1188
Douglas Gregor4fa58902009-02-26 23:50:07 +00001189/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattner4b009652007-07-25 00:24:17 +00001190///
Douglas Gregor4fa58902009-02-26 23:50:07 +00001191QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Chris Lattner4b009652007-07-25 00:24:17 +00001192 // Unique functions, to guarantee there is only one function of a particular
1193 // structure.
1194 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001195 FunctionNoProtoType::Profile(ID, ResultTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001196
1197 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001198 if (FunctionNoProtoType *FT =
1199 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001200 return QualType(FT, 0);
1201
1202 QualType Canonical;
1203 if (!ResultTy->isCanonical()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00001204 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001205
1206 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001207 FunctionNoProtoType *NewIP =
1208 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001209 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001210 }
1211
Douglas Gregor4fa58902009-02-26 23:50:07 +00001212 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001213 Types.push_back(New);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001214 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001215 return QualType(New, 0);
1216}
1217
1218/// getFunctionType - Return a normal function type with a typed argument
1219/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner2fda0ed2008-10-05 17:34:18 +00001220QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001221 unsigned NumArgs, bool isVariadic,
1222 unsigned TypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +00001223 // Unique functions, to guarantee there is only one function of a particular
1224 // structure.
1225 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001226 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001227 TypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001228
1229 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001230 if (FunctionProtoType *FTP =
1231 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001232 return QualType(FTP, 0);
1233
1234 // Determine whether the type being created is already canonical or not.
1235 bool isCanonical = ResultTy->isCanonical();
1236 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1237 if (!ArgArray[i]->isCanonical())
1238 isCanonical = false;
1239
1240 // If this type isn't canonical, get the canonical version of it.
1241 QualType Canonical;
1242 if (!isCanonical) {
1243 llvm::SmallVector<QualType, 16> CanonicalArgs;
1244 CanonicalArgs.reserve(NumArgs);
1245 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001246 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Chris Lattner4b009652007-07-25 00:24:17 +00001247
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001248 Canonical = getFunctionType(getCanonicalType(ResultTy),
Chris Lattner4b009652007-07-25 00:24:17 +00001249 &CanonicalArgs[0], NumArgs,
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001250 isVariadic, TypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001251
1252 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001253 FunctionProtoType *NewIP =
1254 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001255 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001256 }
1257
Douglas Gregor4fa58902009-02-26 23:50:07 +00001258 // FunctionProtoType objects are allocated with extra bytes after them
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001259 // for a variable size array (for parameter types) at the end of them.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001260 FunctionProtoType *FTP =
1261 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
Steve Naroff207b9ec2009-01-27 23:20:32 +00001262 NumArgs*sizeof(QualType), 8);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001263 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001264 TypeQuals, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001265 Types.push_back(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001266 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001267 return QualType(FTP, 0);
1268}
1269
Douglas Gregor1d661552008-04-13 21:07:44 +00001270/// getTypeDeclType - Return the unique reference to the type for the
1271/// specified type declaration.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001272QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001273 assert(Decl && "Passed null for Decl param");
Douglas Gregor1d661552008-04-13 21:07:44 +00001274 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1275
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001276 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001277 return getTypedefType(Typedef);
Douglas Gregora4918772009-02-05 23:33:38 +00001278 else if (isa<TemplateTypeParmDecl>(Decl)) {
1279 assert(false && "Template type parameter types are always available.");
1280 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001281 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001282
Douglas Gregor2e047592009-02-28 01:32:25 +00001283 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001284 if (PrevDecl)
1285 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001286 else
1287 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek46a837c2008-09-05 17:16:31 +00001288 }
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001289 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1290 if (PrevDecl)
1291 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001292 else
1293 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001294 }
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001295 else
Douglas Gregor1d661552008-04-13 21:07:44 +00001296 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001297
Ted Kremenek46a837c2008-09-05 17:16:31 +00001298 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001299 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +00001300}
1301
Chris Lattner4b009652007-07-25 00:24:17 +00001302/// getTypedefType - Return the unique reference to the type for the
1303/// specified typename decl.
1304QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1305 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1306
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001307 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001308 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001309 Types.push_back(Decl->TypeForDecl);
1310 return QualType(Decl->TypeForDecl, 0);
1311}
1312
Ted Kremenek42730c52008-01-07 19:49:32 +00001313/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff81f1bba2007-09-06 21:24:23 +00001314/// specified ObjC interface decl.
Ted Kremenek42730c52008-01-07 19:49:32 +00001315QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
Steve Naroff81f1bba2007-09-06 21:24:23 +00001316 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1317
Steve Naroff93fd2112009-01-27 22:08:43 +00001318 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
Steve Naroff81f1bba2007-09-06 21:24:23 +00001319 Types.push_back(Decl->TypeForDecl);
1320 return QualType(Decl->TypeForDecl, 0);
1321}
1322
Fariborz Jahanian27ecc672009-02-14 20:13:28 +00001323/// buildObjCInterfaceType - Returns a new type for the interface
1324/// declaration, regardless. It also removes any previously built
1325/// record declaration so caller can rebuild it.
1326QualType ASTContext::buildObjCInterfaceType(ObjCInterfaceDecl *Decl) {
1327 const RecordDecl *&RD = ASTRecordForInterface[Decl];
1328 if (RD)
1329 RD = 0;
1330 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
1331 Types.push_back(Decl->TypeForDecl);
1332 return QualType(Decl->TypeForDecl, 0);
1333}
1334
Douglas Gregora4918772009-02-05 23:33:38 +00001335/// \brief Retrieve the template type parameter type for a template
1336/// parameter with the given depth, index, and (optionally) name.
1337QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1338 IdentifierInfo *Name) {
1339 llvm::FoldingSetNodeID ID;
1340 TemplateTypeParmType::Profile(ID, Depth, Index, Name);
1341 void *InsertPos = 0;
1342 TemplateTypeParmType *TypeParm
1343 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1344
1345 if (TypeParm)
1346 return QualType(TypeParm, 0);
1347
1348 if (Name)
1349 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name,
1350 getTemplateTypeParmType(Depth, Index));
1351 else
1352 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index);
1353
1354 Types.push_back(TypeParm);
1355 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1356
1357 return QualType(TypeParm, 0);
1358}
1359
Douglas Gregor8e458f42009-02-09 18:46:07 +00001360QualType
1361ASTContext::getClassTemplateSpecializationType(TemplateDecl *Template,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001362 const TemplateArgument *Args,
Douglas Gregor8e458f42009-02-09 18:46:07 +00001363 unsigned NumArgs,
Douglas Gregor8e458f42009-02-09 18:46:07 +00001364 QualType Canon) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001365 if (!Canon.isNull())
1366 Canon = getCanonicalType(Canon);
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001367
Douglas Gregor8e458f42009-02-09 18:46:07 +00001368 llvm::FoldingSetNodeID ID;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001369 ClassTemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
1370
Douglas Gregor8e458f42009-02-09 18:46:07 +00001371 void *InsertPos = 0;
1372 ClassTemplateSpecializationType *Spec
1373 = ClassTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1374
1375 if (Spec)
1376 return QualType(Spec, 0);
1377
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001378 void *Mem = Allocate((sizeof(ClassTemplateSpecializationType) +
1379 sizeof(TemplateArgument) * NumArgs),
1380 8);
1381 Spec = new (Mem) ClassTemplateSpecializationType(Template, Args, NumArgs,
1382 Canon);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001383 Types.push_back(Spec);
1384 ClassTemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1385
1386 return QualType(Spec, 0);
1387}
1388
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001389QualType
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001390ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001391 QualType NamedType) {
1392 llvm::FoldingSetNodeID ID;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001393 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001394
1395 void *InsertPos = 0;
1396 QualifiedNameType *T
1397 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1398 if (T)
1399 return QualType(T, 0);
1400
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001401 T = new (*this) QualifiedNameType(NNS, NamedType,
1402 getCanonicalType(NamedType));
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001403 Types.push_back(T);
1404 QualifiedNameTypes.InsertNode(T, InsertPos);
1405 return QualType(T, 0);
1406}
1407
Douglas Gregord3022602009-03-27 23:10:48 +00001408QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1409 const IdentifierInfo *Name,
1410 QualType Canon) {
1411 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1412
1413 if (Canon.isNull()) {
1414 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1415 if (CanonNNS != NNS)
1416 Canon = getTypenameType(CanonNNS, Name);
1417 }
1418
1419 llvm::FoldingSetNodeID ID;
1420 TypenameType::Profile(ID, NNS, Name);
1421
1422 void *InsertPos = 0;
1423 TypenameType *T
1424 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1425 if (T)
1426 return QualType(T, 0);
1427
1428 T = new (*this) TypenameType(NNS, Name, Canon);
1429 Types.push_back(T);
1430 TypenameTypes.InsertNode(T, InsertPos);
1431 return QualType(T, 0);
1432}
1433
Chris Lattnere1352302008-04-07 04:56:42 +00001434/// CmpProtocolNames - Comparison predicate for sorting protocols
1435/// alphabetically.
1436static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1437 const ObjCProtocolDecl *RHS) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001438 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere1352302008-04-07 04:56:42 +00001439}
1440
1441static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1442 unsigned &NumProtocols) {
1443 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1444
1445 // Sort protocols, keyed by name.
1446 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1447
1448 // Remove duplicates.
1449 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1450 NumProtocols = ProtocolsEnd-Protocols;
1451}
1452
1453
Chris Lattnerb0c6a1f2008-04-07 04:44:08 +00001454/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1455/// the given interface decl and the conforming protocol list.
Ted Kremenek42730c52008-01-07 19:49:32 +00001456QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1457 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +00001458 // Sort the protocol list alphabetically to canonicalize it.
1459 SortAndUniqueProtocols(Protocols, NumProtocols);
1460
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001461 llvm::FoldingSetNodeID ID;
Chris Lattner7cdcb252008-04-07 06:38:24 +00001462 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001463
1464 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001465 if (ObjCQualifiedInterfaceType *QT =
1466 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001467 return QualType(QT, 0);
1468
1469 // No Match;
Ted Kremenek42730c52008-01-07 19:49:32 +00001470 ObjCQualifiedInterfaceType *QType =
Steve Naroff93fd2112009-01-27 22:08:43 +00001471 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001472
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001473 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001474 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001475 return QualType(QType, 0);
1476}
1477
Chris Lattnere1352302008-04-07 04:56:42 +00001478/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1479/// and the conforming protocol list.
Chris Lattner4a68fe02008-07-26 00:46:50 +00001480QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001481 unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +00001482 // Sort the protocol list alphabetically to canonicalize it.
1483 SortAndUniqueProtocols(Protocols, NumProtocols);
1484
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001485 llvm::FoldingSetNodeID ID;
Ted Kremenek42730c52008-01-07 19:49:32 +00001486 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001487
1488 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001489 if (ObjCQualifiedIdType *QT =
Chris Lattner4a68fe02008-07-26 00:46:50 +00001490 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001491 return QualType(QT, 0);
1492
1493 // No Match;
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001494 ObjCQualifiedIdType *QType =
Steve Naroff93fd2112009-01-27 22:08:43 +00001495 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001496 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001497 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001498 return QualType(QType, 0);
1499}
1500
Douglas Gregor4fa58902009-02-26 23:50:07 +00001501/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1502/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff0604dd92007-08-01 18:02:17 +00001503/// multiple declarations that refer to "typeof(x)" all contain different
1504/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1505/// on canonical type's (which are always unique).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001506QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001507 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001508 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001509 Types.push_back(toe);
1510 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001511}
1512
Steve Naroff0604dd92007-08-01 18:02:17 +00001513/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1514/// TypeOfType AST's. The only motivation to unique these nodes would be
1515/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1516/// an issue. This doesn't effect the type checker, since it operates
1517/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +00001518QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001519 QualType Canonical = getCanonicalType(tofType);
Steve Naroff93fd2112009-01-27 22:08:43 +00001520 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001521 Types.push_back(tot);
1522 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001523}
1524
Chris Lattner4b009652007-07-25 00:24:17 +00001525/// getTagDeclType - Return the unique reference to the type for the
1526/// specified TagDecl (struct/union/class/enum) decl.
1527QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +00001528 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +00001529 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001530}
1531
1532/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1533/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1534/// needs to agree with the definition in <stddef.h>.
1535QualType ASTContext::getSizeType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001536 return getFromTargetType(Target.getSizeType());
Chris Lattner4b009652007-07-25 00:24:17 +00001537}
1538
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001539/// getSignedWCharType - Return the type of "signed wchar_t".
1540/// Used when in C++, as a GCC extension.
1541QualType ASTContext::getSignedWCharType() const {
1542 // FIXME: derive from "Target" ?
1543 return WCharTy;
1544}
1545
1546/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1547/// Used when in C++, as a GCC extension.
1548QualType ASTContext::getUnsignedWCharType() const {
1549 // FIXME: derive from "Target" ?
1550 return UnsignedIntTy;
1551}
1552
Chris Lattner4b009652007-07-25 00:24:17 +00001553/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1554/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1555QualType ASTContext::getPointerDiffType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001556 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner4b009652007-07-25 00:24:17 +00001557}
1558
Chris Lattner19eb97e2008-04-02 05:18:44 +00001559//===----------------------------------------------------------------------===//
1560// Type Operators
1561//===----------------------------------------------------------------------===//
1562
Chris Lattner3dae6f42008-04-06 22:41:35 +00001563/// getCanonicalType - Return the canonical (structural) type corresponding to
1564/// the specified potentially non-canonical type. The non-canonical version
1565/// of a type may have many "decorated" versions of types. Decorators can
1566/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1567/// to be free of any of these, allowing two canonical types to be compared
1568/// for exact equality with a simple pointer comparison.
1569QualType ASTContext::getCanonicalType(QualType T) {
1570 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001571
1572 // If the result has type qualifiers, make sure to canonicalize them as well.
1573 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1574 if (TypeQuals == 0) return CanType;
1575
1576 // If the type qualifiers are on an array type, get the canonical type of the
1577 // array with the qualifiers applied to the element type.
1578 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1579 if (!AT)
1580 return CanType.getQualifiedType(TypeQuals);
1581
1582 // Get the canonical version of the element with the extra qualifiers on it.
1583 // This can recursively sink qualifiers through multiple levels of arrays.
1584 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1585 NewEltTy = getCanonicalType(NewEltTy);
1586
1587 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1588 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1589 CAT->getIndexTypeQualifier());
1590 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1591 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1592 IAT->getIndexTypeQualifier());
1593
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001594 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1595 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1596 DSAT->getSizeModifier(),
1597 DSAT->getIndexTypeQualifier());
1598
Chris Lattnera1923f62008-08-04 07:31:14 +00001599 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1600 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1601 VAT->getSizeModifier(),
1602 VAT->getIndexTypeQualifier());
1603}
1604
Douglas Gregord3022602009-03-27 23:10:48 +00001605NestedNameSpecifier *
1606ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1607 if (!NNS)
1608 return 0;
1609
1610 switch (NNS->getKind()) {
1611 case NestedNameSpecifier::Identifier:
1612 // Canonicalize the prefix but keep the identifier the same.
1613 return NestedNameSpecifier::Create(*this,
1614 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1615 NNS->getAsIdentifier());
1616
1617 case NestedNameSpecifier::Namespace:
1618 // A namespace is canonical; build a nested-name-specifier with
1619 // this namespace and no prefix.
1620 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1621
1622 case NestedNameSpecifier::TypeSpec:
1623 case NestedNameSpecifier::TypeSpecWithTemplate: {
1624 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1625 NestedNameSpecifier *Prefix = 0;
1626
1627 // FIXME: This isn't the right check!
1628 if (T->isDependentType())
1629 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1630
1631 return NestedNameSpecifier::Create(*this, Prefix,
1632 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1633 T.getTypePtr());
1634 }
1635
1636 case NestedNameSpecifier::Global:
1637 // The global specifier is canonical and unique.
1638 return NNS;
1639 }
1640
1641 // Required to silence a GCC warning
1642 return 0;
1643}
1644
Chris Lattnera1923f62008-08-04 07:31:14 +00001645
1646const ArrayType *ASTContext::getAsArrayType(QualType T) {
1647 // Handle the non-qualified case efficiently.
1648 if (T.getCVRQualifiers() == 0) {
1649 // Handle the common positive case fast.
1650 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1651 return AT;
1652 }
1653
1654 // Handle the common negative case fast, ignoring CVR qualifiers.
1655 QualType CType = T->getCanonicalTypeInternal();
1656
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001657 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnera1923f62008-08-04 07:31:14 +00001658 // test.
1659 if (!isa<ArrayType>(CType) &&
1660 !isa<ArrayType>(CType.getUnqualifiedType()))
1661 return 0;
1662
1663 // Apply any CVR qualifiers from the array type to the element type. This
1664 // implements C99 6.7.3p8: "If the specification of an array type includes
1665 // any type qualifiers, the element type is so qualified, not the array type."
1666
1667 // If we get here, we either have type qualifiers on the type, or we have
1668 // sugar such as a typedef in the way. If we have type qualifiers on the type
1669 // we must propagate them down into the elemeng type.
1670 unsigned CVRQuals = T.getCVRQualifiers();
1671 unsigned AddrSpace = 0;
1672 Type *Ty = T.getTypePtr();
1673
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001674 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001675 while (1) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001676 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1677 AddrSpace = EXTQT->getAddressSpace();
1678 Ty = EXTQT->getBaseType();
Chris Lattnera1923f62008-08-04 07:31:14 +00001679 } else {
1680 T = Ty->getDesugaredType();
1681 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1682 break;
1683 CVRQuals |= T.getCVRQualifiers();
1684 Ty = T.getTypePtr();
1685 }
1686 }
1687
1688 // If we have a simple case, just return now.
1689 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1690 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1691 return ATy;
1692
1693 // Otherwise, we have an array and we have qualifiers on it. Push the
1694 // qualifiers into the array element type and return a new array type.
1695 // Get the canonical version of the element with the extra qualifiers on it.
1696 // This can recursively sink qualifiers through multiple levels of arrays.
1697 QualType NewEltTy = ATy->getElementType();
1698 if (AddrSpace)
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001699 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnera1923f62008-08-04 07:31:14 +00001700 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1701
1702 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1703 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1704 CAT->getSizeModifier(),
1705 CAT->getIndexTypeQualifier()));
1706 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1707 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1708 IAT->getSizeModifier(),
1709 IAT->getIndexTypeQualifier()));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001710
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001711 if (const DependentSizedArrayType *DSAT
1712 = dyn_cast<DependentSizedArrayType>(ATy))
1713 return cast<ArrayType>(
1714 getDependentSizedArrayType(NewEltTy,
1715 DSAT->getSizeExpr(),
1716 DSAT->getSizeModifier(),
1717 DSAT->getIndexTypeQualifier()));
Chris Lattnera1923f62008-08-04 07:31:14 +00001718
Chris Lattnera1923f62008-08-04 07:31:14 +00001719 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1720 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1721 VAT->getSizeModifier(),
1722 VAT->getIndexTypeQualifier()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00001723}
1724
1725
Chris Lattner19eb97e2008-04-02 05:18:44 +00001726/// getArrayDecayedType - Return the properly qualified result of decaying the
1727/// specified array type to a pointer. This operation is non-trivial when
1728/// handling typedefs etc. The canonical type of "T" must be an array type,
1729/// this returns a pointer to a properly qualified element of the array.
1730///
1731/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1732QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001733 // Get the element type with 'getAsArrayType' so that we don't lose any
1734 // typedefs in the element type of the array. This also handles propagation
1735 // of type qualifiers from the array type into the element type if present
1736 // (C99 6.7.3p8).
1737 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1738 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00001739
Chris Lattnera1923f62008-08-04 07:31:14 +00001740 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001741
1742 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00001743 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001744}
1745
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001746QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson76d19c82008-12-21 03:44:36 +00001747 QualType ElemTy = VAT->getElementType();
1748
1749 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1750 return getBaseElementType(VAT);
1751
1752 return ElemTy;
1753}
1754
Chris Lattner4b009652007-07-25 00:24:17 +00001755/// getFloatingRank - Return a relative rank for floating point types.
1756/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001757static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001758 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00001759 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00001760
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001761 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001762 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00001763 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00001764 case BuiltinType::Float: return FloatRank;
1765 case BuiltinType::Double: return DoubleRank;
1766 case BuiltinType::LongDouble: return LongDoubleRank;
1767 }
1768}
1769
Steve Narofffa0c4532007-08-27 01:41:48 +00001770/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1771/// point or a complex type (based on typeDomain/typeSize).
1772/// 'typeDomain' is a real floating point or complex type.
1773/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00001774QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1775 QualType Domain) const {
1776 FloatingRank EltRank = getFloatingRank(Size);
1777 if (Domain->isComplexType()) {
1778 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00001779 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00001780 case FloatRank: return FloatComplexTy;
1781 case DoubleRank: return DoubleComplexTy;
1782 case LongDoubleRank: return LongDoubleComplexTy;
1783 }
Chris Lattner4b009652007-07-25 00:24:17 +00001784 }
Chris Lattner7794ae22008-04-06 23:58:54 +00001785
1786 assert(Domain->isRealFloatingType() && "Unknown domain!");
1787 switch (EltRank) {
1788 default: assert(0 && "getFloatingRank(): illegal value for rank");
1789 case FloatRank: return FloatTy;
1790 case DoubleRank: return DoubleTy;
1791 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00001792 }
Chris Lattner4b009652007-07-25 00:24:17 +00001793}
1794
Chris Lattner51285d82008-04-06 23:55:33 +00001795/// getFloatingTypeOrder - Compare the rank of the two specified floating
1796/// point types, ignoring the domain of the type (i.e. 'double' ==
1797/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1798/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001799int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1800 FloatingRank LHSR = getFloatingRank(LHS);
1801 FloatingRank RHSR = getFloatingRank(RHS);
1802
1803 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001804 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00001805 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001806 return 1;
1807 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00001808}
1809
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001810/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1811/// routine will assert if passed a built-in type that isn't an integer or enum,
1812/// or if it is not canonicalized.
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001813unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001814 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001815 if (EnumType* ET = dyn_cast<EnumType>(T))
1816 T = ET->getDecl()->getIntegerType().getTypePtr();
1817
1818 // There are two things which impact the integer rank: the width, and
1819 // the ordering of builtins. The builtin ordering is encoded in the
1820 // bottom three bits; the width is encoded in the bits above that.
1821 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
1822 return FWIT->getWidth() << 3;
1823 }
1824
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001825 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00001826 default: assert(0 && "getIntegerRank(): not a built-in integer");
1827 case BuiltinType::Bool:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001828 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001829 case BuiltinType::Char_S:
1830 case BuiltinType::Char_U:
1831 case BuiltinType::SChar:
1832 case BuiltinType::UChar:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001833 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001834 case BuiltinType::Short:
1835 case BuiltinType::UShort:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001836 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001837 case BuiltinType::Int:
1838 case BuiltinType::UInt:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001839 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001840 case BuiltinType::Long:
1841 case BuiltinType::ULong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001842 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001843 case BuiltinType::LongLong:
1844 case BuiltinType::ULongLong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001845 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001846 }
1847}
1848
Chris Lattner51285d82008-04-06 23:55:33 +00001849/// getIntegerTypeOrder - Returns the highest ranked integer type:
1850/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
1851/// LHS < RHS, return -1.
1852int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001853 Type *LHSC = getCanonicalType(LHS).getTypePtr();
1854 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00001855 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001856
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001857 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1858 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00001859
Chris Lattner51285d82008-04-06 23:55:33 +00001860 unsigned LHSRank = getIntegerRank(LHSC);
1861 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00001862
Chris Lattner51285d82008-04-06 23:55:33 +00001863 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
1864 if (LHSRank == RHSRank) return 0;
1865 return LHSRank > RHSRank ? 1 : -1;
1866 }
Chris Lattner4b009652007-07-25 00:24:17 +00001867
Chris Lattner51285d82008-04-06 23:55:33 +00001868 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1869 if (LHSUnsigned) {
1870 // If the unsigned [LHS] type is larger, return it.
1871 if (LHSRank >= RHSRank)
1872 return 1;
1873
1874 // If the signed type can represent all values of the unsigned type, it
1875 // wins. Because we are dealing with 2's complement and types that are
1876 // powers of two larger than each other, this is always safe.
1877 return -1;
1878 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001879
Chris Lattner51285d82008-04-06 23:55:33 +00001880 // If the unsigned [RHS] type is larger, return it.
1881 if (RHSRank >= LHSRank)
1882 return -1;
1883
1884 // If the signed type can represent all values of the unsigned type, it
1885 // wins. Because we are dealing with 2's complement and types that are
1886 // powers of two larger than each other, this is always safe.
1887 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001888}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001889
1890// getCFConstantStringType - Return the type used for constant CFStrings.
1891QualType ASTContext::getCFConstantStringType() {
1892 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00001893 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001894 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001895 &Idents.get("NSConstantString"));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001896 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001897
1898 // const int *isa;
1899 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001900 // int flags;
1901 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001902 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001903 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001904 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001905 FieldTypes[3] = LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001906
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001907 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00001908 for (unsigned i = 0; i < 4; ++i) {
1909 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
1910 SourceLocation(), 0,
1911 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001912 /*Mutable=*/false);
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001913 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001914 }
1915
1916 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001917 }
1918
1919 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00001920}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001921
Anders Carlssonf58cac72008-08-30 19:34:46 +00001922QualType ASTContext::getObjCFastEnumerationStateType()
1923{
1924 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001925 ObjCFastEnumerationStateTypeDecl =
1926 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1927 &Idents.get("__objcFastEnumerationState"));
1928
Anders Carlssonf58cac72008-08-30 19:34:46 +00001929 QualType FieldTypes[] = {
1930 UnsignedLongTy,
1931 getPointerType(ObjCIdType),
1932 getPointerType(UnsignedLongTy),
1933 getConstantArrayType(UnsignedLongTy,
1934 llvm::APInt(32, 5), ArrayType::Normal, 0)
1935 };
1936
Douglas Gregor8acb7272008-12-11 16:49:14 +00001937 for (size_t i = 0; i < 4; ++i) {
1938 FieldDecl *Field = FieldDecl::Create(*this,
1939 ObjCFastEnumerationStateTypeDecl,
1940 SourceLocation(), 0,
1941 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001942 /*Mutable=*/false);
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001943 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001944 }
Anders Carlssonf58cac72008-08-30 19:34:46 +00001945
Douglas Gregor8acb7272008-12-11 16:49:14 +00001946 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonf58cac72008-08-30 19:34:46 +00001947 }
1948
1949 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
1950}
1951
Anders Carlssone3f02572007-10-29 06:33:42 +00001952// This returns true if a type has been typedefed to BOOL:
1953// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00001954static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00001955 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner85fb3842008-11-24 03:52:59 +00001956 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
1957 return II->isStr("BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001958
1959 return false;
1960}
1961
Ted Kremenek42730c52008-01-07 19:49:32 +00001962/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001963/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00001964int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001965 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001966
1967 // Make all integer and enum types at least as large as an int
1968 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00001969 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001970 // Treat arrays as pointers, since that's how they're passed in.
1971 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00001972 sz = getTypeSize(VoidPtrTy);
1973 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001974}
1975
Ted Kremenek42730c52008-01-07 19:49:32 +00001976/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001977/// declaration.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001978void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnerae430292008-11-19 07:24:05 +00001979 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001980 // FIXME: This is not very efficient.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001981 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00001982 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001983 // Encode result type.
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001984 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001985 // Compute size of all parameters.
1986 // Start with computing size of a pointer in number of bytes.
1987 // FIXME: There might(should) be a better way of doing this computation!
1988 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001989 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001990 // The first two arguments (self and _cmd) are pointers; account for
1991 // their size.
1992 int ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00001993 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
1994 E = Decl->param_end(); PI != E; ++PI) {
1995 QualType PType = (*PI)->getType();
1996 int sz = getObjCEncodingTypeSize(PType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001997 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001998 ParmOffset += sz;
1999 }
2000 S += llvm::utostr(ParmOffset);
2001 S += "@0:";
2002 S += llvm::utostr(PtrSize);
2003
2004 // Argument types.
2005 ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002006 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2007 E = Decl->param_end(); PI != E; ++PI) {
2008 ParmVarDecl *PVDecl = *PI;
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002009 QualType PType = PVDecl->getOriginalType();
2010 if (const ArrayType *AT =
2011 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal()))
2012 // Use array's original type only if it has known number of
2013 // elements.
2014 if (!dyn_cast<ConstantArrayType>(AT))
2015 PType = PVDecl->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002016 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002017 // 'in', 'inout', etc.
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002018 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002019 getObjCEncodingForType(PType, S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002020 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00002021 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002022 }
2023}
2024
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002025/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002026/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002027/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2028/// NULL when getting encodings for protocol properties.
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002029/// Property attributes are stored as a comma-delimited C string. The simple
2030/// attributes readonly and bycopy are encoded as single characters. The
2031/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2032/// encoded as single characters, followed by an identifier. Property types
2033/// are also encoded as a parametrized attribute. The characters used to encode
2034/// these attributes are defined by the following enumeration:
2035/// @code
2036/// enum PropertyAttributes {
2037/// kPropertyReadOnly = 'R', // property is read-only.
2038/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2039/// kPropertyByref = '&', // property is a reference to the value last assigned
2040/// kPropertyDynamic = 'D', // property is dynamic
2041/// kPropertyGetter = 'G', // followed by getter selector name
2042/// kPropertySetter = 'S', // followed by setter selector name
2043/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2044/// kPropertyType = 't' // followed by old-style type encoding.
2045/// kPropertyWeak = 'W' // 'weak' property
2046/// kPropertyStrong = 'P' // property GC'able
2047/// kPropertyNonAtomic = 'N' // property non-atomic
2048/// };
2049/// @endcode
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002050void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2051 const Decl *Container,
Chris Lattnerae430292008-11-19 07:24:05 +00002052 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002053 // Collect information from the property implementation decl(s).
2054 bool Dynamic = false;
2055 ObjCPropertyImplDecl *SynthesizePID = 0;
2056
2057 // FIXME: Duplicated code due to poor abstraction.
2058 if (Container) {
2059 if (const ObjCCategoryImplDecl *CID =
2060 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2061 for (ObjCCategoryImplDecl::propimpl_iterator
2062 i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) {
2063 ObjCPropertyImplDecl *PID = *i;
2064 if (PID->getPropertyDecl() == PD) {
2065 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2066 Dynamic = true;
2067 } else {
2068 SynthesizePID = PID;
2069 }
2070 }
2071 }
2072 } else {
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002073 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002074 for (ObjCCategoryImplDecl::propimpl_iterator
2075 i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) {
2076 ObjCPropertyImplDecl *PID = *i;
2077 if (PID->getPropertyDecl() == PD) {
2078 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2079 Dynamic = true;
2080 } else {
2081 SynthesizePID = PID;
2082 }
2083 }
2084 }
2085 }
2086 }
2087
2088 // FIXME: This is not very efficient.
2089 S = "T";
2090
2091 // Encode result type.
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002092 // GCC has some special rules regarding encoding of properties which
2093 // closely resembles encoding of ivars.
2094 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, NULL,
2095 true /* outermost type */,
2096 true /* encoding for property */);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002097
2098 if (PD->isReadOnly()) {
2099 S += ",R";
2100 } else {
2101 switch (PD->getSetterKind()) {
2102 case ObjCPropertyDecl::Assign: break;
2103 case ObjCPropertyDecl::Copy: S += ",C"; break;
2104 case ObjCPropertyDecl::Retain: S += ",&"; break;
2105 }
2106 }
2107
2108 // It really isn't clear at all what this means, since properties
2109 // are "dynamic by default".
2110 if (Dynamic)
2111 S += ",D";
2112
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002113 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2114 S += ",N";
2115
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002116 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2117 S += ",G";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002118 S += PD->getGetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002119 }
2120
2121 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2122 S += ",S";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002123 S += PD->getSetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002124 }
2125
2126 if (SynthesizePID) {
2127 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2128 S += ",V";
Chris Lattner6c5ec622008-11-24 04:00:27 +00002129 S += OID->getNameAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002130 }
2131
2132 // FIXME: OBJCGC: weak & strong
2133}
2134
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002135/// getLegacyIntegralTypeEncoding -
2136/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanian89155952009-02-11 23:59:18 +00002137/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002138/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2139///
2140void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2141 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2142 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanian89155952009-02-11 23:59:18 +00002143 if (BT->getKind() == BuiltinType::ULong &&
2144 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002145 PointeeTy = UnsignedIntTy;
Fariborz Jahanian89155952009-02-11 23:59:18 +00002146 else
2147 if (BT->getKind() == BuiltinType::Long &&
2148 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002149 PointeeTy = IntTy;
2150 }
2151 }
2152}
2153
Fariborz Jahanian248db262008-01-22 22:44:46 +00002154void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002155 FieldDecl *Field) const {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002156 // We follow the behavior of gcc, expanding structures which are
2157 // directly pointed to, and expanding embedded structures. Note that
2158 // these rules are sufficient to prevent recursive encoding of the
2159 // same type.
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002160 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2161 true /* outermost type */);
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002162}
2163
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002164static void EncodeBitField(const ASTContext *Context, std::string& S,
2165 FieldDecl *FD) {
2166 const Expr *E = FD->getBitWidth();
2167 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2168 ASTContext *Ctx = const_cast<ASTContext*>(Context);
2169 unsigned N = E->getIntegerConstantExprValue(*Ctx).getZExtValue();
2170 S += 'b';
2171 S += llvm::utostr(N);
2172}
2173
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002174void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2175 bool ExpandPointedToStructures,
2176 bool ExpandStructures,
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002177 FieldDecl *FD,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002178 bool OutermostType,
2179 bool EncodingProperty) const {
Anders Carlssone3f02572007-10-29 06:33:42 +00002180 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002181 if (FD && FD->isBitField()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002182 EncodeBitField(this, S, FD);
Anders Carlsson36f07d82007-10-29 05:01:08 +00002183 }
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002184 else {
2185 char encoding;
2186 switch (BT->getKind()) {
2187 default: assert(0 && "Unhandled builtin type kind");
2188 case BuiltinType::Void: encoding = 'v'; break;
2189 case BuiltinType::Bool: encoding = 'B'; break;
2190 case BuiltinType::Char_U:
2191 case BuiltinType::UChar: encoding = 'C'; break;
2192 case BuiltinType::UShort: encoding = 'S'; break;
2193 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002194 case BuiltinType::ULong:
2195 encoding =
2196 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2197 break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002198 case BuiltinType::ULongLong: encoding = 'Q'; break;
2199 case BuiltinType::Char_S:
2200 case BuiltinType::SChar: encoding = 'c'; break;
2201 case BuiltinType::Short: encoding = 's'; break;
2202 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002203 case BuiltinType::Long:
2204 encoding =
2205 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2206 break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002207 case BuiltinType::LongLong: encoding = 'q'; break;
2208 case BuiltinType::Float: encoding = 'f'; break;
2209 case BuiltinType::Double: encoding = 'd'; break;
2210 case BuiltinType::LongDouble: encoding = 'd'; break;
2211 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002212
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002213 S += encoding;
2214 }
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002215 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002216 else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002217 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2218 ExpandPointedToStructures,
2219 ExpandStructures, FD);
2220 if (FD || EncodingProperty) {
2221 // Note that we do extended encoding of protocol qualifer list
2222 // Only when doing ivar or property encoding.
2223 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2224 S += '"';
2225 for (unsigned i =0; i < QIDT->getNumProtocols(); i++) {
2226 ObjCProtocolDecl *Proto = QIDT->getProtocols(i);
2227 S += '<';
2228 S += Proto->getNameAsString();
2229 S += '>';
2230 }
2231 S += '"';
2232 }
2233 return;
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002234 }
2235 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002236 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002237 bool isReadOnly = false;
2238 // For historical/compatibility reasons, the read-only qualifier of the
2239 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2240 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2241 // Also, do not emit the 'r' for anything but the outermost type!
2242 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2243 if (OutermostType && T.isConstQualified()) {
2244 isReadOnly = true;
2245 S += 'r';
2246 }
2247 }
2248 else if (OutermostType) {
2249 QualType P = PointeeTy;
2250 while (P->getAsPointerType())
2251 P = P->getAsPointerType()->getPointeeType();
2252 if (P.isConstQualified()) {
2253 isReadOnly = true;
2254 S += 'r';
2255 }
2256 }
2257 if (isReadOnly) {
2258 // Another legacy compatibility encoding. Some ObjC qualifier and type
2259 // combinations need to be rearranged.
2260 // Rewrite "in const" from "nr" to "rn"
2261 const char * s = S.c_str();
2262 int len = S.length();
2263 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2264 std::string replace = "rn";
2265 S.replace(S.end()-2, S.end(), replace);
2266 }
2267 }
Steve Naroff17c03822009-02-12 17:52:19 +00002268 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002269 S += '@';
2270 return;
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002271 }
2272 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanian94675042009-02-16 21:41:04 +00002273 if (!EncodingProperty &&
Fariborz Jahanian6bc0f2d2009-02-16 22:09:26 +00002274 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniand3498aa2008-12-23 21:30:15 +00002275 // Another historical/compatibility reason.
2276 // We encode the underlying type which comes out as
2277 // {...};
2278 S += '^';
2279 getObjCEncodingForTypeImpl(PointeeTy, S,
2280 false, ExpandPointedToStructures,
2281 NULL);
2282 return;
2283 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002284 S += '@';
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002285 if (FD || EncodingProperty) {
Fariborz Jahanianc69da272009-02-21 18:23:24 +00002286 const ObjCInterfaceType *OIT =
2287 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002288 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002289 S += '"';
2290 S += OI->getNameAsCString();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002291 for (unsigned i =0; i < OIT->getNumProtocols(); i++) {
2292 ObjCProtocolDecl *Proto = OIT->getProtocol(i);
2293 S += '<';
2294 S += Proto->getNameAsString();
2295 S += '>';
2296 }
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002297 S += '"';
2298 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002299 return;
Steve Naroff17c03822009-02-12 17:52:19 +00002300 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002301 S += '#';
2302 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002303 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002304 S += ':';
2305 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002306 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002307
2308 if (PointeeTy->isCharType()) {
2309 // char pointer types should be encoded as '*' unless it is a
2310 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00002311 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002312 S += '*';
2313 return;
2314 }
2315 }
2316
2317 S += '^';
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002318 getLegacyIntegralTypeEncoding(PointeeTy);
2319
2320 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbaraa913102008-10-17 16:17:37 +00002321 false, ExpandPointedToStructures,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002322 NULL);
Chris Lattnera1923f62008-08-04 07:31:14 +00002323 } else if (const ArrayType *AT =
2324 // Ignore type qualifiers etc.
2325 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson858c64d2009-02-22 01:38:57 +00002326 if (isa<IncompleteArrayType>(AT)) {
2327 // Incomplete arrays are encoded as a pointer to the array element.
2328 S += '^';
2329
2330 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2331 false, ExpandStructures, FD);
2332 } else {
2333 S += '[';
Anders Carlsson36f07d82007-10-29 05:01:08 +00002334
Anders Carlsson858c64d2009-02-22 01:38:57 +00002335 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2336 S += llvm::utostr(CAT->getSize().getZExtValue());
2337 else {
2338 //Variable length arrays are encoded as a regular array with 0 elements.
2339 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2340 S += '0';
2341 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002342
Anders Carlsson858c64d2009-02-22 01:38:57 +00002343 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2344 false, ExpandStructures, FD);
2345 S += ']';
2346 }
Anders Carlsson5695bb72007-10-30 00:06:20 +00002347 } else if (T->getAsFunctionType()) {
2348 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002349 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002350 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002351 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar146b2d02008-10-17 06:22:57 +00002352 // Anonymous structures print as '?'
2353 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2354 S += II->getName();
2355 } else {
2356 S += '?';
2357 }
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002358 if (ExpandStructures) {
Fariborz Jahanian248db262008-01-22 22:44:46 +00002359 S += '=';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002360 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2361 FieldEnd = RDecl->field_end();
2362 Field != FieldEnd; ++Field) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002363 if (FD) {
Daniel Dunbaraa913102008-10-17 16:17:37 +00002364 S += '"';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002365 S += Field->getNameAsString();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002366 S += '"';
2367 }
2368
2369 // Special case bit-fields.
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002370 if (Field->isBitField()) {
2371 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2372 (*Field));
Daniel Dunbaraa913102008-10-17 16:17:37 +00002373 } else {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002374 QualType qt = Field->getType();
2375 getLegacyIntegralTypeEncoding(qt);
2376 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002377 FD);
Daniel Dunbaraa913102008-10-17 16:17:37 +00002378 }
Fariborz Jahanian248db262008-01-22 22:44:46 +00002379 }
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002380 }
Daniel Dunbaraa913102008-10-17 16:17:37 +00002381 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff49af3f32007-12-12 22:30:11 +00002382 } else if (T->isEnumeralType()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002383 if (FD && FD->isBitField())
2384 EncodeBitField(this, S, FD);
2385 else
2386 S += 'i';
Steve Naroff62f09f52008-09-24 15:05:44 +00002387 } else if (T->isBlockPointerType()) {
Steve Naroff725e0662009-02-02 18:24:29 +00002388 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002389 } else if (T->isObjCInterfaceType()) {
2390 // @encode(class_name)
2391 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2392 S += '{';
2393 const IdentifierInfo *II = OI->getIdentifier();
2394 S += II->getName();
2395 S += '=';
2396 std::vector<FieldDecl*> RecFields;
2397 CollectObjCIvars(OI, RecFields);
2398 for (unsigned int i = 0; i != RecFields.size(); i++) {
2399 if (RecFields[i]->isBitField())
2400 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2401 RecFields[i]);
2402 else
2403 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2404 FD);
2405 }
2406 S += '}';
2407 }
2408 else
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002409 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002410}
2411
Ted Kremenek42730c52008-01-07 19:49:32 +00002412void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002413 std::string& S) const {
2414 if (QT & Decl::OBJC_TQ_In)
2415 S += 'n';
2416 if (QT & Decl::OBJC_TQ_Inout)
2417 S += 'N';
2418 if (QT & Decl::OBJC_TQ_Out)
2419 S += 'o';
2420 if (QT & Decl::OBJC_TQ_Bycopy)
2421 S += 'O';
2422 if (QT & Decl::OBJC_TQ_Byref)
2423 S += 'R';
2424 if (QT & Decl::OBJC_TQ_Oneway)
2425 S += 'V';
2426}
2427
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002428void ASTContext::setBuiltinVaListType(QualType T)
2429{
2430 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2431
2432 BuiltinVaListType = T;
2433}
2434
Ted Kremenek42730c52008-01-07 19:49:32 +00002435void ASTContext::setObjCIdType(TypedefDecl *TD)
Steve Naroff9d12c902007-10-15 14:41:52 +00002436{
Ted Kremenek42730c52008-01-07 19:49:32 +00002437 ObjCIdType = getTypedefType(TD);
Steve Naroff9d12c902007-10-15 14:41:52 +00002438
2439 // typedef struct objc_object *id;
2440 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002441 // User error - caller will issue diagnostics.
2442 if (!ptr)
2443 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002444 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002445 // User error - caller will issue diagnostics.
2446 if (!rec)
2447 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002448 IdStructType = rec;
2449}
2450
Ted Kremenek42730c52008-01-07 19:49:32 +00002451void ASTContext::setObjCSelType(TypedefDecl *TD)
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002452{
Ted Kremenek42730c52008-01-07 19:49:32 +00002453 ObjCSelType = getTypedefType(TD);
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002454
2455 // typedef struct objc_selector *SEL;
2456 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002457 if (!ptr)
2458 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002459 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002460 if (!rec)
2461 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002462 SelStructType = rec;
2463}
2464
Ted Kremenek42730c52008-01-07 19:49:32 +00002465void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002466{
Ted Kremenek42730c52008-01-07 19:49:32 +00002467 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002468}
2469
Ted Kremenek42730c52008-01-07 19:49:32 +00002470void ASTContext::setObjCClassType(TypedefDecl *TD)
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002471{
Ted Kremenek42730c52008-01-07 19:49:32 +00002472 ObjCClassType = getTypedefType(TD);
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002473
2474 // typedef struct objc_class *Class;
2475 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2476 assert(ptr && "'Class' incorrectly typed");
2477 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2478 assert(rec && "'Class' incorrectly typed");
2479 ClassStructType = rec;
2480}
2481
Ted Kremenek42730c52008-01-07 19:49:32 +00002482void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2483 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00002484 "'NSConstantString' type already set!");
2485
Ted Kremenek42730c52008-01-07 19:49:32 +00002486 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00002487}
2488
Douglas Gregorc6507e42008-11-03 14:12:49 +00002489/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorbb66b412008-11-03 15:57:00 +00002490/// TargetInfo, produce the corresponding type. The unsigned @p Type
2491/// is actually a value of type @c TargetInfo::IntType.
2492QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00002493 switch (Type) {
2494 case TargetInfo::NoInt: return QualType();
2495 case TargetInfo::SignedShort: return ShortTy;
2496 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2497 case TargetInfo::SignedInt: return IntTy;
2498 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2499 case TargetInfo::SignedLong: return LongTy;
2500 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2501 case TargetInfo::SignedLongLong: return LongLongTy;
2502 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2503 }
2504
2505 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbar7b0dcc22008-11-11 01:16:00 +00002506 return QualType();
Douglas Gregorc6507e42008-11-03 14:12:49 +00002507}
Ted Kremenek118930e2008-07-24 23:58:27 +00002508
2509//===----------------------------------------------------------------------===//
2510// Type Predicates.
2511//===----------------------------------------------------------------------===//
2512
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002513/// isObjCNSObjectType - Return true if this is an NSObject object using
2514/// NSObject attribute on a c-style pointer type.
2515/// FIXME - Make it work directly on types.
2516///
2517bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2518 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2519 if (TypedefDecl *TD = TDT->getDecl())
2520 if (TD->getAttr<ObjCNSObjectAttr>())
2521 return true;
2522 }
2523 return false;
2524}
2525
Ted Kremenek118930e2008-07-24 23:58:27 +00002526/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2527/// to an object type. This includes "id" and "Class" (two 'special' pointers
2528/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2529/// ID type).
2530bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroff6805fc42009-02-23 18:36:16 +00002531 if (Ty->isObjCQualifiedIdType())
Ted Kremenek118930e2008-07-24 23:58:27 +00002532 return true;
2533
Steve Naroffd9e00802008-10-21 18:24:04 +00002534 // Blocks are objects.
2535 if (Ty->isBlockPointerType())
2536 return true;
2537
2538 // All other object types are pointers.
Ted Kremenek118930e2008-07-24 23:58:27 +00002539 if (!Ty->isPointerType())
2540 return false;
2541
2542 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2543 // pointer types. This looks for the typedef specifically, not for the
2544 // underlying type.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00002545 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2546 Ty.getUnqualifiedType() == getObjCClassType())
Ted Kremenek118930e2008-07-24 23:58:27 +00002547 return true;
2548
2549 // If this a pointer to an interface (e.g. NSString*), it is ok.
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002550 if (Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType())
2551 return true;
2552
2553 // If is has NSObject attribute, OK as well.
2554 return isObjCNSObjectType(Ty);
Ted Kremenek118930e2008-07-24 23:58:27 +00002555}
2556
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002557/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2558/// garbage collection attribute.
2559///
2560QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002561 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002562 if (getLangOptions().ObjC1 &&
2563 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002564 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002565 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002566 // (or pointers to them) be treated as though they were declared
2567 // as __strong.
2568 if (GCAttrs == QualType::GCNone) {
2569 if (isObjCObjectPointerType(Ty))
2570 GCAttrs = QualType::Strong;
2571 else if (Ty->isPointerType())
2572 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2573 }
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002574 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002575 return GCAttrs;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002576}
2577
Chris Lattner6ff358b2008-04-07 06:51:04 +00002578//===----------------------------------------------------------------------===//
2579// Type Compatibility Testing
2580//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00002581
Steve Naroff3454b6c2008-09-04 15:10:53 +00002582/// typesAreBlockCompatible - This routine is called when comparing two
Steve Naroffd6163f32008-09-05 22:11:13 +00002583/// block types. Types must be strictly compatible here. For example,
2584/// C unfortunately doesn't produce an error for the following:
2585///
2586/// int (*emptyArgFunc)();
2587/// int (*intArgList)(int) = emptyArgFunc;
2588///
2589/// For blocks, we will produce an error for the following (similar to C++):
2590///
2591/// int (^emptyArgBlock)();
2592/// int (^intArgBlock)(int) = emptyArgBlock;
2593///
2594/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2595///
Steve Naroff3454b6c2008-09-04 15:10:53 +00002596bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
Steve Naroff09e1b9e2008-12-10 17:49:55 +00002597 const FunctionType *lbase = lhs->getAsFunctionType();
2598 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00002599 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2600 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Steve Naroff09e1b9e2008-12-10 17:49:55 +00002601 if (lproto && rproto)
2602 return !mergeTypes(lhs, rhs).isNull();
2603 return false;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002604}
2605
Chris Lattner6ff358b2008-04-07 06:51:04 +00002606/// areCompatVectorTypes - Return true if the two specified vector types are
2607/// compatible.
2608static bool areCompatVectorTypes(const VectorType *LHS,
2609 const VectorType *RHS) {
2610 assert(LHS->isCanonical() && RHS->isCanonical());
2611 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002612 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ff358b2008-04-07 06:51:04 +00002613}
2614
Eli Friedman0d9549b2008-08-22 00:56:42 +00002615/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ff358b2008-04-07 06:51:04 +00002616/// compatible for assignment from RHS to LHS. This handles validation of any
2617/// protocol qualifiers on the LHS or RHS.
2618///
Eli Friedman0d9549b2008-08-22 00:56:42 +00002619bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2620 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00002621 // Verify that the base decls are compatible: the RHS must be a subclass of
2622 // the LHS.
2623 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2624 return false;
2625
2626 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2627 // protocol qualified at all, then we are good.
2628 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2629 return true;
2630
2631 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2632 // isn't a superset.
2633 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2634 return true; // FIXME: should return false!
2635
2636 // Finally, we must have two protocol-qualified interfaces.
2637 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2638 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ff358b2008-04-07 06:51:04 +00002639
Steve Naroff98e71b82009-03-01 16:12:44 +00002640 // All LHS protocols must have a presence on the RHS.
2641 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ff358b2008-04-07 06:51:04 +00002642
Steve Naroff98e71b82009-03-01 16:12:44 +00002643 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2644 LHSPE = LHSP->qual_end();
2645 LHSPI != LHSPE; LHSPI++) {
2646 bool RHSImplementsProtocol = false;
2647
2648 // If the RHS doesn't implement the protocol on the left, the types
2649 // are incompatible.
2650 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2651 RHSPE = RHSP->qual_end();
2652 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2653 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2654 RHSImplementsProtocol = true;
2655 }
2656 // FIXME: For better diagnostics, consider passing back the protocol name.
2657 if (!RHSImplementsProtocol)
2658 return false;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002659 }
Steve Naroff98e71b82009-03-01 16:12:44 +00002660 // The RHS implements all protocols listed on the LHS.
2661 return true;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002662}
2663
Steve Naroff17c03822009-02-12 17:52:19 +00002664bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2665 // get the "pointed to" types
2666 const PointerType *LHSPT = LHS->getAsPointerType();
2667 const PointerType *RHSPT = RHS->getAsPointerType();
2668
2669 if (!LHSPT || !RHSPT)
2670 return false;
2671
2672 QualType lhptee = LHSPT->getPointeeType();
2673 QualType rhptee = RHSPT->getPointeeType();
2674 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2675 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2676 // ID acts sort of like void* for ObjC interfaces
2677 if (LHSIface && isObjCIdStructType(rhptee))
2678 return true;
2679 if (RHSIface && isObjCIdStructType(lhptee))
2680 return true;
2681 if (!LHSIface || !RHSIface)
2682 return false;
2683 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2684 canAssignObjCInterfaces(RHSIface, LHSIface);
2685}
2686
Steve Naroff85f0dc52007-10-15 20:41:53 +00002687/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2688/// both shall have the identically qualified version of a compatible type.
2689/// C99 6.2.7p1: Two types have compatible types if their types are the
2690/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002691bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2692 return !mergeTypes(LHS, RHS).isNull();
2693}
2694
2695QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2696 const FunctionType *lbase = lhs->getAsFunctionType();
2697 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00002698 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2699 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002700 bool allLTypes = true;
2701 bool allRTypes = true;
2702
2703 // Check return type
2704 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2705 if (retType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002706 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2707 allLTypes = false;
2708 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2709 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002710
2711 if (lproto && rproto) { // two C99 style function prototypes
2712 unsigned lproto_nargs = lproto->getNumArgs();
2713 unsigned rproto_nargs = rproto->getNumArgs();
2714
2715 // Compatible functions must have the same number of arguments
2716 if (lproto_nargs != rproto_nargs)
2717 return QualType();
2718
2719 // Variadic and non-variadic functions aren't compatible
2720 if (lproto->isVariadic() != rproto->isVariadic())
2721 return QualType();
2722
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002723 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2724 return QualType();
2725
Eli Friedman0d9549b2008-08-22 00:56:42 +00002726 // Check argument compatibility
2727 llvm::SmallVector<QualType, 10> types;
2728 for (unsigned i = 0; i < lproto_nargs; i++) {
2729 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2730 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2731 QualType argtype = mergeTypes(largtype, rargtype);
2732 if (argtype.isNull()) return QualType();
2733 types.push_back(argtype);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002734 if (getCanonicalType(argtype) != getCanonicalType(largtype))
2735 allLTypes = false;
2736 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2737 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002738 }
2739 if (allLTypes) return lhs;
2740 if (allRTypes) return rhs;
2741 return getFunctionType(retType, types.begin(), types.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002742 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00002743 }
2744
2745 if (lproto) allRTypes = false;
2746 if (rproto) allLTypes = false;
2747
Douglas Gregor4fa58902009-02-26 23:50:07 +00002748 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002749 if (proto) {
2750 if (proto->isVariadic()) return QualType();
2751 // Check that the types are compatible with the types that
2752 // would result from default argument promotions (C99 6.7.5.3p15).
2753 // The only types actually affected are promotable integer
2754 // types and floats, which would be passed as a different
2755 // type depending on whether the prototype is visible.
2756 unsigned proto_nargs = proto->getNumArgs();
2757 for (unsigned i = 0; i < proto_nargs; ++i) {
2758 QualType argTy = proto->getArgType(i);
2759 if (argTy->isPromotableIntegerType() ||
2760 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2761 return QualType();
2762 }
2763
2764 if (allLTypes) return lhs;
2765 if (allRTypes) return rhs;
2766 return getFunctionType(retType, proto->arg_type_begin(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002767 proto->getNumArgs(), lproto->isVariadic(),
2768 lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00002769 }
2770
2771 if (allLTypes) return lhs;
2772 if (allRTypes) return rhs;
Douglas Gregor4fa58902009-02-26 23:50:07 +00002773 return getFunctionNoProtoType(retType);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002774}
2775
2776QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling6a9d8542007-12-03 07:33:35 +00002777 // C++ [expr]: If an expression initially has the type "reference to T", the
2778 // type is adjusted to "T" prior to any further analysis, the expression
2779 // designates the object or function denoted by the reference, and the
Sebastian Redlce6fff02009-03-16 23:22:08 +00002780 // expression is an lvalue unless the reference is an rvalue reference and
2781 // the expression is a function call (possibly inside parentheses).
Eli Friedman0d9549b2008-08-22 00:56:42 +00002782 // FIXME: C++ shouldn't be going through here! The rules are different
2783 // enough that they should be handled separately.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002784 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
2785 // shouldn't be going through here!
Eli Friedman0d9549b2008-08-22 00:56:42 +00002786 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00002787 LHS = RT->getPointeeType();
Eli Friedman0d9549b2008-08-22 00:56:42 +00002788 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00002789 RHS = RT->getPointeeType();
Chris Lattnerd47d6042008-04-07 05:37:56 +00002790
Eli Friedman0d9549b2008-08-22 00:56:42 +00002791 QualType LHSCan = getCanonicalType(LHS),
2792 RHSCan = getCanonicalType(RHS);
2793
2794 // If two types are identical, they are compatible.
2795 if (LHSCan == RHSCan)
2796 return LHS;
2797
2798 // If the qualifiers are different, the types aren't compatible
Eli Friedman94fcc9a2009-02-27 23:04:43 +00002799 // Note that we handle extended qualifiers later, in the
2800 // case for ExtQualType.
2801 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman0d9549b2008-08-22 00:56:42 +00002802 return QualType();
2803
2804 Type::TypeClass LHSClass = LHSCan->getTypeClass();
2805 Type::TypeClass RHSClass = RHSCan->getTypeClass();
2806
Chris Lattnerc38d4522008-01-14 05:45:46 +00002807 // We want to consider the two function types to be the same for these
2808 // comparisons, just force one to the other.
2809 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
2810 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00002811
2812 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00002813 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
2814 LHSClass = Type::ConstantArray;
2815 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
2816 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00002817
Nate Begemanaf6ed502008-04-18 23:10:10 +00002818 // Canonicalize ExtVector -> Vector.
2819 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
2820 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00002821
Chris Lattner7cdcb252008-04-07 06:38:24 +00002822 // Consider qualified interfaces and interfaces the same.
2823 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
2824 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002825
Chris Lattnerb5709e22008-04-07 05:43:21 +00002826 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00002827 if (LHSClass != RHSClass) {
Steve Naroff0bbc1352009-02-21 16:18:07 +00002828 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2829 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2830
2831 // ID acts sort of like void* for ObjC interfaces
2832 if (LHSIface && isObjCIdStructType(RHS))
2833 return LHS;
2834 if (RHSIface && isObjCIdStructType(LHS))
2835 return RHS;
2836
Steve Naroff28ceff72008-12-10 22:14:21 +00002837 // ID is compatible with all qualified id types.
2838 if (LHS->isObjCQualifiedIdType()) {
2839 if (const PointerType *PT = RHS->getAsPointerType()) {
2840 QualType pType = PT->getPointeeType();
Steve Naroff17c03822009-02-12 17:52:19 +00002841 if (isObjCIdStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00002842 return LHS;
2843 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2844 // Unfortunately, this API is part of Sema (which we don't have access
2845 // to. Need to refactor. The following check is insufficient, since we
2846 // need to make sure the class implements the protocol.
2847 if (pType->isObjCInterfaceType())
2848 return LHS;
2849 }
2850 }
2851 if (RHS->isObjCQualifiedIdType()) {
2852 if (const PointerType *PT = LHS->getAsPointerType()) {
2853 QualType pType = PT->getPointeeType();
Steve Naroff17c03822009-02-12 17:52:19 +00002854 if (isObjCIdStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00002855 return RHS;
2856 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2857 // Unfortunately, this API is part of Sema (which we don't have access
2858 // to. Need to refactor. The following check is insufficient, since we
2859 // need to make sure the class implements the protocol.
2860 if (pType->isObjCInterfaceType())
2861 return RHS;
2862 }
2863 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002864 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
2865 // a signed integer type, or an unsigned integer type.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002866 if (const EnumType* ETy = LHS->getAsEnumType()) {
2867 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
2868 return RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00002869 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002870 if (const EnumType* ETy = RHS->getAsEnumType()) {
2871 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
2872 return LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00002873 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002874
Eli Friedman0d9549b2008-08-22 00:56:42 +00002875 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00002876 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002877
Steve Naroffc88babe2008-01-09 22:43:08 +00002878 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00002879 switch (LHSClass) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002880#define TYPE(Class, Base)
2881#define ABSTRACT_TYPE(Class, Base)
2882#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2883#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2884#include "clang/AST/TypeNodes.def"
2885 assert(false && "Non-canonical and dependent types shouldn't get here");
2886 return QualType();
2887
Sebastian Redlce6fff02009-03-16 23:22:08 +00002888 case Type::LValueReference:
2889 case Type::RValueReference:
Douglas Gregor4fa58902009-02-26 23:50:07 +00002890 case Type::MemberPointer:
2891 assert(false && "C++ should never be in mergeTypes");
2892 return QualType();
2893
2894 case Type::IncompleteArray:
2895 case Type::VariableArray:
2896 case Type::FunctionProto:
2897 case Type::ExtVector:
2898 case Type::ObjCQualifiedInterface:
2899 assert(false && "Types are eliminated above");
2900 return QualType();
2901
Chris Lattnerc38d4522008-01-14 05:45:46 +00002902 case Type::Pointer:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002903 {
2904 // Merge two pointer types, while trying to preserve typedef info
2905 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
2906 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
2907 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2908 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002909 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2910 return LHS;
2911 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2912 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002913 return getPointerType(ResultType);
2914 }
Steve Naroff09e1b9e2008-12-10 17:49:55 +00002915 case Type::BlockPointer:
2916 {
2917 // Merge two block pointer types, while trying to preserve typedef info
2918 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
2919 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
2920 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2921 if (ResultType.isNull()) return QualType();
2922 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2923 return LHS;
2924 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2925 return RHS;
2926 return getBlockPointerType(ResultType);
2927 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002928 case Type::ConstantArray:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002929 {
2930 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
2931 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
2932 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
2933 return QualType();
2934
2935 QualType LHSElem = getAsArrayType(LHS)->getElementType();
2936 QualType RHSElem = getAsArrayType(RHS)->getElementType();
2937 QualType ResultType = mergeTypes(LHSElem, RHSElem);
2938 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002939 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2940 return LHS;
2941 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2942 return RHS;
Eli Friedmanc91a3f32008-08-22 01:48:21 +00002943 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
2944 ArrayType::ArraySizeModifier(), 0);
2945 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
2946 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002947 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
2948 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002949 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2950 return LHS;
2951 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2952 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002953 if (LVAT) {
2954 // FIXME: This isn't correct! But tricky to implement because
2955 // the array's size has to be the size of LHS, but the type
2956 // has to be different.
2957 return LHS;
2958 }
2959 if (RVAT) {
2960 // FIXME: This isn't correct! But tricky to implement because
2961 // the array's size has to be the size of RHS, but the type
2962 // has to be different.
2963 return RHS;
2964 }
Eli Friedmanc91a3f32008-08-22 01:48:21 +00002965 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
2966 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002967 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002968 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002969 case Type::FunctionNoProto:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002970 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor4fa58902009-02-26 23:50:07 +00002971 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +00002972 case Type::Enum:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002973 // FIXME: Why are these compatible?
Steve Naroff17c03822009-02-12 17:52:19 +00002974 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
2975 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002976 return QualType();
Chris Lattnerc38d4522008-01-14 05:45:46 +00002977 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00002978 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002979 return QualType();
Daniel Dunbar457f33d2009-01-28 21:22:12 +00002980 case Type::Complex:
2981 // Distinct complex types are incompatible.
2982 return QualType();
Chris Lattnerd1240fa2008-04-07 05:55:38 +00002983 case Type::Vector:
Eli Friedman94fcc9a2009-02-27 23:04:43 +00002984 // FIXME: The merged type should be an ExtVector!
Eli Friedman0d9549b2008-08-22 00:56:42 +00002985 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
2986 return LHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002987 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00002988 case Type::ObjCInterface: {
Steve Naroff0bbc1352009-02-21 16:18:07 +00002989 // Check if the interfaces are assignment compatible.
Eli Friedman94fcc9a2009-02-27 23:04:43 +00002990 // FIXME: This should be type compatibility, e.g. whether
2991 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff0bbc1352009-02-21 16:18:07 +00002992 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2993 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2994 if (LHSIface && RHSIface &&
2995 canAssignObjCInterfaces(LHSIface, RHSIface))
2996 return LHS;
2997
Eli Friedman0d9549b2008-08-22 00:56:42 +00002998 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00002999 }
Steve Naroff28ceff72008-12-10 22:14:21 +00003000 case Type::ObjCQualifiedId:
3001 // Distinct qualified id's are not compatible.
3002 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003003 case Type::FixedWidthInt:
3004 // Distinct fixed-width integers are not compatible.
3005 return QualType();
3006 case Type::ObjCQualifiedClass:
3007 // Distinct qualified classes are not compatible.
3008 return QualType();
3009 case Type::ExtQual:
3010 // FIXME: ExtQual types can be compatible even if they're not
3011 // identical!
3012 return QualType();
3013 // First attempt at an implementation, but I'm not really sure it's
3014 // right...
3015#if 0
3016 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3017 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3018 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3019 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3020 return QualType();
3021 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3022 LHSBase = QualType(LQual->getBaseType(), 0);
3023 RHSBase = QualType(RQual->getBaseType(), 0);
3024 ResultType = mergeTypes(LHSBase, RHSBase);
3025 if (ResultType.isNull()) return QualType();
3026 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3027 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3028 return LHS;
3029 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3030 return RHS;
3031 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3032 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3033 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3034 return ResultType;
3035#endif
Steve Naroff85f0dc52007-10-15 20:41:53 +00003036 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00003037
3038 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003039}
Ted Kremenek738e6c02007-10-31 17:10:13 +00003040
Chris Lattner1d78a862008-04-07 07:01:58 +00003041//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00003042// Integer Predicates
3043//===----------------------------------------------------------------------===//
Chris Lattner74f67012009-01-16 07:15:35 +00003044
Eli Friedman0832dbc2008-06-28 06:23:08 +00003045unsigned ASTContext::getIntWidth(QualType T) {
3046 if (T == BoolTy)
3047 return 1;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00003048 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3049 return FWIT->getWidth();
3050 }
3051 // For builtin types, just use the standard type sizing method
Eli Friedman0832dbc2008-06-28 06:23:08 +00003052 return (unsigned)getTypeSize(T);
3053}
3054
3055QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3056 assert(T->isSignedIntegerType() && "Unexpected type");
3057 if (const EnumType* ETy = T->getAsEnumType())
3058 T = ETy->getDecl()->getIntegerType();
3059 const BuiltinType* BTy = T->getAsBuiltinType();
3060 assert (BTy && "Unexpected signed integer type");
3061 switch (BTy->getKind()) {
3062 case BuiltinType::Char_S:
3063 case BuiltinType::SChar:
3064 return UnsignedCharTy;
3065 case BuiltinType::Short:
3066 return UnsignedShortTy;
3067 case BuiltinType::Int:
3068 return UnsignedIntTy;
3069 case BuiltinType::Long:
3070 return UnsignedLongTy;
3071 case BuiltinType::LongLong:
3072 return UnsignedLongLongTy;
3073 default:
3074 assert(0 && "Unexpected signed integer type");
3075 return QualType();
3076 }
3077}
3078
3079
3080//===----------------------------------------------------------------------===//
Chris Lattner1d78a862008-04-07 07:01:58 +00003081// Serialization Support
3082//===----------------------------------------------------------------------===//
3083
Chris Lattnerb09b31d2009-03-28 03:45:20 +00003084enum {
3085 BasicMetadataBlock = 1,
3086 ASTContextBlock = 2,
3087 DeclsBlock = 3
3088};
3089
Chris Lattnerf4fbc442009-03-28 04:27:18 +00003090void ASTContext::EmitASTBitcodeBuffer(std::vector<unsigned char> &Buffer) const{
3091 // Create bitstream.
3092 llvm::BitstreamWriter Stream(Buffer);
3093
3094 // Emit the preamble.
3095 Stream.Emit((unsigned)'B', 8);
3096 Stream.Emit((unsigned)'C', 8);
3097 Stream.Emit(0xC, 4);
3098 Stream.Emit(0xF, 4);
3099 Stream.Emit(0xE, 4);
3100 Stream.Emit(0x0, 4);
3101
3102 // Create serializer.
3103 llvm::Serializer S(Stream);
3104
Chris Lattnerb09b31d2009-03-28 03:45:20 +00003105 // ===---------------------------------------------------===/
3106 // Serialize the "Translation Unit" metadata.
3107 // ===---------------------------------------------------===/
3108
3109 // Emit ASTContext.
3110 S.EnterBlock(ASTContextBlock);
3111 S.EmitOwnedPtr(this);
3112 S.ExitBlock(); // exit "ASTContextBlock"
3113
3114 S.EnterBlock(BasicMetadataBlock);
3115
3116 // Block for SourceManager and Target. Allows easy skipping
3117 // around to the block for the Selectors during deserialization.
3118 S.EnterBlock();
3119
3120 // Emit the SourceManager.
3121 S.Emit(getSourceManager());
3122
3123 // Emit the Target.
3124 S.EmitPtr(&Target);
3125 S.EmitCStr(Target.getTargetTriple());
3126
3127 S.ExitBlock(); // exit "SourceManager and Target Block"
3128
3129 // Emit the Selectors.
3130 S.Emit(Selectors);
3131
3132 // Emit the Identifier Table.
3133 S.Emit(Idents);
3134
3135 S.ExitBlock(); // exit "BasicMetadataBlock"
3136}
3137
3138
Ted Kremenek738e6c02007-10-31 17:10:13 +00003139/// Emit - Serialize an ASTContext object to Bitcode.
3140void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremenek842126e2008-06-04 15:55:15 +00003141 S.Emit(LangOpts);
Ted Kremenek9af4d5c2007-10-31 20:00:03 +00003142 S.EmitRef(SourceMgr);
3143 S.EmitRef(Target);
3144 S.EmitRef(Idents);
3145 S.EmitRef(Selectors);
Ted Kremenek738e6c02007-10-31 17:10:13 +00003146
Ted Kremenek68228a92007-10-31 22:44:07 +00003147 // Emit the size of the type vector so that we can reserve that size
3148 // when we reconstitute the ASTContext object.
Ted Kremenek0199d9f2007-11-06 22:26:16 +00003149 S.EmitInt(Types.size());
3150
Ted Kremenek034a78c2007-11-13 22:02:55 +00003151 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
3152 I!=E;++I)
3153 (*I)->Emit(S);
Ted Kremenek0199d9f2007-11-06 22:26:16 +00003154
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003155 S.EmitOwnedPtr(TUDecl);
3156
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00003157 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
Ted Kremenek738e6c02007-10-31 17:10:13 +00003158}
3159
Chris Lattnerf4fbc442009-03-28 04:27:18 +00003160
3161ASTContext *ASTContext::ReadASTBitcodeBuffer(llvm::MemoryBuffer &Buffer,
3162 FileManager &FMgr) {
3163 // Check if the file is of the proper length.
3164 if (Buffer.getBufferSize() & 0x3) {
3165 // FIXME: Provide diagnostic: "Length should be a multiple of 4 bytes."
3166 return 0;
3167 }
3168
3169 // Create the bitstream reader.
3170 unsigned char *BufPtr = (unsigned char *)Buffer.getBufferStart();
3171 llvm::BitstreamReader Stream(BufPtr, BufPtr+Buffer.getBufferSize());
3172
3173 if (Stream.Read(8) != 'B' ||
3174 Stream.Read(8) != 'C' ||
3175 Stream.Read(4) != 0xC ||
3176 Stream.Read(4) != 0xF ||
3177 Stream.Read(4) != 0xE ||
3178 Stream.Read(4) != 0x0) {
3179 // FIXME: Provide diagnostic.
3180 return NULL;
3181 }
3182
3183 // Create the deserializer.
3184 llvm::Deserializer Dezr(Stream);
3185
Chris Lattnerb09b31d2009-03-28 03:45:20 +00003186 // ===---------------------------------------------------===/
3187 // Deserialize the "Translation Unit" metadata.
3188 // ===---------------------------------------------------===/
3189
3190 // Skip to the BasicMetaDataBlock. First jump to ASTContextBlock
3191 // (which will appear earlier) and record its location.
3192
3193 bool FoundBlock = Dezr.SkipToBlock(ASTContextBlock);
3194 assert (FoundBlock);
3195
3196 llvm::Deserializer::Location ASTContextBlockLoc =
3197 Dezr.getCurrentBlockLocation();
3198
3199 FoundBlock = Dezr.SkipToBlock(BasicMetadataBlock);
3200 assert (FoundBlock);
3201
3202 // Read the SourceManager.
3203 SourceManager::CreateAndRegister(Dezr, FMgr);
3204
3205 { // Read the TargetInfo.
3206 llvm::SerializedPtrID PtrID = Dezr.ReadPtrID();
3207 char* triple = Dezr.ReadCStr(NULL,0,true);
3208 Dezr.RegisterPtr(PtrID, TargetInfo::CreateTargetInfo(std::string(triple)));
3209 delete [] triple;
3210 }
3211
3212 // For Selectors, we must read the identifier table first because the
3213 // SelectorTable depends on the identifiers being already deserialized.
3214 llvm::Deserializer::Location SelectorBlkLoc = Dezr.getCurrentBlockLocation();
3215 Dezr.SkipBlock();
3216
3217 // Read the identifier table.
3218 IdentifierTable::CreateAndRegister(Dezr);
3219
3220 // Now jump back and read the selectors.
3221 Dezr.JumpTo(SelectorBlkLoc);
3222 SelectorTable::CreateAndRegister(Dezr);
3223
3224 // Now jump back to ASTContextBlock and read the ASTContext.
3225 Dezr.JumpTo(ASTContextBlockLoc);
3226 return Dezr.ReadOwnedPtr<ASTContext>();
3227}
3228
Ted Kremenekacba3612007-11-13 00:25:37 +00003229ASTContext* ASTContext::Create(llvm::Deserializer& D) {
Ted Kremenek842126e2008-06-04 15:55:15 +00003230
3231 // Read the language options.
3232 LangOptions LOpts;
3233 LOpts.Read(D);
3234
Ted Kremenek68228a92007-10-31 22:44:07 +00003235 SourceManager &SM = D.ReadRef<SourceManager>();
3236 TargetInfo &t = D.ReadRef<TargetInfo>();
3237 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
3238 SelectorTable &sels = D.ReadRef<SelectorTable>();
Chris Lattnereee57c02008-04-04 06:12:32 +00003239
Ted Kremenek68228a92007-10-31 22:44:07 +00003240 unsigned size_reserve = D.ReadInt();
3241
Douglas Gregor24afd4a2008-11-17 14:58:09 +00003242 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels,
3243 size_reserve);
Ted Kremenek68228a92007-10-31 22:44:07 +00003244
Ted Kremenek034a78c2007-11-13 22:02:55 +00003245 for (unsigned i = 0; i < size_reserve; ++i)
3246 Type::Create(*A,i,D);
Chris Lattnereee57c02008-04-04 06:12:32 +00003247
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003248 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
3249
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00003250 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
Ted Kremenek68228a92007-10-31 22:44:07 +00003251
3252 return A;
3253}