blob: 5a6aa1ae3120514b5bb57eacf9f41ee432708fa5 [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"
Daniel Dunbarde300732008-08-11 04:54:23 +000017#include "clang/AST/Expr.h"
18#include "clang/AST/RecordLayout.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000020#include "llvm/ADT/StringExtras.h"
Ted Kremenek738e6c02007-10-31 17:10:13 +000021#include "llvm/Bitcode/Serialize.h"
22#include "llvm/Bitcode/Deserialize.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25
26enum FloatingRank {
27 FloatRank, DoubleRank, LongDoubleRank
28};
29
Daniel Dunbarde300732008-08-11 04:54:23 +000030ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, TargetInfo &t,
31 IdentifierTable &idents, SelectorTable &sels,
32 unsigned size_reserve) :
Anders Carlssonf58cac72008-08-30 19:34:46 +000033 CFConstantStringTypeDecl(0), ObjCFastEnumerationStateTypeDecl(0),
34 SourceMgr(SM), LangOpts(LOpts), Target(t),
Daniel Dunbarde300732008-08-11 04:54:23 +000035 Idents(idents), Selectors(sels)
36{
37 if (size_reserve > 0) Types.reserve(size_reserve);
38 InitBuiltinTypes();
39 BuiltinInfo.InitializeBuiltins(idents, Target);
40 TUDecl = TranslationUnitDecl::Create(*this);
41}
42
Chris Lattner4b009652007-07-25 00:24:17 +000043ASTContext::~ASTContext() {
44 // Deallocate all the types.
45 while (!Types.empty()) {
Ted Kremenekdb4d5972008-05-21 16:38:54 +000046 Types.back()->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000047 Types.pop_back();
48 }
Eli Friedman65489b72008-05-27 03:08:09 +000049
50 TUDecl->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000051}
52
53void ASTContext::PrintStats() const {
54 fprintf(stderr, "*** AST Context Stats:\n");
55 fprintf(stderr, " %d types total.\n", (int)Types.size());
56 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
57 unsigned NumVector = 0, NumComplex = 0;
58 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
59
60 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000061 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
62 unsigned NumObjCQualifiedIds = 0;
Steve Naroffe0430632008-05-21 15:59:22 +000063 unsigned NumTypeOfTypes = 0, NumTypeOfExprs = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000064
65 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
66 Type *T = Types[i];
67 if (isa<BuiltinType>(T))
68 ++NumBuiltin;
69 else if (isa<PointerType>(T))
70 ++NumPointer;
71 else if (isa<ReferenceType>(T))
72 ++NumReference;
73 else if (isa<ComplexType>(T))
74 ++NumComplex;
75 else if (isa<ArrayType>(T))
76 ++NumArray;
77 else if (isa<VectorType>(T))
78 ++NumVector;
79 else if (isa<FunctionTypeNoProto>(T))
80 ++NumFunctionNP;
81 else if (isa<FunctionTypeProto>(T))
82 ++NumFunctionP;
83 else if (isa<TypedefType>(T))
84 ++NumTypeName;
85 else if (TagType *TT = dyn_cast<TagType>(T)) {
86 ++NumTagged;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +000087 switch (TT->getDecl()->getTagKind()) {
Chris Lattner4b009652007-07-25 00:24:17 +000088 default: assert(0 && "Unknown tagged type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +000089 case TagDecl::TK_struct: ++NumTagStruct; break;
90 case TagDecl::TK_union: ++NumTagUnion; break;
91 case TagDecl::TK_class: ++NumTagClass; break;
92 case TagDecl::TK_enum: ++NumTagEnum; break;
Chris Lattner4b009652007-07-25 00:24:17 +000093 }
Ted Kremenek42730c52008-01-07 19:49:32 +000094 } else if (isa<ObjCInterfaceType>(T))
95 ++NumObjCInterfaces;
96 else if (isa<ObjCQualifiedInterfaceType>(T))
97 ++NumObjCQualifiedInterfaces;
98 else if (isa<ObjCQualifiedIdType>(T))
99 ++NumObjCQualifiedIds;
Steve Naroffe0430632008-05-21 15:59:22 +0000100 else if (isa<TypeOfType>(T))
101 ++NumTypeOfTypes;
102 else if (isa<TypeOfExpr>(T))
103 ++NumTypeOfExprs;
Steve Naroff948fd372007-09-17 14:16:13 +0000104 else {
Chris Lattner8a35b462007-12-12 06:43:05 +0000105 QualType(T, 0).dump();
Chris Lattner4b009652007-07-25 00:24:17 +0000106 assert(0 && "Unknown type!");
107 }
108 }
109
110 fprintf(stderr, " %d builtin types\n", NumBuiltin);
111 fprintf(stderr, " %d pointer types\n", NumPointer);
112 fprintf(stderr, " %d reference types\n", NumReference);
113 fprintf(stderr, " %d complex types\n", NumComplex);
114 fprintf(stderr, " %d array types\n", NumArray);
115 fprintf(stderr, " %d vector types\n", NumVector);
116 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
117 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
118 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
119 fprintf(stderr, " %d tagged types\n", NumTagged);
120 fprintf(stderr, " %d struct types\n", NumTagStruct);
121 fprintf(stderr, " %d union types\n", NumTagUnion);
122 fprintf(stderr, " %d class types\n", NumTagClass);
123 fprintf(stderr, " %d enum types\n", NumTagEnum);
Ted Kremenek42730c52008-01-07 19:49:32 +0000124 fprintf(stderr, " %d interface types\n", NumObjCInterfaces);
Chris Lattner8a35b462007-12-12 06:43:05 +0000125 fprintf(stderr, " %d protocol qualified interface types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000126 NumObjCQualifiedInterfaces);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000127 fprintf(stderr, " %d protocol qualified id types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000128 NumObjCQualifiedIds);
Steve Naroffe0430632008-05-21 15:59:22 +0000129 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes);
130 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprs);
131
Chris Lattner4b009652007-07-25 00:24:17 +0000132 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
133 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
134 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
135 NumFunctionP*sizeof(FunctionTypeProto)+
136 NumFunctionNP*sizeof(FunctionTypeNoProto)+
Steve Naroffe0430632008-05-21 15:59:22 +0000137 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
138 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprs*sizeof(TypeOfExpr)));
Chris Lattner4b009652007-07-25 00:24:17 +0000139}
140
141
142void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
143 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr());
144}
145
Chris Lattner4b009652007-07-25 00:24:17 +0000146void ASTContext::InitBuiltinTypes() {
147 assert(VoidTy.isNull() && "Context reinitialized?");
148
149 // C99 6.2.5p19.
150 InitBuiltinType(VoidTy, BuiltinType::Void);
151
152 // C99 6.2.5p2.
153 InitBuiltinType(BoolTy, BuiltinType::Bool);
154 // C99 6.2.5p3.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000155 if (Target.isCharSigned())
Chris Lattner4b009652007-07-25 00:24:17 +0000156 InitBuiltinType(CharTy, BuiltinType::Char_S);
157 else
158 InitBuiltinType(CharTy, BuiltinType::Char_U);
159 // C99 6.2.5p4.
160 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
161 InitBuiltinType(ShortTy, BuiltinType::Short);
162 InitBuiltinType(IntTy, BuiltinType::Int);
163 InitBuiltinType(LongTy, BuiltinType::Long);
164 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
165
166 // C99 6.2.5p6.
167 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
168 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
169 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
170 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
171 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
172
173 // C99 6.2.5p10.
174 InitBuiltinType(FloatTy, BuiltinType::Float);
175 InitBuiltinType(DoubleTy, BuiltinType::Double);
176 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000177
178 // C++ 3.9.1p5
179 InitBuiltinType(WCharTy, BuiltinType::WChar);
180
Chris Lattner4b009652007-07-25 00:24:17 +0000181 // C99 6.2.5p11.
182 FloatComplexTy = getComplexType(FloatTy);
183 DoubleComplexTy = getComplexType(DoubleTy);
184 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Steve Naroff9d12c902007-10-15 14:41:52 +0000185
186 BuiltinVaListType = QualType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000187 ObjCIdType = QualType();
Steve Naroff9d12c902007-10-15 14:41:52 +0000188 IdStructType = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000189 ObjCClassType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000190 ClassStructType = 0;
191
Ted Kremenek42730c52008-01-07 19:49:32 +0000192 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000193
194 // void * type
195 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000196}
197
198//===----------------------------------------------------------------------===//
199// Type Sizing and Analysis
200//===----------------------------------------------------------------------===//
201
Chris Lattner2a674dc2008-06-30 18:32:54 +0000202/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
203/// scalar floating point type.
204const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
205 const BuiltinType *BT = T->getAsBuiltinType();
206 assert(BT && "Not a floating point type!");
207 switch (BT->getKind()) {
208 default: assert(0 && "Not a floating point type!");
209 case BuiltinType::Float: return Target.getFloatFormat();
210 case BuiltinType::Double: return Target.getDoubleFormat();
211 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
212 }
213}
214
215
Chris Lattner4b009652007-07-25 00:24:17 +0000216/// getTypeSize - Return the size of the specified type, in bits. This method
217/// does not work on incomplete types.
218std::pair<uint64_t, unsigned>
Chris Lattner8cd0e932008-03-05 18:54:05 +0000219ASTContext::getTypeInfo(QualType T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000220 T = getCanonicalType(T);
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000221 uint64_t Width;
Chris Lattner4b009652007-07-25 00:24:17 +0000222 unsigned Align;
223 switch (T->getTypeClass()) {
224 case Type::TypeName: assert(0 && "Not a canonical type!");
225 case Type::FunctionNoProto:
226 case Type::FunctionProto:
227 default:
228 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000229 case Type::VariableArray:
230 assert(0 && "VLAs not implemented yet!");
231 case Type::ConstantArray: {
232 ConstantArrayType *CAT = cast<ConstantArrayType>(T);
233
Chris Lattner8cd0e932008-03-05 18:54:05 +0000234 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000235 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000236 Align = EltInfo.second;
237 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000238 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000239 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000240 case Type::Vector: {
241 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000242 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000243 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000244 // FIXME: This isn't right for unusual vectors
245 Align = Width;
Chris Lattner4b009652007-07-25 00:24:17 +0000246 break;
247 }
248
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000249 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000250 switch (cast<BuiltinType>(T)->getKind()) {
251 default: assert(0 && "Unknown builtin type!");
252 case BuiltinType::Void:
253 assert(0 && "Incomplete types have no size!");
Chris Lattnerb66237b2007-12-19 19:23:28 +0000254 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000255 Width = Target.getBoolWidth();
256 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000257 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000258 case BuiltinType::Char_S:
259 case BuiltinType::Char_U:
260 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000261 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000262 Width = Target.getCharWidth();
263 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000264 break;
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000265 case BuiltinType::WChar:
266 Width = Target.getWCharWidth();
267 Align = Target.getWCharAlign();
268 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000269 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000270 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000271 Width = Target.getShortWidth();
272 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000273 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000274 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000275 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000276 Width = Target.getIntWidth();
277 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000278 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000279 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000280 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000281 Width = Target.getLongWidth();
282 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000283 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000284 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000285 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000286 Width = Target.getLongLongWidth();
287 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000288 break;
289 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000290 Width = Target.getFloatWidth();
291 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000292 break;
293 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000294 Width = Target.getDoubleWidth();
295 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000296 break;
297 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000298 Width = Target.getLongDoubleWidth();
299 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000300 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000301 }
302 break;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000303 case Type::ASQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000304 // FIXME: Pointers into different addr spaces could have different sizes and
305 // alignment requirements: getPointerInfo should take an AddrSpace.
306 return getTypeInfo(QualType(cast<ASQualType>(T)->getBaseType(), 0));
Ted Kremenek42730c52008-01-07 19:49:32 +0000307 case Type::ObjCQualifiedId:
Chris Lattner1d78a862008-04-07 07:01:58 +0000308 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000309 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000310 break;
Chris Lattner461a6c52008-03-08 08:34:58 +0000311 case Type::Pointer: {
312 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000313 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000314 Align = Target.getPointerAlign(AS);
315 break;
316 }
Chris Lattner4b009652007-07-25 00:24:17 +0000317 case Type::Reference:
318 // "When applied to a reference or a reference type, the result is the size
319 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000320 // FIXME: This is wrong for struct layout: a reference in a struct has
321 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000322 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Chris Lattner4b009652007-07-25 00:24:17 +0000323
324 case Type::Complex: {
325 // Complex types have the same alignment as their elements, but twice the
326 // size.
327 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000328 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000329 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000330 Align = EltInfo.second;
331 break;
332 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000333 case Type::ObjCInterface: {
334 ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
335 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
336 Width = Layout.getSize();
337 Align = Layout.getAlignment();
338 break;
339 }
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000340 case Type::Tagged: {
Chris Lattnerfd799692008-08-09 21:35:13 +0000341 if (cast<TagType>(T)->getDecl()->isInvalidDecl()) {
342 Width = 1;
343 Align = 1;
344 break;
345 }
346
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000347 if (EnumType *ET = dyn_cast<EnumType>(cast<TagType>(T)))
348 return getTypeInfo(ET->getDecl()->getIntegerType());
349
350 RecordType *RT = cast<RecordType>(T);
351 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
352 Width = Layout.getSize();
353 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000354 break;
355 }
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000356 }
Chris Lattner4b009652007-07-25 00:24:17 +0000357
358 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000359 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000360}
361
Devang Patelbfe323c2008-06-04 21:22:16 +0000362/// LayoutField - Field layout.
363void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
364 bool IsUnion, bool StructIsPacked,
365 ASTContext &Context) {
366 bool FieldIsPacked = StructIsPacked || FD->getAttr<PackedAttr>();
367 uint64_t FieldOffset = IsUnion ? 0 : Size;
368 uint64_t FieldSize;
369 unsigned FieldAlign;
370
371 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
372 // TODO: Need to check this algorithm on other targets!
373 // (tested on Linux-X86)
Daniel Dunbar7cbcbf42008-08-13 23:47:13 +0000374 FieldSize =
375 BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue();
Devang Patelbfe323c2008-06-04 21:22:16 +0000376
377 std::pair<uint64_t, unsigned> FieldInfo =
378 Context.getTypeInfo(FD->getType());
379 uint64_t TypeSize = FieldInfo.first;
380
381 FieldAlign = FieldInfo.second;
382 if (FieldIsPacked)
383 FieldAlign = 1;
384 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
385 FieldAlign = std::max(FieldAlign, AA->getAlignment());
386
387 // Check if we need to add padding to give the field the correct
388 // alignment.
389 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
390 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
391
392 // Padding members don't affect overall alignment
393 if (!FD->getIdentifier())
394 FieldAlign = 1;
395 } else {
Chris Lattnerfd799692008-08-09 21:35:13 +0000396 if (FD->getType()->isIncompleteArrayType()) {
397 // This is a flexible array member; we can't directly
Devang Patelbfe323c2008-06-04 21:22:16 +0000398 // query getTypeInfo about these, so we figure it out here.
399 // Flexible array members don't have any size, but they
400 // have to be aligned appropriately for their element type.
401 FieldSize = 0;
Chris Lattnera1923f62008-08-04 07:31:14 +0000402 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patelbfe323c2008-06-04 21:22:16 +0000403 FieldAlign = Context.getTypeAlign(ATy->getElementType());
404 } else {
405 std::pair<uint64_t, unsigned> FieldInfo =
406 Context.getTypeInfo(FD->getType());
407 FieldSize = FieldInfo.first;
408 FieldAlign = FieldInfo.second;
409 }
410
411 if (FieldIsPacked)
412 FieldAlign = 8;
413 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
414 FieldAlign = std::max(FieldAlign, AA->getAlignment());
415
416 // Round up the current record size to the field's alignment boundary.
417 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
418 }
419
420 // Place this field at the current location.
421 FieldOffsets[FieldNo] = FieldOffset;
422
423 // Reserve space for this field.
424 if (IsUnion) {
425 Size = std::max(Size, FieldSize);
426 } else {
427 Size = FieldOffset + FieldSize;
428 }
429
430 // Remember max struct/class alignment.
431 Alignment = std::max(Alignment, FieldAlign);
432}
433
Devang Patel4b6bf702008-06-04 21:54:36 +0000434
435/// getASTObjcInterfaceLayout - Get or compute information about the layout of the
436/// specified Objective C, which indicates its size and ivar
437/// position information.
438const ASTRecordLayout &
439ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
440 // Look up this layout, if already laid out, return what we have.
441 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
442 if (Entry) return *Entry;
443
444 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
445 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
Devang Patel8682d882008-06-06 02:14:01 +0000446 ASTRecordLayout *NewEntry = NULL;
447 unsigned FieldCount = D->ivar_size();
448 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
449 FieldCount++;
450 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
451 unsigned Alignment = SL.getAlignment();
452 uint64_t Size = SL.getSize();
453 NewEntry = new ASTRecordLayout(Size, Alignment);
454 NewEntry->InitializeLayout(FieldCount);
455 NewEntry->SetFieldOffset(0, 0); // Super class is at the beginning of the layout.
456 } else {
457 NewEntry = new ASTRecordLayout();
458 NewEntry->InitializeLayout(FieldCount);
459 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000460 Entry = NewEntry;
461
Devang Patel4b6bf702008-06-04 21:54:36 +0000462 bool IsPacked = D->getAttr<PackedAttr>();
463
464 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
465 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
466 AA->getAlignment()));
467
468 // Layout each ivar sequentially.
469 unsigned i = 0;
470 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
471 IVE = D->ivar_end(); IVI != IVE; ++IVI) {
472 const ObjCIvarDecl* Ivar = (*IVI);
473 NewEntry->LayoutField(Ivar, i++, false, IsPacked, *this);
474 }
475
476 // Finally, round the size of the total struct up to the alignment of the
477 // struct itself.
478 NewEntry->FinalizeLayout();
479 return *NewEntry;
480}
481
Devang Patel7a78e432007-11-01 19:11:01 +0000482/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000483/// specified record (struct/union/class), which indicates its size and field
484/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000485const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000486 assert(D->isDefinition() && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000487
Chris Lattner4b009652007-07-25 00:24:17 +0000488 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000489 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000490 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000491
Devang Patel7a78e432007-11-01 19:11:01 +0000492 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
493 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
494 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000495 Entry = NewEntry;
Eli Friedman5949a022008-05-30 09:31:38 +0000496
Devang Patelbfe323c2008-06-04 21:22:16 +0000497 NewEntry->InitializeLayout(D->getNumMembers());
Eli Friedman5949a022008-05-30 09:31:38 +0000498 bool StructIsPacked = D->getAttr<PackedAttr>();
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000499 bool IsUnion = D->isUnion();
Chris Lattner4b009652007-07-25 00:24:17 +0000500
Eli Friedman5949a022008-05-30 09:31:38 +0000501 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patelbfe323c2008-06-04 21:22:16 +0000502 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
503 AA->getAlignment()));
Anders Carlsson058237f2008-02-18 07:13:09 +0000504
Eli Friedman5949a022008-05-30 09:31:38 +0000505 // Layout each field, for now, just sequentially, respecting alignment. In
506 // the future, this will need to be tweakable by targets.
507 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
508 const FieldDecl *FD = D->getMember(i);
Devang Patelbfe323c2008-06-04 21:22:16 +0000509 NewEntry->LayoutField(FD, i, IsUnion, StructIsPacked, *this);
Chris Lattner4b009652007-07-25 00:24:17 +0000510 }
Eli Friedman5949a022008-05-30 09:31:38 +0000511
512 // Finally, round the size of the total struct up to the alignment of the
513 // struct itself.
Devang Patelbfe323c2008-06-04 21:22:16 +0000514 NewEntry->FinalizeLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000515 return *NewEntry;
516}
517
Chris Lattner4b009652007-07-25 00:24:17 +0000518//===----------------------------------------------------------------------===//
519// Type creation/memoization methods
520//===----------------------------------------------------------------------===//
521
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000522QualType ASTContext::getASQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000523 QualType CanT = getCanonicalType(T);
524 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000525 return T;
526
527 // Type's cannot have multiple ASQuals, therefore we know we only have to deal
528 // with CVR qualifiers from here on out.
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000529 assert(CanT.getAddressSpace() == 0 &&
Chris Lattner35fef522008-02-20 20:55:12 +0000530 "Type is already address space qualified");
531
532 // Check if we've already instantiated an address space qual'd type of this
533 // type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000534 llvm::FoldingSetNodeID ID;
Chris Lattner35fef522008-02-20 20:55:12 +0000535 ASQualType::Profile(ID, T.getTypePtr(), AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000536 void *InsertPos = 0;
537 if (ASQualType *ASQy = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos))
538 return QualType(ASQy, 0);
539
540 // If the base type isn't canonical, this won't be a canonical type either,
541 // so fill in the canonical type field.
542 QualType Canonical;
543 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000544 Canonical = getASQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000545
546 // Get the new insert position for the node we care about.
547 ASQualType *NewIP = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos);
548 assert(NewIP == 0 && "Shouldn't be in the map!");
549 }
Chris Lattner35fef522008-02-20 20:55:12 +0000550 ASQualType *New = new ASQualType(T.getTypePtr(), Canonical, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000551 ASQualTypes.InsertNode(New, InsertPos);
552 Types.push_back(New);
Chris Lattner35fef522008-02-20 20:55:12 +0000553 return QualType(New, T.getCVRQualifiers());
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000554}
555
Chris Lattner4b009652007-07-25 00:24:17 +0000556
557/// getComplexType - Return the uniqued reference to the type for a complex
558/// number with the specified element type.
559QualType ASTContext::getComplexType(QualType T) {
560 // Unique pointers, to guarantee there is only one pointer of a particular
561 // structure.
562 llvm::FoldingSetNodeID ID;
563 ComplexType::Profile(ID, T);
564
565 void *InsertPos = 0;
566 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
567 return QualType(CT, 0);
568
569 // If the pointee type isn't canonical, this won't be a canonical type either,
570 // so fill in the canonical type field.
571 QualType Canonical;
572 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000573 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000574
575 // Get the new insert position for the node we care about.
576 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
577 assert(NewIP == 0 && "Shouldn't be in the map!");
578 }
579 ComplexType *New = new ComplexType(T, Canonical);
580 Types.push_back(New);
581 ComplexTypes.InsertNode(New, InsertPos);
582 return QualType(New, 0);
583}
584
585
586/// getPointerType - Return the uniqued reference to the type for a pointer to
587/// the specified type.
588QualType ASTContext::getPointerType(QualType T) {
589 // Unique pointers, to guarantee there is only one pointer of a particular
590 // structure.
591 llvm::FoldingSetNodeID ID;
592 PointerType::Profile(ID, T);
593
594 void *InsertPos = 0;
595 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
596 return QualType(PT, 0);
597
598 // If the pointee type isn't canonical, this won't be a canonical type either,
599 // so fill in the canonical type field.
600 QualType Canonical;
601 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000602 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000603
604 // Get the new insert position for the node we care about.
605 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
606 assert(NewIP == 0 && "Shouldn't be in the map!");
607 }
608 PointerType *New = new PointerType(T, Canonical);
609 Types.push_back(New);
610 PointerTypes.InsertNode(New, InsertPos);
611 return QualType(New, 0);
612}
613
Steve Naroff7aa54752008-08-27 16:04:49 +0000614/// getBlockPointerType - Return the uniqued reference to the type for
615/// a pointer to the specified block.
616QualType ASTContext::getBlockPointerType(QualType T) {
Steve Narofffd5b19d2008-08-28 19:20:44 +0000617 assert(T->isFunctionType() && "block of function types only");
618 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff7aa54752008-08-27 16:04:49 +0000619 // structure.
620 llvm::FoldingSetNodeID ID;
621 BlockPointerType::Profile(ID, T);
622
623 void *InsertPos = 0;
624 if (BlockPointerType *PT =
625 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
626 return QualType(PT, 0);
627
Steve Narofffd5b19d2008-08-28 19:20:44 +0000628 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff7aa54752008-08-27 16:04:49 +0000629 // type either so fill in the canonical type field.
630 QualType Canonical;
631 if (!T->isCanonical()) {
632 Canonical = getBlockPointerType(getCanonicalType(T));
633
634 // Get the new insert position for the node we care about.
635 BlockPointerType *NewIP =
636 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
637 assert(NewIP == 0 && "Shouldn't be in the map!");
638 }
639 BlockPointerType *New = new BlockPointerType(T, Canonical);
640 Types.push_back(New);
641 BlockPointerTypes.InsertNode(New, InsertPos);
642 return QualType(New, 0);
643}
644
Chris Lattner4b009652007-07-25 00:24:17 +0000645/// getReferenceType - Return the uniqued reference to the type for a reference
646/// to the specified type.
647QualType ASTContext::getReferenceType(QualType T) {
648 // Unique pointers, to guarantee there is only one pointer of a particular
649 // structure.
650 llvm::FoldingSetNodeID ID;
651 ReferenceType::Profile(ID, T);
652
653 void *InsertPos = 0;
654 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
655 return QualType(RT, 0);
656
657 // If the referencee type isn't canonical, this won't be a canonical type
658 // either, so fill in the canonical type field.
659 QualType Canonical;
660 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000661 Canonical = getReferenceType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000662
663 // Get the new insert position for the node we care about.
664 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
665 assert(NewIP == 0 && "Shouldn't be in the map!");
666 }
667
668 ReferenceType *New = new ReferenceType(T, Canonical);
669 Types.push_back(New);
670 ReferenceTypes.InsertNode(New, InsertPos);
671 return QualType(New, 0);
672}
673
Steve Naroff83c13012007-08-30 01:06:46 +0000674/// getConstantArrayType - Return the unique reference to the type for an
675/// array of the specified element type.
676QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +0000677 const llvm::APInt &ArySize,
678 ArrayType::ArraySizeModifier ASM,
679 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +0000680 llvm::FoldingSetNodeID ID;
Steve Naroff83c13012007-08-30 01:06:46 +0000681 ConstantArrayType::Profile(ID, EltTy, ArySize);
Chris Lattner4b009652007-07-25 00:24:17 +0000682
683 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +0000684 if (ConstantArrayType *ATP =
685 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000686 return QualType(ATP, 0);
687
688 // If the element type isn't canonical, this won't be a canonical type either,
689 // so fill in the canonical type field.
690 QualType Canonical;
691 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000692 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +0000693 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +0000694 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +0000695 ConstantArrayType *NewIP =
696 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
697
Chris Lattner4b009652007-07-25 00:24:17 +0000698 assert(NewIP == 0 && "Shouldn't be in the map!");
699 }
700
Steve Naroff24c9b982007-08-30 18:10:14 +0000701 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
702 ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +0000703 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000704 Types.push_back(New);
705 return QualType(New, 0);
706}
707
Steve Naroffe2579e32007-08-30 18:14:25 +0000708/// getVariableArrayType - Returns a non-unique reference to the type for a
709/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +0000710QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
711 ArrayType::ArraySizeModifier ASM,
712 unsigned EltTypeQuals) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000713 // Since we don't unique expressions, it isn't possible to unique VLA's
714 // that have an expression provided for their size.
715
716 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
717 ASM, EltTypeQuals);
718
719 VariableArrayTypes.push_back(New);
720 Types.push_back(New);
721 return QualType(New, 0);
722}
723
724QualType ASTContext::getIncompleteArrayType(QualType EltTy,
725 ArrayType::ArraySizeModifier ASM,
726 unsigned EltTypeQuals) {
727 llvm::FoldingSetNodeID ID;
728 IncompleteArrayType::Profile(ID, EltTy);
729
730 void *InsertPos = 0;
731 if (IncompleteArrayType *ATP =
732 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
733 return QualType(ATP, 0);
734
735 // If the element type isn't canonical, this won't be a canonical type
736 // either, so fill in the canonical type field.
737 QualType Canonical;
738
739 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000740 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000741 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +0000742
743 // Get the new insert position for the node we care about.
744 IncompleteArrayType *NewIP =
745 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
746
747 assert(NewIP == 0 && "Shouldn't be in the map!");
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000748 }
Eli Friedman8ff07782008-02-15 18:16:39 +0000749
750 IncompleteArrayType *New = new IncompleteArrayType(EltTy, Canonical,
751 ASM, EltTypeQuals);
752
753 IncompleteArrayTypes.InsertNode(New, InsertPos);
754 Types.push_back(New);
755 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +0000756}
757
Chris Lattner4b009652007-07-25 00:24:17 +0000758/// getVectorType - Return the unique reference to a vector type of
759/// the specified element type and size. VectorType must be a built-in type.
760QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
761 BuiltinType *baseType;
762
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000763 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +0000764 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
765
766 // Check if we've already instantiated a vector of this type.
767 llvm::FoldingSetNodeID ID;
768 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
769 void *InsertPos = 0;
770 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
771 return QualType(VTP, 0);
772
773 // If the element type isn't canonical, this won't be a canonical type either,
774 // so fill in the canonical type field.
775 QualType Canonical;
776 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000777 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +0000778
779 // Get the new insert position for the node we care about.
780 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
781 assert(NewIP == 0 && "Shouldn't be in the map!");
782 }
783 VectorType *New = new VectorType(vecType, NumElts, Canonical);
784 VectorTypes.InsertNode(New, InsertPos);
785 Types.push_back(New);
786 return QualType(New, 0);
787}
788
Nate Begemanaf6ed502008-04-18 23:10:10 +0000789/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +0000790/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000791QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +0000792 BuiltinType *baseType;
793
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000794 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +0000795 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +0000796
797 // Check if we've already instantiated a vector of this type.
798 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +0000799 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +0000800 void *InsertPos = 0;
801 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
802 return QualType(VTP, 0);
803
804 // If the element type isn't canonical, this won't be a canonical type either,
805 // so fill in the canonical type field.
806 QualType Canonical;
807 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000808 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +0000809
810 // Get the new insert position for the node we care about.
811 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
812 assert(NewIP == 0 && "Shouldn't be in the map!");
813 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000814 ExtVectorType *New = new ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000815 VectorTypes.InsertNode(New, InsertPos);
816 Types.push_back(New);
817 return QualType(New, 0);
818}
819
820/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
821///
822QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
823 // Unique functions, to guarantee there is only one function of a particular
824 // structure.
825 llvm::FoldingSetNodeID ID;
826 FunctionTypeNoProto::Profile(ID, ResultTy);
827
828 void *InsertPos = 0;
829 if (FunctionTypeNoProto *FT =
830 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
831 return QualType(FT, 0);
832
833 QualType Canonical;
834 if (!ResultTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000835 Canonical = getFunctionTypeNoProto(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000836
837 // Get the new insert position for the node we care about.
838 FunctionTypeNoProto *NewIP =
839 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
840 assert(NewIP == 0 && "Shouldn't be in the map!");
841 }
842
843 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
844 Types.push_back(New);
Eli Friedmanaa0fdfd2008-02-25 22:11:40 +0000845 FunctionTypeNoProtos.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000846 return QualType(New, 0);
847}
848
849/// getFunctionType - Return a normal function type with a typed argument
850/// list. isVariadic indicates whether the argument list includes '...'.
Eli Friedman36104c12008-08-22 00:59:49 +0000851QualType ASTContext::getFunctionType(QualType ResultTy, const QualType *ArgArray,
Chris Lattner4b009652007-07-25 00:24:17 +0000852 unsigned NumArgs, bool isVariadic) {
853 // Unique functions, to guarantee there is only one function of a particular
854 // structure.
855 llvm::FoldingSetNodeID ID;
856 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic);
857
858 void *InsertPos = 0;
859 if (FunctionTypeProto *FTP =
860 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
861 return QualType(FTP, 0);
862
863 // Determine whether the type being created is already canonical or not.
864 bool isCanonical = ResultTy->isCanonical();
865 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
866 if (!ArgArray[i]->isCanonical())
867 isCanonical = false;
868
869 // If this type isn't canonical, get the canonical version of it.
870 QualType Canonical;
871 if (!isCanonical) {
872 llvm::SmallVector<QualType, 16> CanonicalArgs;
873 CanonicalArgs.reserve(NumArgs);
874 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000875 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Chris Lattner4b009652007-07-25 00:24:17 +0000876
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000877 Canonical = getFunctionType(getCanonicalType(ResultTy),
Chris Lattner4b009652007-07-25 00:24:17 +0000878 &CanonicalArgs[0], NumArgs,
879 isVariadic);
880
881 // Get the new insert position for the node we care about.
882 FunctionTypeProto *NewIP =
883 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
884 assert(NewIP == 0 && "Shouldn't be in the map!");
885 }
886
887 // FunctionTypeProto objects are not allocated with new because they have a
888 // variable size array (for parameter types) at the end of them.
889 FunctionTypeProto *FTP =
890 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) +
891 NumArgs*sizeof(QualType));
892 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
893 Canonical);
894 Types.push_back(FTP);
895 FunctionTypeProtos.InsertNode(FTP, InsertPos);
896 return QualType(FTP, 0);
897}
898
Douglas Gregor1d661552008-04-13 21:07:44 +0000899/// getTypeDeclType - Return the unique reference to the type for the
900/// specified type declaration.
901QualType ASTContext::getTypeDeclType(TypeDecl *Decl) {
902 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
903
904 if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(Decl))
905 return getTypedefType(Typedef);
906 else if (ObjCInterfaceDecl *ObjCInterface
907 = dyn_cast_or_null<ObjCInterfaceDecl>(Decl))
908 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000909
910 if (CXXRecordDecl *CXXRecord = dyn_cast_or_null<CXXRecordDecl>(Decl))
911 Decl->TypeForDecl = new CXXRecordType(CXXRecord);
912 else if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +0000913 Decl->TypeForDecl = new RecordType(Record);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000914 else if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +0000915 Decl->TypeForDecl = new EnumType(Enum);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000916 else
Douglas Gregor1d661552008-04-13 21:07:44 +0000917 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000918
919 Types.push_back(Decl->TypeForDecl);
920 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +0000921}
922
Chris Lattner4b009652007-07-25 00:24:17 +0000923/// getTypedefType - Return the unique reference to the type for the
924/// specified typename decl.
925QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
926 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
927
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000928 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000929 Decl->TypeForDecl = new TypedefType(Type::TypeName, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000930 Types.push_back(Decl->TypeForDecl);
931 return QualType(Decl->TypeForDecl, 0);
932}
933
Ted Kremenek42730c52008-01-07 19:49:32 +0000934/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff81f1bba2007-09-06 21:24:23 +0000935/// specified ObjC interface decl.
Ted Kremenek42730c52008-01-07 19:49:32 +0000936QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
Steve Naroff81f1bba2007-09-06 21:24:23 +0000937 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
938
Ted Kremenek42730c52008-01-07 19:49:32 +0000939 Decl->TypeForDecl = new ObjCInterfaceType(Type::ObjCInterface, Decl);
Steve Naroff81f1bba2007-09-06 21:24:23 +0000940 Types.push_back(Decl->TypeForDecl);
941 return QualType(Decl->TypeForDecl, 0);
942}
943
Chris Lattnere1352302008-04-07 04:56:42 +0000944/// CmpProtocolNames - Comparison predicate for sorting protocols
945/// alphabetically.
946static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
947 const ObjCProtocolDecl *RHS) {
948 return strcmp(LHS->getName(), RHS->getName()) < 0;
949}
950
951static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
952 unsigned &NumProtocols) {
953 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
954
955 // Sort protocols, keyed by name.
956 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
957
958 // Remove duplicates.
959 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
960 NumProtocols = ProtocolsEnd-Protocols;
961}
962
963
Chris Lattnerb0c6a1f2008-04-07 04:44:08 +0000964/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
965/// the given interface decl and the conforming protocol list.
Ted Kremenek42730c52008-01-07 19:49:32 +0000966QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
967 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +0000968 // Sort the protocol list alphabetically to canonicalize it.
969 SortAndUniqueProtocols(Protocols, NumProtocols);
970
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000971 llvm::FoldingSetNodeID ID;
Chris Lattner7cdcb252008-04-07 06:38:24 +0000972 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000973
974 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000975 if (ObjCQualifiedInterfaceType *QT =
976 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000977 return QualType(QT, 0);
978
979 // No Match;
Ted Kremenek42730c52008-01-07 19:49:32 +0000980 ObjCQualifiedInterfaceType *QType =
981 new ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000982 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +0000983 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000984 return QualType(QType, 0);
985}
986
Chris Lattnere1352302008-04-07 04:56:42 +0000987/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
988/// and the conforming protocol list.
Chris Lattner4a68fe02008-07-26 00:46:50 +0000989QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000990 unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +0000991 // Sort the protocol list alphabetically to canonicalize it.
992 SortAndUniqueProtocols(Protocols, NumProtocols);
993
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000994 llvm::FoldingSetNodeID ID;
Ted Kremenek42730c52008-01-07 19:49:32 +0000995 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000996
997 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000998 if (ObjCQualifiedIdType *QT =
Chris Lattner4a68fe02008-07-26 00:46:50 +0000999 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001000 return QualType(QT, 0);
1001
1002 // No Match;
Chris Lattner4a68fe02008-07-26 00:46:50 +00001003 ObjCQualifiedIdType *QType = new ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001004 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001005 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001006 return QualType(QType, 0);
1007}
1008
Steve Naroff0604dd92007-08-01 18:02:17 +00001009/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
1010/// TypeOfExpr AST's (since expression's are never shared). For example,
1011/// multiple declarations that refer to "typeof(x)" all contain different
1012/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1013/// on canonical type's (which are always unique).
Steve Naroff11b649c2007-08-01 17:20:42 +00001014QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001015 QualType Canonical = getCanonicalType(tofExpr->getType());
Steve Naroff0604dd92007-08-01 18:02:17 +00001016 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
1017 Types.push_back(toe);
1018 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001019}
1020
Steve Naroff0604dd92007-08-01 18:02:17 +00001021/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1022/// TypeOfType AST's. The only motivation to unique these nodes would be
1023/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1024/// an issue. This doesn't effect the type checker, since it operates
1025/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +00001026QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001027 QualType Canonical = getCanonicalType(tofType);
Steve Naroff0604dd92007-08-01 18:02:17 +00001028 TypeOfType *tot = new TypeOfType(tofType, Canonical);
1029 Types.push_back(tot);
1030 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001031}
1032
Chris Lattner4b009652007-07-25 00:24:17 +00001033/// getTagDeclType - Return the unique reference to the type for the
1034/// specified TagDecl (struct/union/class/enum) decl.
1035QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +00001036 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +00001037 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001038}
1039
1040/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1041/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1042/// needs to agree with the definition in <stddef.h>.
1043QualType ASTContext::getSizeType() const {
1044 // On Darwin, size_t is defined as a "long unsigned int".
1045 // FIXME: should derive from "Target".
1046 return UnsignedLongTy;
1047}
1048
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +00001049/// getWCharType - Return the unique type for "wchar_t" (C99 7.17), the
Eli Friedmanfdd35d72008-02-12 08:29:21 +00001050/// width of characters in wide strings, The value is target dependent and
1051/// needs to agree with the definition in <stddef.h>.
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +00001052QualType ASTContext::getWCharType() const {
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001053 if (LangOpts.CPlusPlus)
1054 return WCharTy;
1055
Eli Friedmanfdd35d72008-02-12 08:29:21 +00001056 // On Darwin, wchar_t is defined as a "int".
1057 // FIXME: should derive from "Target".
1058 return IntTy;
1059}
1060
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001061/// getSignedWCharType - Return the type of "signed wchar_t".
1062/// Used when in C++, as a GCC extension.
1063QualType ASTContext::getSignedWCharType() const {
1064 // FIXME: derive from "Target" ?
1065 return WCharTy;
1066}
1067
1068/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1069/// Used when in C++, as a GCC extension.
1070QualType ASTContext::getUnsignedWCharType() const {
1071 // FIXME: derive from "Target" ?
1072 return UnsignedIntTy;
1073}
1074
Chris Lattner4b009652007-07-25 00:24:17 +00001075/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1076/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1077QualType ASTContext::getPointerDiffType() const {
1078 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug...
1079 // FIXME: should derive from "Target".
1080 return IntTy;
1081}
1082
Chris Lattner19eb97e2008-04-02 05:18:44 +00001083//===----------------------------------------------------------------------===//
1084// Type Operators
1085//===----------------------------------------------------------------------===//
1086
Chris Lattner3dae6f42008-04-06 22:41:35 +00001087/// getCanonicalType - Return the canonical (structural) type corresponding to
1088/// the specified potentially non-canonical type. The non-canonical version
1089/// of a type may have many "decorated" versions of types. Decorators can
1090/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1091/// to be free of any of these, allowing two canonical types to be compared
1092/// for exact equality with a simple pointer comparison.
1093QualType ASTContext::getCanonicalType(QualType T) {
1094 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001095
1096 // If the result has type qualifiers, make sure to canonicalize them as well.
1097 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1098 if (TypeQuals == 0) return CanType;
1099
1100 // If the type qualifiers are on an array type, get the canonical type of the
1101 // array with the qualifiers applied to the element type.
1102 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1103 if (!AT)
1104 return CanType.getQualifiedType(TypeQuals);
1105
1106 // Get the canonical version of the element with the extra qualifiers on it.
1107 // This can recursively sink qualifiers through multiple levels of arrays.
1108 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1109 NewEltTy = getCanonicalType(NewEltTy);
1110
1111 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1112 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1113 CAT->getIndexTypeQualifier());
1114 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1115 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1116 IAT->getIndexTypeQualifier());
1117
1118 // FIXME: What is the ownership of size expressions in VLAs?
1119 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1120 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1121 VAT->getSizeModifier(),
1122 VAT->getIndexTypeQualifier());
1123}
1124
1125
1126const ArrayType *ASTContext::getAsArrayType(QualType T) {
1127 // Handle the non-qualified case efficiently.
1128 if (T.getCVRQualifiers() == 0) {
1129 // Handle the common positive case fast.
1130 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1131 return AT;
1132 }
1133
1134 // Handle the common negative case fast, ignoring CVR qualifiers.
1135 QualType CType = T->getCanonicalTypeInternal();
1136
1137 // Make sure to look through type qualifiers (like ASQuals) for the negative
1138 // test.
1139 if (!isa<ArrayType>(CType) &&
1140 !isa<ArrayType>(CType.getUnqualifiedType()))
1141 return 0;
1142
1143 // Apply any CVR qualifiers from the array type to the element type. This
1144 // implements C99 6.7.3p8: "If the specification of an array type includes
1145 // any type qualifiers, the element type is so qualified, not the array type."
1146
1147 // If we get here, we either have type qualifiers on the type, or we have
1148 // sugar such as a typedef in the way. If we have type qualifiers on the type
1149 // we must propagate them down into the elemeng type.
1150 unsigned CVRQuals = T.getCVRQualifiers();
1151 unsigned AddrSpace = 0;
1152 Type *Ty = T.getTypePtr();
1153
1154 // Rip through ASQualType's and typedefs to get to a concrete type.
1155 while (1) {
1156 if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty)) {
1157 AddrSpace = ASQT->getAddressSpace();
1158 Ty = ASQT->getBaseType();
1159 } else {
1160 T = Ty->getDesugaredType();
1161 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1162 break;
1163 CVRQuals |= T.getCVRQualifiers();
1164 Ty = T.getTypePtr();
1165 }
1166 }
1167
1168 // If we have a simple case, just return now.
1169 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1170 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1171 return ATy;
1172
1173 // Otherwise, we have an array and we have qualifiers on it. Push the
1174 // qualifiers into the array element type and return a new array type.
1175 // Get the canonical version of the element with the extra qualifiers on it.
1176 // This can recursively sink qualifiers through multiple levels of arrays.
1177 QualType NewEltTy = ATy->getElementType();
1178 if (AddrSpace)
1179 NewEltTy = getASQualType(NewEltTy, AddrSpace);
1180 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1181
1182 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1183 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1184 CAT->getSizeModifier(),
1185 CAT->getIndexTypeQualifier()));
1186 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1187 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1188 IAT->getSizeModifier(),
1189 IAT->getIndexTypeQualifier()));
1190
1191 // FIXME: What is the ownership of size expressions in VLAs?
1192 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1193 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1194 VAT->getSizeModifier(),
1195 VAT->getIndexTypeQualifier()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00001196}
1197
1198
Chris Lattner19eb97e2008-04-02 05:18:44 +00001199/// getArrayDecayedType - Return the properly qualified result of decaying the
1200/// specified array type to a pointer. This operation is non-trivial when
1201/// handling typedefs etc. The canonical type of "T" must be an array type,
1202/// this returns a pointer to a properly qualified element of the array.
1203///
1204/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1205QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001206 // Get the element type with 'getAsArrayType' so that we don't lose any
1207 // typedefs in the element type of the array. This also handles propagation
1208 // of type qualifiers from the array type into the element type if present
1209 // (C99 6.7.3p8).
1210 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1211 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00001212
Chris Lattnera1923f62008-08-04 07:31:14 +00001213 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001214
1215 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00001216 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001217}
1218
Chris Lattner4b009652007-07-25 00:24:17 +00001219/// getFloatingRank - Return a relative rank for floating point types.
1220/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001221static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001222 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00001223 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00001224
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001225 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00001226 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00001227 case BuiltinType::Float: return FloatRank;
1228 case BuiltinType::Double: return DoubleRank;
1229 case BuiltinType::LongDouble: return LongDoubleRank;
1230 }
1231}
1232
Steve Narofffa0c4532007-08-27 01:41:48 +00001233/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1234/// point or a complex type (based on typeDomain/typeSize).
1235/// 'typeDomain' is a real floating point or complex type.
1236/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00001237QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1238 QualType Domain) const {
1239 FloatingRank EltRank = getFloatingRank(Size);
1240 if (Domain->isComplexType()) {
1241 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00001242 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00001243 case FloatRank: return FloatComplexTy;
1244 case DoubleRank: return DoubleComplexTy;
1245 case LongDoubleRank: return LongDoubleComplexTy;
1246 }
Chris Lattner4b009652007-07-25 00:24:17 +00001247 }
Chris Lattner7794ae22008-04-06 23:58:54 +00001248
1249 assert(Domain->isRealFloatingType() && "Unknown domain!");
1250 switch (EltRank) {
1251 default: assert(0 && "getFloatingRank(): illegal value for rank");
1252 case FloatRank: return FloatTy;
1253 case DoubleRank: return DoubleTy;
1254 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00001255 }
Chris Lattner4b009652007-07-25 00:24:17 +00001256}
1257
Chris Lattner51285d82008-04-06 23:55:33 +00001258/// getFloatingTypeOrder - Compare the rank of the two specified floating
1259/// point types, ignoring the domain of the type (i.e. 'double' ==
1260/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1261/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001262int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1263 FloatingRank LHSR = getFloatingRank(LHS);
1264 FloatingRank RHSR = getFloatingRank(RHS);
1265
1266 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001267 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00001268 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001269 return 1;
1270 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001273/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1274/// routine will assert if passed a built-in type that isn't an integer or enum,
1275/// or if it is not canonicalized.
1276static unsigned getIntegerRank(Type *T) {
1277 assert(T->isCanonical() && "T should be canonicalized");
1278 if (isa<EnumType>(T))
1279 return 4;
1280
1281 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00001282 default: assert(0 && "getIntegerRank(): not a built-in integer");
1283 case BuiltinType::Bool:
1284 return 1;
1285 case BuiltinType::Char_S:
1286 case BuiltinType::Char_U:
1287 case BuiltinType::SChar:
1288 case BuiltinType::UChar:
1289 return 2;
1290 case BuiltinType::Short:
1291 case BuiltinType::UShort:
1292 return 3;
1293 case BuiltinType::Int:
1294 case BuiltinType::UInt:
1295 return 4;
1296 case BuiltinType::Long:
1297 case BuiltinType::ULong:
1298 return 5;
1299 case BuiltinType::LongLong:
1300 case BuiltinType::ULongLong:
1301 return 6;
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001302 }
1303}
1304
Chris Lattner51285d82008-04-06 23:55:33 +00001305/// getIntegerTypeOrder - Returns the highest ranked integer type:
1306/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
1307/// LHS < RHS, return -1.
1308int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001309 Type *LHSC = getCanonicalType(LHS).getTypePtr();
1310 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00001311 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001312
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001313 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1314 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00001315
Chris Lattner51285d82008-04-06 23:55:33 +00001316 unsigned LHSRank = getIntegerRank(LHSC);
1317 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00001318
Chris Lattner51285d82008-04-06 23:55:33 +00001319 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
1320 if (LHSRank == RHSRank) return 0;
1321 return LHSRank > RHSRank ? 1 : -1;
1322 }
Chris Lattner4b009652007-07-25 00:24:17 +00001323
Chris Lattner51285d82008-04-06 23:55:33 +00001324 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1325 if (LHSUnsigned) {
1326 // If the unsigned [LHS] type is larger, return it.
1327 if (LHSRank >= RHSRank)
1328 return 1;
1329
1330 // If the signed type can represent all values of the unsigned type, it
1331 // wins. Because we are dealing with 2's complement and types that are
1332 // powers of two larger than each other, this is always safe.
1333 return -1;
1334 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001335
Chris Lattner51285d82008-04-06 23:55:33 +00001336 // If the unsigned [RHS] type is larger, return it.
1337 if (RHSRank >= LHSRank)
1338 return -1;
1339
1340 // If the signed type can represent all values of the unsigned type, it
1341 // wins. Because we are dealing with 2's complement and types that are
1342 // powers of two larger than each other, this is always safe.
1343 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001344}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001345
1346// getCFConstantStringType - Return the type used for constant CFStrings.
1347QualType ASTContext::getCFConstantStringType() {
1348 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00001349 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001350 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001351 &Idents.get("NSConstantString"));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001352 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001353
1354 // const int *isa;
1355 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001356 // int flags;
1357 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001358 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001359 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001360 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001361 FieldTypes[3] = LongTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001362 // Create fields
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001363 FieldDecl *FieldDecls[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001364
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001365 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001366 FieldDecls[i] = FieldDecl::Create(*this, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001367 FieldTypes[i]);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001368
1369 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
1370 }
1371
1372 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00001373}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001374
Anders Carlssonf58cac72008-08-30 19:34:46 +00001375QualType ASTContext::getObjCFastEnumerationStateType()
1376{
1377 if (!ObjCFastEnumerationStateTypeDecl) {
1378 QualType FieldTypes[] = {
1379 UnsignedLongTy,
1380 getPointerType(ObjCIdType),
1381 getPointerType(UnsignedLongTy),
1382 getConstantArrayType(UnsignedLongTy,
1383 llvm::APInt(32, 5), ArrayType::Normal, 0)
1384 };
1385
1386 FieldDecl *FieldDecls[4];
1387 for (size_t i = 0; i < 4; ++i)
1388 FieldDecls[i] = FieldDecl::Create(*this, SourceLocation(), 0,
1389 FieldTypes[i]);
1390
1391 ObjCFastEnumerationStateTypeDecl =
1392 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001393 &Idents.get("__objcFastEnumerationState"));
Anders Carlssonf58cac72008-08-30 19:34:46 +00001394
1395 ObjCFastEnumerationStateTypeDecl->defineBody(FieldDecls, 4);
1396 }
1397
1398 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
1399}
1400
Anders Carlssone3f02572007-10-29 06:33:42 +00001401// This returns true if a type has been typedefed to BOOL:
1402// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00001403static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00001404 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnercb034cb2007-10-30 20:27:44 +00001405 return !strcmp(TT->getDecl()->getName(), "BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001406
1407 return false;
1408}
1409
Ted Kremenek42730c52008-01-07 19:49:32 +00001410/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001411/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00001412int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001413 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001414
1415 // Make all integer and enum types at least as large as an int
1416 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00001417 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001418 // Treat arrays as pointers, since that's how they're passed in.
1419 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00001420 sz = getTypeSize(VoidPtrTy);
1421 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001422}
1423
Ted Kremenek42730c52008-01-07 19:49:32 +00001424/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001425/// declaration.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001426void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001427 std::string& S)
1428{
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001429 // FIXME: This is not very efficient.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001430 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00001431 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001432 // Encode result type.
Fariborz Jahanian248db262008-01-22 22:44:46 +00001433 getObjCEncodingForType(Decl->getResultType(), S, EncodingRecordTypes);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001434 // Compute size of all parameters.
1435 // Start with computing size of a pointer in number of bytes.
1436 // FIXME: There might(should) be a better way of doing this computation!
1437 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001438 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001439 // The first two arguments (self and _cmd) are pointers; account for
1440 // their size.
1441 int ParmOffset = 2 * PtrSize;
1442 int NumOfParams = Decl->getNumParams();
1443 for (int i = 0; i < NumOfParams; i++) {
1444 QualType PType = Decl->getParamDecl(i)->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001445 int sz = getObjCEncodingTypeSize (PType);
1446 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001447 ParmOffset += sz;
1448 }
1449 S += llvm::utostr(ParmOffset);
1450 S += "@0:";
1451 S += llvm::utostr(PtrSize);
1452
1453 // Argument types.
1454 ParmOffset = 2 * PtrSize;
1455 for (int i = 0; i < NumOfParams; i++) {
1456 QualType PType = Decl->getParamDecl(i)->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001457 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001458 // 'in', 'inout', etc.
Ted Kremenek42730c52008-01-07 19:49:32 +00001459 getObjCEncodingForTypeQualifier(
1460 Decl->getParamDecl(i)->getObjCDeclQualifier(), S);
Fariborz Jahanian248db262008-01-22 22:44:46 +00001461 getObjCEncodingForType(PType, S, EncodingRecordTypes);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001462 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00001463 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001464 }
1465}
1466
Daniel Dunbar698d6f32008-08-28 04:38:10 +00001467/// getObjCEncodingForPropertyDecl - Return the encoded type for this
1468/// method declaration. If non-NULL, Container must be either an
1469/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
1470/// NULL when getting encodings for protocol properties.
1471void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1472 const Decl *Container,
1473 std::string& S)
1474{
1475 // Collect information from the property implementation decl(s).
1476 bool Dynamic = false;
1477 ObjCPropertyImplDecl *SynthesizePID = 0;
1478
1479 // FIXME: Duplicated code due to poor abstraction.
1480 if (Container) {
1481 if (const ObjCCategoryImplDecl *CID =
1482 dyn_cast<ObjCCategoryImplDecl>(Container)) {
1483 for (ObjCCategoryImplDecl::propimpl_iterator
1484 i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) {
1485 ObjCPropertyImplDecl *PID = *i;
1486 if (PID->getPropertyDecl() == PD) {
1487 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
1488 Dynamic = true;
1489 } else {
1490 SynthesizePID = PID;
1491 }
1492 }
1493 }
1494 } else {
1495 const ObjCImplementationDecl *OID = cast<ObjCImplementationDecl>(Container);
1496 for (ObjCCategoryImplDecl::propimpl_iterator
1497 i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) {
1498 ObjCPropertyImplDecl *PID = *i;
1499 if (PID->getPropertyDecl() == PD) {
1500 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
1501 Dynamic = true;
1502 } else {
1503 SynthesizePID = PID;
1504 }
1505 }
1506 }
1507 }
1508 }
1509
1510 // FIXME: This is not very efficient.
1511 S = "T";
1512
1513 // Encode result type.
1514 // FIXME: GCC uses a generating_property_type_encoding mode during
1515 // this part. Investigate.
1516 getObjCEncodingForType(PD->getType(), S, EncodingRecordTypes);
1517
1518 if (PD->isReadOnly()) {
1519 S += ",R";
1520 } else {
1521 switch (PD->getSetterKind()) {
1522 case ObjCPropertyDecl::Assign: break;
1523 case ObjCPropertyDecl::Copy: S += ",C"; break;
1524 case ObjCPropertyDecl::Retain: S += ",&"; break;
1525 }
1526 }
1527
1528 // It really isn't clear at all what this means, since properties
1529 // are "dynamic by default".
1530 if (Dynamic)
1531 S += ",D";
1532
1533 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1534 S += ",G";
1535 S += PD->getGetterName().getName();
1536 }
1537
1538 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1539 S += ",S";
1540 S += PD->getSetterName().getName();
1541 }
1542
1543 if (SynthesizePID) {
1544 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
1545 S += ",V";
1546 S += OID->getName();
1547 }
1548
1549 // FIXME: OBJCGC: weak & strong
1550}
1551
Fariborz Jahanian248db262008-01-22 22:44:46 +00001552void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Chris Lattnera1923f62008-08-04 07:31:14 +00001553 llvm::SmallVector<const RecordType *, 8> &ERType) const {
Anders Carlssone3f02572007-10-29 06:33:42 +00001554 // FIXME: This currently doesn't encode:
1555 // @ An object (whether statically typed or typed id)
1556 // # A class object (Class)
1557 // : A method selector (SEL)
1558 // {name=type...} A structure
1559 // (name=type...) A union
1560 // bnum A bit field of num bits
1561
1562 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001563 char encoding;
1564 switch (BT->getKind()) {
Chris Lattner2bf1d6c2008-04-06 22:05:18 +00001565 default: assert(0 && "Unhandled builtin type kind");
1566 case BuiltinType::Void: encoding = 'v'; break;
1567 case BuiltinType::Bool: encoding = 'B'; break;
Anders Carlsson36f07d82007-10-29 05:01:08 +00001568 case BuiltinType::Char_U:
Chris Lattner2bf1d6c2008-04-06 22:05:18 +00001569 case BuiltinType::UChar: encoding = 'C'; break;
1570 case BuiltinType::UShort: encoding = 'S'; break;
1571 case BuiltinType::UInt: encoding = 'I'; break;
1572 case BuiltinType::ULong: encoding = 'L'; break;
1573 case BuiltinType::ULongLong: encoding = 'Q'; break;
Anders Carlsson36f07d82007-10-29 05:01:08 +00001574 case BuiltinType::Char_S:
Chris Lattner2bf1d6c2008-04-06 22:05:18 +00001575 case BuiltinType::SChar: encoding = 'c'; break;
1576 case BuiltinType::Short: encoding = 's'; break;
1577 case BuiltinType::Int: encoding = 'i'; break;
1578 case BuiltinType::Long: encoding = 'l'; break;
1579 case BuiltinType::LongLong: encoding = 'q'; break;
1580 case BuiltinType::Float: encoding = 'f'; break;
1581 case BuiltinType::Double: encoding = 'd'; break;
1582 case BuiltinType::LongDouble: encoding = 'd'; break;
Anders Carlsson36f07d82007-10-29 05:01:08 +00001583 }
1584
1585 S += encoding;
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001586 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001587 else if (T->isObjCQualifiedIdType()) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001588 // Treat id<P...> same as 'id' for encoding purposes.
Fariborz Jahanian248db262008-01-22 22:44:46 +00001589 return getObjCEncodingForType(getObjCIdType(), S, ERType);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001590
1591 }
1592 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001593 QualType PointeeTy = PT->getPointeeType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001594 if (isObjCIdType(PointeeTy) || PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001595 S += '@';
1596 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00001597 } else if (isObjCClassType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001598 S += '#';
1599 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00001600 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001601 S += ':';
1602 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001603 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00001604
1605 if (PointeeTy->isCharType()) {
1606 // char pointer types should be encoded as '*' unless it is a
1607 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00001608 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001609 S += '*';
1610 return;
1611 }
1612 }
1613
1614 S += '^';
Fariborz Jahanian248db262008-01-22 22:44:46 +00001615 getObjCEncodingForType(PT->getPointeeType(), S, ERType);
Chris Lattnera1923f62008-08-04 07:31:14 +00001616 } else if (const ArrayType *AT =
1617 // Ignore type qualifiers etc.
1618 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001619 S += '[';
1620
1621 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1622 S += llvm::utostr(CAT->getSize().getZExtValue());
1623 else
1624 assert(0 && "Unhandled array type!");
1625
Fariborz Jahanian248db262008-01-22 22:44:46 +00001626 getObjCEncodingForType(AT->getElementType(), S, ERType);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001627 S += ']';
Anders Carlsson5695bb72007-10-30 00:06:20 +00001628 } else if (T->getAsFunctionType()) {
1629 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001630 } else if (const RecordType *RTy = T->getAsRecordType()) {
1631 RecordDecl *RDecl= RTy->getDecl();
Steve Naroff03385292008-08-14 15:00:38 +00001632 // This mimics the behavior in gcc's encode_aggregate_within().
1633 // The idea is to only inline structure definitions for top level pointers
1634 // to structures and embedded structures.
1635 bool inlining = (S.size() == 1 && S[0] == '^' ||
1636 S.size() > 1 && S[S.size()-1] != '^');
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001637 S += '{';
1638 S += RDecl->getName();
Fariborz Jahanian248db262008-01-22 22:44:46 +00001639 bool found = false;
1640 for (unsigned i = 0, e = ERType.size(); i != e; ++i)
1641 if (ERType[i] == RTy) {
1642 found = true;
1643 break;
1644 }
Steve Naroff03385292008-08-14 15:00:38 +00001645 if (!found && inlining) {
Fariborz Jahanian248db262008-01-22 22:44:46 +00001646 ERType.push_back(RTy);
1647 S += '=';
1648 for (int i = 0; i < RDecl->getNumMembers(); i++) {
1649 FieldDecl *field = RDecl->getMember(i);
1650 getObjCEncodingForType(field->getType(), S, ERType);
1651 }
1652 assert(ERType.back() == RTy && "Record Type stack mismatch.");
1653 ERType.pop_back();
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001654 }
1655 S += '}';
Steve Naroff49af3f32007-12-12 22:30:11 +00001656 } else if (T->isEnumeralType()) {
1657 S += 'i';
Anders Carlsson36f07d82007-10-29 05:01:08 +00001658 } else
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001659 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001660}
1661
Ted Kremenek42730c52008-01-07 19:49:32 +00001662void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001663 std::string& S) const {
1664 if (QT & Decl::OBJC_TQ_In)
1665 S += 'n';
1666 if (QT & Decl::OBJC_TQ_Inout)
1667 S += 'N';
1668 if (QT & Decl::OBJC_TQ_Out)
1669 S += 'o';
1670 if (QT & Decl::OBJC_TQ_Bycopy)
1671 S += 'O';
1672 if (QT & Decl::OBJC_TQ_Byref)
1673 S += 'R';
1674 if (QT & Decl::OBJC_TQ_Oneway)
1675 S += 'V';
1676}
1677
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001678void ASTContext::setBuiltinVaListType(QualType T)
1679{
1680 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1681
1682 BuiltinVaListType = T;
1683}
1684
Ted Kremenek42730c52008-01-07 19:49:32 +00001685void ASTContext::setObjCIdType(TypedefDecl *TD)
Steve Naroff9d12c902007-10-15 14:41:52 +00001686{
Ted Kremenek42730c52008-01-07 19:49:32 +00001687 assert(ObjCIdType.isNull() && "'id' type already set!");
Steve Naroff9d12c902007-10-15 14:41:52 +00001688
Ted Kremenek42730c52008-01-07 19:49:32 +00001689 ObjCIdType = getTypedefType(TD);
Steve Naroff9d12c902007-10-15 14:41:52 +00001690
1691 // typedef struct objc_object *id;
1692 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1693 assert(ptr && "'id' incorrectly typed");
1694 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1695 assert(rec && "'id' incorrectly typed");
1696 IdStructType = rec;
1697}
1698
Ted Kremenek42730c52008-01-07 19:49:32 +00001699void ASTContext::setObjCSelType(TypedefDecl *TD)
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001700{
Ted Kremenek42730c52008-01-07 19:49:32 +00001701 assert(ObjCSelType.isNull() && "'SEL' type already set!");
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001702
Ted Kremenek42730c52008-01-07 19:49:32 +00001703 ObjCSelType = getTypedefType(TD);
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001704
1705 // typedef struct objc_selector *SEL;
1706 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1707 assert(ptr && "'SEL' incorrectly typed");
1708 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1709 assert(rec && "'SEL' incorrectly typed");
1710 SelStructType = rec;
1711}
1712
Ted Kremenek42730c52008-01-07 19:49:32 +00001713void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001714{
Ted Kremenek42730c52008-01-07 19:49:32 +00001715 assert(ObjCProtoType.isNull() && "'Protocol' type already set!");
1716 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001717}
1718
Ted Kremenek42730c52008-01-07 19:49:32 +00001719void ASTContext::setObjCClassType(TypedefDecl *TD)
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001720{
Ted Kremenek42730c52008-01-07 19:49:32 +00001721 assert(ObjCClassType.isNull() && "'Class' type already set!");
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001722
Ted Kremenek42730c52008-01-07 19:49:32 +00001723 ObjCClassType = getTypedefType(TD);
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001724
1725 // typedef struct objc_class *Class;
1726 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1727 assert(ptr && "'Class' incorrectly typed");
1728 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1729 assert(rec && "'Class' incorrectly typed");
1730 ClassStructType = rec;
1731}
1732
Ted Kremenek42730c52008-01-07 19:49:32 +00001733void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
1734 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00001735 "'NSConstantString' type already set!");
1736
Ted Kremenek42730c52008-01-07 19:49:32 +00001737 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00001738}
1739
Ted Kremenek118930e2008-07-24 23:58:27 +00001740
1741//===----------------------------------------------------------------------===//
1742// Type Predicates.
1743//===----------------------------------------------------------------------===//
1744
1745/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
1746/// to an object type. This includes "id" and "Class" (two 'special' pointers
1747/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
1748/// ID type).
1749bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
1750 if (Ty->isObjCQualifiedIdType())
1751 return true;
1752
1753 if (!Ty->isPointerType())
1754 return false;
1755
1756 // Check to see if this is 'id' or 'Class', both of which are typedefs for
1757 // pointer types. This looks for the typedef specifically, not for the
1758 // underlying type.
1759 if (Ty == getObjCIdType() || Ty == getObjCClassType())
1760 return true;
1761
1762 // If this a pointer to an interface (e.g. NSString*), it is ok.
1763 return Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType();
1764}
1765
Chris Lattner6ff358b2008-04-07 06:51:04 +00001766//===----------------------------------------------------------------------===//
1767// Type Compatibility Testing
1768//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00001769
Steve Naroff3454b6c2008-09-04 15:10:53 +00001770/// typesAreBlockCompatible - This routine is called when comparing two
Steve Naroff6f373332008-09-04 15:31:07 +00001771/// block types. Types must be strictly compatible here.
Steve Naroff3454b6c2008-09-04 15:10:53 +00001772bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
1773 if (lhs.getCVRQualifiers() != rhs.getCVRQualifiers())
1774 return false;
1775
1776 QualType lcanon = getCanonicalType(lhs);
1777 QualType rcanon = getCanonicalType(rhs);
1778
1779 // If two types are identical, they are are compatible
1780 if (lcanon == rcanon)
1781 return true;
1782 if (isa<FunctionType>(lcanon) && isa<FunctionType>(rcanon)) {
1783 const FunctionType *lbase = cast<FunctionType>(lcanon);
1784 const FunctionType *rbase = cast<FunctionType>(rcanon);
1785
1786 // First check the return types.
1787 if (!typesAreBlockCompatible(lbase->getResultType(),rbase->getResultType()))
1788 return false;
1789
1790 // Return types matched, now check the argument types.
1791 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1792 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1793
1794 if (lproto && rproto) { // two C99 style function prototypes
1795 unsigned lproto_nargs = lproto->getNumArgs();
1796 unsigned rproto_nargs = rproto->getNumArgs();
1797
1798 if (lproto_nargs != rproto_nargs)
1799 return false;
1800
1801 if (lproto->isVariadic() || rproto->isVariadic())
1802 return false;
1803
1804 // The use of ellipsis agree...now check the argument types.
1805 for (unsigned i = 0; i < lproto_nargs; i++)
1806 if (!typesAreBlockCompatible(lproto->getArgType(i),
1807 rproto->getArgType(i)))
1808 return false;
1809 return true;
1810 }
1811 return (!lproto && !rproto); // two K&R style function decls match.
1812 }
1813 return false;
1814}
1815
Chris Lattner6ff358b2008-04-07 06:51:04 +00001816/// areCompatVectorTypes - Return true if the two specified vector types are
1817/// compatible.
1818static bool areCompatVectorTypes(const VectorType *LHS,
1819 const VectorType *RHS) {
1820 assert(LHS->isCanonical() && RHS->isCanonical());
1821 return LHS->getElementType() == RHS->getElementType() &&
1822 LHS->getNumElements() == RHS->getNumElements();
1823}
1824
Eli Friedman0d9549b2008-08-22 00:56:42 +00001825/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ff358b2008-04-07 06:51:04 +00001826/// compatible for assignment from RHS to LHS. This handles validation of any
1827/// protocol qualifiers on the LHS or RHS.
1828///
Eli Friedman0d9549b2008-08-22 00:56:42 +00001829bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
1830 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00001831 // Verify that the base decls are compatible: the RHS must be a subclass of
1832 // the LHS.
1833 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
1834 return false;
1835
1836 // RHS must have a superset of the protocols in the LHS. If the LHS is not
1837 // protocol qualified at all, then we are good.
1838 if (!isa<ObjCQualifiedInterfaceType>(LHS))
1839 return true;
1840
1841 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
1842 // isn't a superset.
1843 if (!isa<ObjCQualifiedInterfaceType>(RHS))
1844 return true; // FIXME: should return false!
1845
1846 // Finally, we must have two protocol-qualified interfaces.
1847 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
1848 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
1849 ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin();
1850 ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end();
1851 ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin();
1852 ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end();
1853
1854 // All protocols in LHS must have a presence in RHS. Since the protocol lists
1855 // are both sorted alphabetically and have no duplicates, we can scan RHS and
1856 // LHS in a single parallel scan until we run out of elements in LHS.
1857 assert(LHSPI != LHSPE && "Empty LHS protocol list?");
1858 ObjCProtocolDecl *LHSProto = *LHSPI;
1859
1860 while (RHSPI != RHSPE) {
1861 ObjCProtocolDecl *RHSProto = *RHSPI++;
1862 // If the RHS has a protocol that the LHS doesn't, ignore it.
1863 if (RHSProto != LHSProto)
1864 continue;
1865
1866 // Otherwise, the RHS does have this element.
1867 ++LHSPI;
1868 if (LHSPI == LHSPE)
1869 return true; // All protocols in LHS exist in RHS.
1870
1871 LHSProto = *LHSPI;
1872 }
1873
1874 // If we got here, we didn't find one of the LHS's protocols in the RHS list.
1875 return false;
1876}
1877
Steve Naroff85f0dc52007-10-15 20:41:53 +00001878/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1879/// both shall have the identically qualified version of a compatible type.
1880/// C99 6.2.7p1: Two types have compatible types if their types are the
1881/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman0d9549b2008-08-22 00:56:42 +00001882bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
1883 return !mergeTypes(LHS, RHS).isNull();
1884}
1885
1886QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
1887 const FunctionType *lbase = lhs->getAsFunctionType();
1888 const FunctionType *rbase = rhs->getAsFunctionType();
1889 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1890 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1891 bool allLTypes = true;
1892 bool allRTypes = true;
1893
1894 // Check return type
1895 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
1896 if (retType.isNull()) return QualType();
1897 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) allLTypes = false;
1898 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) allRTypes = false;
1899
1900 if (lproto && rproto) { // two C99 style function prototypes
1901 unsigned lproto_nargs = lproto->getNumArgs();
1902 unsigned rproto_nargs = rproto->getNumArgs();
1903
1904 // Compatible functions must have the same number of arguments
1905 if (lproto_nargs != rproto_nargs)
1906 return QualType();
1907
1908 // Variadic and non-variadic functions aren't compatible
1909 if (lproto->isVariadic() != rproto->isVariadic())
1910 return QualType();
1911
1912 // Check argument compatibility
1913 llvm::SmallVector<QualType, 10> types;
1914 for (unsigned i = 0; i < lproto_nargs; i++) {
1915 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
1916 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
1917 QualType argtype = mergeTypes(largtype, rargtype);
1918 if (argtype.isNull()) return QualType();
1919 types.push_back(argtype);
1920 if (getCanonicalType(argtype) != getCanonicalType(largtype)) allLTypes = false;
1921 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) allRTypes = false;
1922 }
1923 if (allLTypes) return lhs;
1924 if (allRTypes) return rhs;
1925 return getFunctionType(retType, types.begin(), types.size(),
1926 lproto->isVariadic());
1927 }
1928
1929 if (lproto) allRTypes = false;
1930 if (rproto) allLTypes = false;
1931
1932 const FunctionTypeProto *proto = lproto ? lproto : rproto;
1933 if (proto) {
1934 if (proto->isVariadic()) return QualType();
1935 // Check that the types are compatible with the types that
1936 // would result from default argument promotions (C99 6.7.5.3p15).
1937 // The only types actually affected are promotable integer
1938 // types and floats, which would be passed as a different
1939 // type depending on whether the prototype is visible.
1940 unsigned proto_nargs = proto->getNumArgs();
1941 for (unsigned i = 0; i < proto_nargs; ++i) {
1942 QualType argTy = proto->getArgType(i);
1943 if (argTy->isPromotableIntegerType() ||
1944 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
1945 return QualType();
1946 }
1947
1948 if (allLTypes) return lhs;
1949 if (allRTypes) return rhs;
1950 return getFunctionType(retType, proto->arg_type_begin(),
1951 proto->getNumArgs(), lproto->isVariadic());
1952 }
1953
1954 if (allLTypes) return lhs;
1955 if (allRTypes) return rhs;
1956 return getFunctionTypeNoProto(retType);
1957}
1958
1959QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling6a9d8542007-12-03 07:33:35 +00001960 // C++ [expr]: If an expression initially has the type "reference to T", the
1961 // type is adjusted to "T" prior to any further analysis, the expression
1962 // designates the object or function denoted by the reference, and the
1963 // expression is an lvalue.
Eli Friedman0d9549b2008-08-22 00:56:42 +00001964 // FIXME: C++ shouldn't be going through here! The rules are different
1965 // enough that they should be handled separately.
1966 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00001967 LHS = RT->getPointeeType();
Eli Friedman0d9549b2008-08-22 00:56:42 +00001968 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00001969 RHS = RT->getPointeeType();
Chris Lattnerd47d6042008-04-07 05:37:56 +00001970
Eli Friedman0d9549b2008-08-22 00:56:42 +00001971 QualType LHSCan = getCanonicalType(LHS),
1972 RHSCan = getCanonicalType(RHS);
1973
1974 // If two types are identical, they are compatible.
1975 if (LHSCan == RHSCan)
1976 return LHS;
1977
1978 // If the qualifiers are different, the types aren't compatible
1979 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers() ||
1980 LHSCan.getAddressSpace() != RHSCan.getAddressSpace())
1981 return QualType();
1982
1983 Type::TypeClass LHSClass = LHSCan->getTypeClass();
1984 Type::TypeClass RHSClass = RHSCan->getTypeClass();
1985
Chris Lattnerc38d4522008-01-14 05:45:46 +00001986 // We want to consider the two function types to be the same for these
1987 // comparisons, just force one to the other.
1988 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
1989 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00001990
1991 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00001992 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
1993 LHSClass = Type::ConstantArray;
1994 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
1995 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00001996
Nate Begemanaf6ed502008-04-18 23:10:10 +00001997 // Canonicalize ExtVector -> Vector.
1998 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
1999 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00002000
Chris Lattner7cdcb252008-04-07 06:38:24 +00002001 // Consider qualified interfaces and interfaces the same.
2002 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
2003 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002004
Chris Lattnerb5709e22008-04-07 05:43:21 +00002005 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00002006 if (LHSClass != RHSClass) {
Steve Naroff44549772008-06-04 15:07:33 +00002007 // ID is compatible with all qualified id types.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002008 if (LHS->isObjCQualifiedIdType()) {
Steve Naroff44549772008-06-04 15:07:33 +00002009 if (const PointerType *PT = RHS->getAsPointerType())
Eli Friedman0d9549b2008-08-22 00:56:42 +00002010 if (isObjCIdType(PT->getPointeeType()))
2011 return LHS;
Steve Naroff44549772008-06-04 15:07:33 +00002012 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002013 if (RHS->isObjCQualifiedIdType()) {
Steve Naroff44549772008-06-04 15:07:33 +00002014 if (const PointerType *PT = LHS->getAsPointerType())
Eli Friedman0d9549b2008-08-22 00:56:42 +00002015 if (isObjCIdType(PT->getPointeeType()))
2016 return RHS;
2017 }
2018
Chris Lattnerc38d4522008-01-14 05:45:46 +00002019 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
2020 // a signed integer type, or an unsigned integer type.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002021 if (const EnumType* ETy = LHS->getAsEnumType()) {
2022 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
2023 return RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00002024 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002025 if (const EnumType* ETy = RHS->getAsEnumType()) {
2026 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
2027 return LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00002028 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002029
Eli Friedman0d9549b2008-08-22 00:56:42 +00002030 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00002031 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002032
Steve Naroffc88babe2008-01-09 22:43:08 +00002033 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00002034 switch (LHSClass) {
Chris Lattnerc38d4522008-01-14 05:45:46 +00002035 case Type::Pointer:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002036 {
2037 // Merge two pointer types, while trying to preserve typedef info
2038 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
2039 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
2040 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2041 if (ResultType.isNull()) return QualType();
Eli Friedmanc91a3f32008-08-22 01:48:21 +00002042 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) return LHS;
2043 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002044 return getPointerType(ResultType);
2045 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002046 case Type::ConstantArray:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002047 {
2048 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
2049 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
2050 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
2051 return QualType();
2052
2053 QualType LHSElem = getAsArrayType(LHS)->getElementType();
2054 QualType RHSElem = getAsArrayType(RHS)->getElementType();
2055 QualType ResultType = mergeTypes(LHSElem, RHSElem);
2056 if (ResultType.isNull()) return QualType();
Eli Friedmanc91a3f32008-08-22 01:48:21 +00002057 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
2058 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
2059 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
2060 ArrayType::ArraySizeModifier(), 0);
2061 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
2062 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002063 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
2064 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Eli Friedmanc91a3f32008-08-22 01:48:21 +00002065 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
2066 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002067 if (LVAT) {
2068 // FIXME: This isn't correct! But tricky to implement because
2069 // the array's size has to be the size of LHS, but the type
2070 // has to be different.
2071 return LHS;
2072 }
2073 if (RVAT) {
2074 // FIXME: This isn't correct! But tricky to implement because
2075 // the array's size has to be the size of RHS, but the type
2076 // has to be different.
2077 return RHS;
2078 }
Eli Friedmanc91a3f32008-08-22 01:48:21 +00002079 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
2080 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002081 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(), 0);
2082 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002083 case Type::FunctionNoProto:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002084 return mergeFunctionTypes(LHS, RHS);
2085 case Type::Tagged:
2086 {
2087 // FIXME: Why are these compatible?
2088 if (isObjCIdType(LHS) && isObjCClassType(RHS)) return LHS;
2089 if (isObjCClassType(LHS) && isObjCIdType(RHS)) return LHS;
2090 return QualType();
2091 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002092 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00002093 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002094 return QualType();
Chris Lattnerd1240fa2008-04-07 05:55:38 +00002095 case Type::Vector:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002096 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
2097 return LHS;
Chris Lattnerc38d4522008-01-14 05:45:46 +00002098 case Type::ObjCInterface:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002099 {
2100 // Distinct ObjC interfaces are not compatible; see canAssignObjCInterfaces
2101 // for checking assignment/comparison safety
2102 return QualType();
2103 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002104 default:
2105 assert(0 && "unexpected type");
Eli Friedman0d9549b2008-08-22 00:56:42 +00002106 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00002107 }
Steve Naroff85f0dc52007-10-15 20:41:53 +00002108}
Ted Kremenek738e6c02007-10-31 17:10:13 +00002109
Chris Lattner1d78a862008-04-07 07:01:58 +00002110//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00002111// Integer Predicates
2112//===----------------------------------------------------------------------===//
2113unsigned ASTContext::getIntWidth(QualType T) {
2114 if (T == BoolTy)
2115 return 1;
2116 // At the moment, only bool has padding bits
2117 return (unsigned)getTypeSize(T);
2118}
2119
2120QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
2121 assert(T->isSignedIntegerType() && "Unexpected type");
2122 if (const EnumType* ETy = T->getAsEnumType())
2123 T = ETy->getDecl()->getIntegerType();
2124 const BuiltinType* BTy = T->getAsBuiltinType();
2125 assert (BTy && "Unexpected signed integer type");
2126 switch (BTy->getKind()) {
2127 case BuiltinType::Char_S:
2128 case BuiltinType::SChar:
2129 return UnsignedCharTy;
2130 case BuiltinType::Short:
2131 return UnsignedShortTy;
2132 case BuiltinType::Int:
2133 return UnsignedIntTy;
2134 case BuiltinType::Long:
2135 return UnsignedLongTy;
2136 case BuiltinType::LongLong:
2137 return UnsignedLongLongTy;
2138 default:
2139 assert(0 && "Unexpected signed integer type");
2140 return QualType();
2141 }
2142}
2143
2144
2145//===----------------------------------------------------------------------===//
Chris Lattner1d78a862008-04-07 07:01:58 +00002146// Serialization Support
2147//===----------------------------------------------------------------------===//
2148
Ted Kremenek738e6c02007-10-31 17:10:13 +00002149/// Emit - Serialize an ASTContext object to Bitcode.
2150void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremenek842126e2008-06-04 15:55:15 +00002151 S.Emit(LangOpts);
Ted Kremenek9af4d5c2007-10-31 20:00:03 +00002152 S.EmitRef(SourceMgr);
2153 S.EmitRef(Target);
2154 S.EmitRef(Idents);
2155 S.EmitRef(Selectors);
Ted Kremenek738e6c02007-10-31 17:10:13 +00002156
Ted Kremenek68228a92007-10-31 22:44:07 +00002157 // Emit the size of the type vector so that we can reserve that size
2158 // when we reconstitute the ASTContext object.
Ted Kremenek0199d9f2007-11-06 22:26:16 +00002159 S.EmitInt(Types.size());
2160
Ted Kremenek034a78c2007-11-13 22:02:55 +00002161 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
2162 I!=E;++I)
2163 (*I)->Emit(S);
Ted Kremenek0199d9f2007-11-06 22:26:16 +00002164
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002165 S.EmitOwnedPtr(TUDecl);
2166
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00002167 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
Ted Kremenek738e6c02007-10-31 17:10:13 +00002168}
2169
Ted Kremenekacba3612007-11-13 00:25:37 +00002170ASTContext* ASTContext::Create(llvm::Deserializer& D) {
Ted Kremenek842126e2008-06-04 15:55:15 +00002171
2172 // Read the language options.
2173 LangOptions LOpts;
2174 LOpts.Read(D);
2175
Ted Kremenek68228a92007-10-31 22:44:07 +00002176 SourceManager &SM = D.ReadRef<SourceManager>();
2177 TargetInfo &t = D.ReadRef<TargetInfo>();
2178 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
2179 SelectorTable &sels = D.ReadRef<SelectorTable>();
Chris Lattnereee57c02008-04-04 06:12:32 +00002180
Ted Kremenek68228a92007-10-31 22:44:07 +00002181 unsigned size_reserve = D.ReadInt();
2182
Ted Kremenek842126e2008-06-04 15:55:15 +00002183 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels, size_reserve);
Ted Kremenek68228a92007-10-31 22:44:07 +00002184
Ted Kremenek034a78c2007-11-13 22:02:55 +00002185 for (unsigned i = 0; i < size_reserve; ++i)
2186 Type::Create(*A,i,D);
Chris Lattnereee57c02008-04-04 06:12:32 +00002187
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002188 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
2189
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00002190 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
Ted Kremenek68228a92007-10-31 22:44:07 +00002191
2192 return A;
2193}