blob: f47855a5c6ed6560ad2aaf163a15112d0c053b46 [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"
15#include "clang/AST/Decl.h"
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff3fafa102007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/Basic/TargetInfo.h"
19#include "llvm/ADT/SmallVector.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
30ASTContext::~ASTContext() {
31 // Deallocate all the types.
32 while (!Types.empty()) {
Ted Kremenekdb4d5972008-05-21 16:38:54 +000033 Types.back()->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000034 Types.pop_back();
35 }
Eli Friedman65489b72008-05-27 03:08:09 +000036
37 TUDecl->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000038}
39
40void ASTContext::PrintStats() const {
41 fprintf(stderr, "*** AST Context Stats:\n");
42 fprintf(stderr, " %d types total.\n", (int)Types.size());
43 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
44 unsigned NumVector = 0, NumComplex = 0;
45 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
46
47 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000048 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
49 unsigned NumObjCQualifiedIds = 0;
Steve Naroffe0430632008-05-21 15:59:22 +000050 unsigned NumTypeOfTypes = 0, NumTypeOfExprs = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000051
52 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
53 Type *T = Types[i];
54 if (isa<BuiltinType>(T))
55 ++NumBuiltin;
56 else if (isa<PointerType>(T))
57 ++NumPointer;
58 else if (isa<ReferenceType>(T))
59 ++NumReference;
60 else if (isa<ComplexType>(T))
61 ++NumComplex;
62 else if (isa<ArrayType>(T))
63 ++NumArray;
64 else if (isa<VectorType>(T))
65 ++NumVector;
66 else if (isa<FunctionTypeNoProto>(T))
67 ++NumFunctionNP;
68 else if (isa<FunctionTypeProto>(T))
69 ++NumFunctionP;
70 else if (isa<TypedefType>(T))
71 ++NumTypeName;
72 else if (TagType *TT = dyn_cast<TagType>(T)) {
73 ++NumTagged;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +000074 switch (TT->getDecl()->getTagKind()) {
Chris Lattner4b009652007-07-25 00:24:17 +000075 default: assert(0 && "Unknown tagged type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +000076 case TagDecl::TK_struct: ++NumTagStruct; break;
77 case TagDecl::TK_union: ++NumTagUnion; break;
78 case TagDecl::TK_class: ++NumTagClass; break;
79 case TagDecl::TK_enum: ++NumTagEnum; break;
Chris Lattner4b009652007-07-25 00:24:17 +000080 }
Ted Kremenek42730c52008-01-07 19:49:32 +000081 } else if (isa<ObjCInterfaceType>(T))
82 ++NumObjCInterfaces;
83 else if (isa<ObjCQualifiedInterfaceType>(T))
84 ++NumObjCQualifiedInterfaces;
85 else if (isa<ObjCQualifiedIdType>(T))
86 ++NumObjCQualifiedIds;
Steve Naroffe0430632008-05-21 15:59:22 +000087 else if (isa<TypeOfType>(T))
88 ++NumTypeOfTypes;
89 else if (isa<TypeOfExpr>(T))
90 ++NumTypeOfExprs;
Steve Naroff948fd372007-09-17 14:16:13 +000091 else {
Chris Lattner8a35b462007-12-12 06:43:05 +000092 QualType(T, 0).dump();
Chris Lattner4b009652007-07-25 00:24:17 +000093 assert(0 && "Unknown type!");
94 }
95 }
96
97 fprintf(stderr, " %d builtin types\n", NumBuiltin);
98 fprintf(stderr, " %d pointer types\n", NumPointer);
99 fprintf(stderr, " %d reference types\n", NumReference);
100 fprintf(stderr, " %d complex types\n", NumComplex);
101 fprintf(stderr, " %d array types\n", NumArray);
102 fprintf(stderr, " %d vector types\n", NumVector);
103 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
104 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
105 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
106 fprintf(stderr, " %d tagged types\n", NumTagged);
107 fprintf(stderr, " %d struct types\n", NumTagStruct);
108 fprintf(stderr, " %d union types\n", NumTagUnion);
109 fprintf(stderr, " %d class types\n", NumTagClass);
110 fprintf(stderr, " %d enum types\n", NumTagEnum);
Ted Kremenek42730c52008-01-07 19:49:32 +0000111 fprintf(stderr, " %d interface types\n", NumObjCInterfaces);
Chris Lattner8a35b462007-12-12 06:43:05 +0000112 fprintf(stderr, " %d protocol qualified interface types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000113 NumObjCQualifiedInterfaces);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000114 fprintf(stderr, " %d protocol qualified id types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000115 NumObjCQualifiedIds);
Steve Naroffe0430632008-05-21 15:59:22 +0000116 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes);
117 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprs);
118
Chris Lattner4b009652007-07-25 00:24:17 +0000119 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
120 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
121 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
122 NumFunctionP*sizeof(FunctionTypeProto)+
123 NumFunctionNP*sizeof(FunctionTypeNoProto)+
Steve Naroffe0430632008-05-21 15:59:22 +0000124 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
125 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprs*sizeof(TypeOfExpr)));
Chris Lattner4b009652007-07-25 00:24:17 +0000126}
127
128
129void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
130 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr());
131}
132
Chris Lattner4b009652007-07-25 00:24:17 +0000133void ASTContext::InitBuiltinTypes() {
134 assert(VoidTy.isNull() && "Context reinitialized?");
135
136 // C99 6.2.5p19.
137 InitBuiltinType(VoidTy, BuiltinType::Void);
138
139 // C99 6.2.5p2.
140 InitBuiltinType(BoolTy, BuiltinType::Bool);
141 // C99 6.2.5p3.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000142 if (Target.isCharSigned())
Chris Lattner4b009652007-07-25 00:24:17 +0000143 InitBuiltinType(CharTy, BuiltinType::Char_S);
144 else
145 InitBuiltinType(CharTy, BuiltinType::Char_U);
146 // C99 6.2.5p4.
147 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
148 InitBuiltinType(ShortTy, BuiltinType::Short);
149 InitBuiltinType(IntTy, BuiltinType::Int);
150 InitBuiltinType(LongTy, BuiltinType::Long);
151 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
152
153 // C99 6.2.5p6.
154 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
155 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
156 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
157 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
158 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
159
160 // C99 6.2.5p10.
161 InitBuiltinType(FloatTy, BuiltinType::Float);
162 InitBuiltinType(DoubleTy, BuiltinType::Double);
163 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
164
165 // C99 6.2.5p11.
166 FloatComplexTy = getComplexType(FloatTy);
167 DoubleComplexTy = getComplexType(DoubleTy);
168 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Steve Naroff9d12c902007-10-15 14:41:52 +0000169
170 BuiltinVaListType = QualType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000171 ObjCIdType = QualType();
Steve Naroff9d12c902007-10-15 14:41:52 +0000172 IdStructType = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000173 ObjCClassType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000174 ClassStructType = 0;
175
Ted Kremenek42730c52008-01-07 19:49:32 +0000176 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000177
178 // void * type
179 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000180}
181
182//===----------------------------------------------------------------------===//
183// Type Sizing and Analysis
184//===----------------------------------------------------------------------===//
185
Chris Lattner2a674dc2008-06-30 18:32:54 +0000186/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
187/// scalar floating point type.
188const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
189 const BuiltinType *BT = T->getAsBuiltinType();
190 assert(BT && "Not a floating point type!");
191 switch (BT->getKind()) {
192 default: assert(0 && "Not a floating point type!");
193 case BuiltinType::Float: return Target.getFloatFormat();
194 case BuiltinType::Double: return Target.getDoubleFormat();
195 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
196 }
197}
198
199
Chris Lattner4b009652007-07-25 00:24:17 +0000200/// getTypeSize - Return the size of the specified type, in bits. This method
201/// does not work on incomplete types.
202std::pair<uint64_t, unsigned>
Chris Lattner8cd0e932008-03-05 18:54:05 +0000203ASTContext::getTypeInfo(QualType T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000204 T = getCanonicalType(T);
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000205 uint64_t Width;
Chris Lattner4b009652007-07-25 00:24:17 +0000206 unsigned Align;
207 switch (T->getTypeClass()) {
208 case Type::TypeName: assert(0 && "Not a canonical type!");
209 case Type::FunctionNoProto:
210 case Type::FunctionProto:
211 default:
212 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000213 case Type::VariableArray:
214 assert(0 && "VLAs not implemented yet!");
215 case Type::ConstantArray: {
216 ConstantArrayType *CAT = cast<ConstantArrayType>(T);
217
Chris Lattner8cd0e932008-03-05 18:54:05 +0000218 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000219 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000220 Align = EltInfo.second;
221 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000222 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000223 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000224 case Type::Vector: {
225 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000226 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000227 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000228 // FIXME: This isn't right for unusual vectors
229 Align = Width;
Chris Lattner4b009652007-07-25 00:24:17 +0000230 break;
231 }
232
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000233 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000234 switch (cast<BuiltinType>(T)->getKind()) {
235 default: assert(0 && "Unknown builtin type!");
236 case BuiltinType::Void:
237 assert(0 && "Incomplete types have no size!");
Chris Lattnerb66237b2007-12-19 19:23:28 +0000238 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000239 Width = Target.getBoolWidth();
240 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000241 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000242 case BuiltinType::Char_S:
243 case BuiltinType::Char_U:
244 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000245 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000246 Width = Target.getCharWidth();
247 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000248 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000249 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000250 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000251 Width = Target.getShortWidth();
252 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000253 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000254 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000255 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000256 Width = Target.getIntWidth();
257 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000258 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000259 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000260 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000261 Width = Target.getLongWidth();
262 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000263 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000264 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000265 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000266 Width = Target.getLongLongWidth();
267 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000268 break;
269 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000270 Width = Target.getFloatWidth();
271 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000272 break;
273 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000274 Width = Target.getDoubleWidth();
275 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000276 break;
277 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000278 Width = Target.getLongDoubleWidth();
279 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000280 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000281 }
282 break;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000283 case Type::ASQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000284 // FIXME: Pointers into different addr spaces could have different sizes and
285 // alignment requirements: getPointerInfo should take an AddrSpace.
286 return getTypeInfo(QualType(cast<ASQualType>(T)->getBaseType(), 0));
Ted Kremenek42730c52008-01-07 19:49:32 +0000287 case Type::ObjCQualifiedId:
Chris Lattner1d78a862008-04-07 07:01:58 +0000288 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000289 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000290 break;
Chris Lattner461a6c52008-03-08 08:34:58 +0000291 case Type::Pointer: {
292 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000293 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000294 Align = Target.getPointerAlign(AS);
295 break;
296 }
Chris Lattner4b009652007-07-25 00:24:17 +0000297 case Type::Reference:
298 // "When applied to a reference or a reference type, the result is the size
299 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000300 // FIXME: This is wrong for struct layout: a reference in a struct has
301 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000302 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Chris Lattner4b009652007-07-25 00:24:17 +0000303
304 case Type::Complex: {
305 // Complex types have the same alignment as their elements, but twice the
306 // size.
307 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000308 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000309 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000310 Align = EltInfo.second;
311 break;
312 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000313 case Type::ObjCInterface: {
314 ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
315 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
316 Width = Layout.getSize();
317 Align = Layout.getAlignment();
318 break;
319 }
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000320 case Type::Tagged: {
321 if (EnumType *ET = dyn_cast<EnumType>(cast<TagType>(T)))
322 return getTypeInfo(ET->getDecl()->getIntegerType());
323
324 RecordType *RT = cast<RecordType>(T);
325 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
326 Width = Layout.getSize();
327 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000328 break;
329 }
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000330 }
Chris Lattner4b009652007-07-25 00:24:17 +0000331
332 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000333 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000334}
335
Devang Patelbfe323c2008-06-04 21:22:16 +0000336/// LayoutField - Field layout.
337void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
338 bool IsUnion, bool StructIsPacked,
339 ASTContext &Context) {
340 bool FieldIsPacked = StructIsPacked || FD->getAttr<PackedAttr>();
341 uint64_t FieldOffset = IsUnion ? 0 : Size;
342 uint64_t FieldSize;
343 unsigned FieldAlign;
344
345 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
346 // TODO: Need to check this algorithm on other targets!
347 // (tested on Linux-X86)
348 llvm::APSInt I(32);
349 bool BitWidthIsICE =
350 BitWidthExpr->isIntegerConstantExpr(I, Context);
351 assert (BitWidthIsICE && "Invalid BitField size expression");
352 FieldSize = I.getZExtValue();
353
354 std::pair<uint64_t, unsigned> FieldInfo =
355 Context.getTypeInfo(FD->getType());
356 uint64_t TypeSize = FieldInfo.first;
357
358 FieldAlign = FieldInfo.second;
359 if (FieldIsPacked)
360 FieldAlign = 1;
361 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
362 FieldAlign = std::max(FieldAlign, AA->getAlignment());
363
364 // Check if we need to add padding to give the field the correct
365 // alignment.
366 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
367 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
368
369 // Padding members don't affect overall alignment
370 if (!FD->getIdentifier())
371 FieldAlign = 1;
372 } else {
373 if (FD->getType()->isIncompleteType()) {
374 // This must be a flexible array member; we can't directly
375 // query getTypeInfo about these, so we figure it out here.
376 // Flexible array members don't have any size, but they
377 // have to be aligned appropriately for their element type.
378 FieldSize = 0;
Chris Lattnera1923f62008-08-04 07:31:14 +0000379 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patelbfe323c2008-06-04 21:22:16 +0000380 FieldAlign = Context.getTypeAlign(ATy->getElementType());
381 } else {
382 std::pair<uint64_t, unsigned> FieldInfo =
383 Context.getTypeInfo(FD->getType());
384 FieldSize = FieldInfo.first;
385 FieldAlign = FieldInfo.second;
386 }
387
388 if (FieldIsPacked)
389 FieldAlign = 8;
390 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
391 FieldAlign = std::max(FieldAlign, AA->getAlignment());
392
393 // Round up the current record size to the field's alignment boundary.
394 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
395 }
396
397 // Place this field at the current location.
398 FieldOffsets[FieldNo] = FieldOffset;
399
400 // Reserve space for this field.
401 if (IsUnion) {
402 Size = std::max(Size, FieldSize);
403 } else {
404 Size = FieldOffset + FieldSize;
405 }
406
407 // Remember max struct/class alignment.
408 Alignment = std::max(Alignment, FieldAlign);
409}
410
Devang Patel4b6bf702008-06-04 21:54:36 +0000411
412/// getASTObjcInterfaceLayout - Get or compute information about the layout of the
413/// specified Objective C, which indicates its size and ivar
414/// position information.
415const ASTRecordLayout &
416ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
417 // Look up this layout, if already laid out, return what we have.
418 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
419 if (Entry) return *Entry;
420
421 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
422 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
Devang Patel8682d882008-06-06 02:14:01 +0000423 ASTRecordLayout *NewEntry = NULL;
424 unsigned FieldCount = D->ivar_size();
425 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
426 FieldCount++;
427 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
428 unsigned Alignment = SL.getAlignment();
429 uint64_t Size = SL.getSize();
430 NewEntry = new ASTRecordLayout(Size, Alignment);
431 NewEntry->InitializeLayout(FieldCount);
432 NewEntry->SetFieldOffset(0, 0); // Super class is at the beginning of the layout.
433 } else {
434 NewEntry = new ASTRecordLayout();
435 NewEntry->InitializeLayout(FieldCount);
436 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000437 Entry = NewEntry;
438
Devang Patel4b6bf702008-06-04 21:54:36 +0000439 bool IsPacked = D->getAttr<PackedAttr>();
440
441 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
442 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
443 AA->getAlignment()));
444
445 // Layout each ivar sequentially.
446 unsigned i = 0;
447 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
448 IVE = D->ivar_end(); IVI != IVE; ++IVI) {
449 const ObjCIvarDecl* Ivar = (*IVI);
450 NewEntry->LayoutField(Ivar, i++, false, IsPacked, *this);
451 }
452
453 // Finally, round the size of the total struct up to the alignment of the
454 // struct itself.
455 NewEntry->FinalizeLayout();
456 return *NewEntry;
457}
458
Devang Patel7a78e432007-11-01 19:11:01 +0000459/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000460/// specified record (struct/union/class), which indicates its size and field
461/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000462const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000463 assert(D->isDefinition() && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000464
Chris Lattner4b009652007-07-25 00:24:17 +0000465 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000466 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000467 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000468
Devang Patel7a78e432007-11-01 19:11:01 +0000469 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
470 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
471 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000472 Entry = NewEntry;
Eli Friedman5949a022008-05-30 09:31:38 +0000473
Devang Patelbfe323c2008-06-04 21:22:16 +0000474 NewEntry->InitializeLayout(D->getNumMembers());
Eli Friedman5949a022008-05-30 09:31:38 +0000475 bool StructIsPacked = D->getAttr<PackedAttr>();
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000476 bool IsUnion = D->isUnion();
Chris Lattner4b009652007-07-25 00:24:17 +0000477
Eli Friedman5949a022008-05-30 09:31:38 +0000478 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patelbfe323c2008-06-04 21:22:16 +0000479 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
480 AA->getAlignment()));
Anders Carlsson058237f2008-02-18 07:13:09 +0000481
Eli Friedman5949a022008-05-30 09:31:38 +0000482 // Layout each field, for now, just sequentially, respecting alignment. In
483 // the future, this will need to be tweakable by targets.
484 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
485 const FieldDecl *FD = D->getMember(i);
Devang Patelbfe323c2008-06-04 21:22:16 +0000486 NewEntry->LayoutField(FD, i, IsUnion, StructIsPacked, *this);
Chris Lattner4b009652007-07-25 00:24:17 +0000487 }
Eli Friedman5949a022008-05-30 09:31:38 +0000488
489 // Finally, round the size of the total struct up to the alignment of the
490 // struct itself.
Devang Patelbfe323c2008-06-04 21:22:16 +0000491 NewEntry->FinalizeLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000492 return *NewEntry;
493}
494
Chris Lattner4b009652007-07-25 00:24:17 +0000495//===----------------------------------------------------------------------===//
496// Type creation/memoization methods
497//===----------------------------------------------------------------------===//
498
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000499QualType ASTContext::getASQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000500 QualType CanT = getCanonicalType(T);
501 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000502 return T;
503
504 // Type's cannot have multiple ASQuals, therefore we know we only have to deal
505 // with CVR qualifiers from here on out.
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000506 assert(CanT.getAddressSpace() == 0 &&
Chris Lattner35fef522008-02-20 20:55:12 +0000507 "Type is already address space qualified");
508
509 // Check if we've already instantiated an address space qual'd type of this
510 // type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000511 llvm::FoldingSetNodeID ID;
Chris Lattner35fef522008-02-20 20:55:12 +0000512 ASQualType::Profile(ID, T.getTypePtr(), AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000513 void *InsertPos = 0;
514 if (ASQualType *ASQy = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos))
515 return QualType(ASQy, 0);
516
517 // If the base type isn't canonical, this won't be a canonical type either,
518 // so fill in the canonical type field.
519 QualType Canonical;
520 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000521 Canonical = getASQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000522
523 // Get the new insert position for the node we care about.
524 ASQualType *NewIP = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos);
525 assert(NewIP == 0 && "Shouldn't be in the map!");
526 }
Chris Lattner35fef522008-02-20 20:55:12 +0000527 ASQualType *New = new ASQualType(T.getTypePtr(), Canonical, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000528 ASQualTypes.InsertNode(New, InsertPos);
529 Types.push_back(New);
Chris Lattner35fef522008-02-20 20:55:12 +0000530 return QualType(New, T.getCVRQualifiers());
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000531}
532
Chris Lattner4b009652007-07-25 00:24:17 +0000533
534/// getComplexType - Return the uniqued reference to the type for a complex
535/// number with the specified element type.
536QualType ASTContext::getComplexType(QualType T) {
537 // Unique pointers, to guarantee there is only one pointer of a particular
538 // structure.
539 llvm::FoldingSetNodeID ID;
540 ComplexType::Profile(ID, T);
541
542 void *InsertPos = 0;
543 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
544 return QualType(CT, 0);
545
546 // If the pointee type isn't canonical, this won't be a canonical type either,
547 // so fill in the canonical type field.
548 QualType Canonical;
549 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000550 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000551
552 // Get the new insert position for the node we care about.
553 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
554 assert(NewIP == 0 && "Shouldn't be in the map!");
555 }
556 ComplexType *New = new ComplexType(T, Canonical);
557 Types.push_back(New);
558 ComplexTypes.InsertNode(New, InsertPos);
559 return QualType(New, 0);
560}
561
562
563/// getPointerType - Return the uniqued reference to the type for a pointer to
564/// the specified type.
565QualType ASTContext::getPointerType(QualType T) {
566 // Unique pointers, to guarantee there is only one pointer of a particular
567 // structure.
568 llvm::FoldingSetNodeID ID;
569 PointerType::Profile(ID, T);
570
571 void *InsertPos = 0;
572 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
573 return QualType(PT, 0);
574
575 // If the pointee type isn't canonical, this won't be a canonical type either,
576 // so fill in the canonical type field.
577 QualType Canonical;
578 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000579 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000580
581 // Get the new insert position for the node we care about.
582 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
583 assert(NewIP == 0 && "Shouldn't be in the map!");
584 }
585 PointerType *New = new PointerType(T, Canonical);
586 Types.push_back(New);
587 PointerTypes.InsertNode(New, InsertPos);
588 return QualType(New, 0);
589}
590
591/// getReferenceType - Return the uniqued reference to the type for a reference
592/// to the specified type.
593QualType ASTContext::getReferenceType(QualType T) {
594 // Unique pointers, to guarantee there is only one pointer of a particular
595 // structure.
596 llvm::FoldingSetNodeID ID;
597 ReferenceType::Profile(ID, T);
598
599 void *InsertPos = 0;
600 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
601 return QualType(RT, 0);
602
603 // If the referencee type isn't canonical, this won't be a canonical type
604 // either, so fill in the canonical type field.
605 QualType Canonical;
606 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000607 Canonical = getReferenceType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000608
609 // Get the new insert position for the node we care about.
610 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
611 assert(NewIP == 0 && "Shouldn't be in the map!");
612 }
613
614 ReferenceType *New = new ReferenceType(T, Canonical);
615 Types.push_back(New);
616 ReferenceTypes.InsertNode(New, InsertPos);
617 return QualType(New, 0);
618}
619
Steve Naroff83c13012007-08-30 01:06:46 +0000620/// getConstantArrayType - Return the unique reference to the type for an
621/// array of the specified element type.
622QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +0000623 const llvm::APInt &ArySize,
624 ArrayType::ArraySizeModifier ASM,
625 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +0000626 llvm::FoldingSetNodeID ID;
Steve Naroff83c13012007-08-30 01:06:46 +0000627 ConstantArrayType::Profile(ID, EltTy, ArySize);
Chris Lattner4b009652007-07-25 00:24:17 +0000628
629 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +0000630 if (ConstantArrayType *ATP =
631 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000632 return QualType(ATP, 0);
633
634 // If the element type isn't canonical, this won't be a canonical type either,
635 // so fill in the canonical type field.
636 QualType Canonical;
637 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000638 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +0000639 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +0000640 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +0000641 ConstantArrayType *NewIP =
642 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
643
Chris Lattner4b009652007-07-25 00:24:17 +0000644 assert(NewIP == 0 && "Shouldn't be in the map!");
645 }
646
Steve Naroff24c9b982007-08-30 18:10:14 +0000647 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
648 ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +0000649 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000650 Types.push_back(New);
651 return QualType(New, 0);
652}
653
Steve Naroffe2579e32007-08-30 18:14:25 +0000654/// getVariableArrayType - Returns a non-unique reference to the type for a
655/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +0000656QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
657 ArrayType::ArraySizeModifier ASM,
658 unsigned EltTypeQuals) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000659 // Since we don't unique expressions, it isn't possible to unique VLA's
660 // that have an expression provided for their size.
661
662 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
663 ASM, EltTypeQuals);
664
665 VariableArrayTypes.push_back(New);
666 Types.push_back(New);
667 return QualType(New, 0);
668}
669
670QualType ASTContext::getIncompleteArrayType(QualType EltTy,
671 ArrayType::ArraySizeModifier ASM,
672 unsigned EltTypeQuals) {
673 llvm::FoldingSetNodeID ID;
674 IncompleteArrayType::Profile(ID, EltTy);
675
676 void *InsertPos = 0;
677 if (IncompleteArrayType *ATP =
678 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
679 return QualType(ATP, 0);
680
681 // If the element type isn't canonical, this won't be a canonical type
682 // either, so fill in the canonical type field.
683 QualType Canonical;
684
685 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000686 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000687 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +0000688
689 // Get the new insert position for the node we care about.
690 IncompleteArrayType *NewIP =
691 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
692
693 assert(NewIP == 0 && "Shouldn't be in the map!");
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000694 }
Eli Friedman8ff07782008-02-15 18:16:39 +0000695
696 IncompleteArrayType *New = new IncompleteArrayType(EltTy, Canonical,
697 ASM, EltTypeQuals);
698
699 IncompleteArrayTypes.InsertNode(New, InsertPos);
700 Types.push_back(New);
701 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +0000702}
703
Chris Lattner4b009652007-07-25 00:24:17 +0000704/// getVectorType - Return the unique reference to a vector type of
705/// the specified element type and size. VectorType must be a built-in type.
706QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
707 BuiltinType *baseType;
708
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000709 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +0000710 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
711
712 // Check if we've already instantiated a vector of this type.
713 llvm::FoldingSetNodeID ID;
714 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
715 void *InsertPos = 0;
716 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
717 return QualType(VTP, 0);
718
719 // If the element type isn't canonical, this won't be a canonical type either,
720 // so fill in the canonical type field.
721 QualType Canonical;
722 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000723 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +0000724
725 // Get the new insert position for the node we care about.
726 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
727 assert(NewIP == 0 && "Shouldn't be in the map!");
728 }
729 VectorType *New = new VectorType(vecType, NumElts, Canonical);
730 VectorTypes.InsertNode(New, InsertPos);
731 Types.push_back(New);
732 return QualType(New, 0);
733}
734
Nate Begemanaf6ed502008-04-18 23:10:10 +0000735/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +0000736/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000737QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +0000738 BuiltinType *baseType;
739
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000740 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +0000741 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +0000742
743 // Check if we've already instantiated a vector of this type.
744 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +0000745 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +0000746 void *InsertPos = 0;
747 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
748 return QualType(VTP, 0);
749
750 // If the element type isn't canonical, this won't be a canonical type either,
751 // so fill in the canonical type field.
752 QualType Canonical;
753 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000754 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +0000755
756 // Get the new insert position for the node we care about.
757 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
758 assert(NewIP == 0 && "Shouldn't be in the map!");
759 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000760 ExtVectorType *New = new ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000761 VectorTypes.InsertNode(New, InsertPos);
762 Types.push_back(New);
763 return QualType(New, 0);
764}
765
766/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
767///
768QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
769 // Unique functions, to guarantee there is only one function of a particular
770 // structure.
771 llvm::FoldingSetNodeID ID;
772 FunctionTypeNoProto::Profile(ID, ResultTy);
773
774 void *InsertPos = 0;
775 if (FunctionTypeNoProto *FT =
776 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
777 return QualType(FT, 0);
778
779 QualType Canonical;
780 if (!ResultTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000781 Canonical = getFunctionTypeNoProto(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000782
783 // Get the new insert position for the node we care about.
784 FunctionTypeNoProto *NewIP =
785 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
786 assert(NewIP == 0 && "Shouldn't be in the map!");
787 }
788
789 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
790 Types.push_back(New);
Eli Friedmanaa0fdfd2008-02-25 22:11:40 +0000791 FunctionTypeNoProtos.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000792 return QualType(New, 0);
793}
794
795/// getFunctionType - Return a normal function type with a typed argument
796/// list. isVariadic indicates whether the argument list includes '...'.
797QualType ASTContext::getFunctionType(QualType ResultTy, QualType *ArgArray,
798 unsigned NumArgs, bool isVariadic) {
799 // Unique functions, to guarantee there is only one function of a particular
800 // structure.
801 llvm::FoldingSetNodeID ID;
802 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic);
803
804 void *InsertPos = 0;
805 if (FunctionTypeProto *FTP =
806 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
807 return QualType(FTP, 0);
808
809 // Determine whether the type being created is already canonical or not.
810 bool isCanonical = ResultTy->isCanonical();
811 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
812 if (!ArgArray[i]->isCanonical())
813 isCanonical = false;
814
815 // If this type isn't canonical, get the canonical version of it.
816 QualType Canonical;
817 if (!isCanonical) {
818 llvm::SmallVector<QualType, 16> CanonicalArgs;
819 CanonicalArgs.reserve(NumArgs);
820 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000821 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Chris Lattner4b009652007-07-25 00:24:17 +0000822
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000823 Canonical = getFunctionType(getCanonicalType(ResultTy),
Chris Lattner4b009652007-07-25 00:24:17 +0000824 &CanonicalArgs[0], NumArgs,
825 isVariadic);
826
827 // Get the new insert position for the node we care about.
828 FunctionTypeProto *NewIP =
829 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
830 assert(NewIP == 0 && "Shouldn't be in the map!");
831 }
832
833 // FunctionTypeProto objects are not allocated with new because they have a
834 // variable size array (for parameter types) at the end of them.
835 FunctionTypeProto *FTP =
836 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) +
837 NumArgs*sizeof(QualType));
838 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
839 Canonical);
840 Types.push_back(FTP);
841 FunctionTypeProtos.InsertNode(FTP, InsertPos);
842 return QualType(FTP, 0);
843}
844
Douglas Gregor1d661552008-04-13 21:07:44 +0000845/// getTypeDeclType - Return the unique reference to the type for the
846/// specified type declaration.
847QualType ASTContext::getTypeDeclType(TypeDecl *Decl) {
848 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
849
850 if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(Decl))
851 return getTypedefType(Typedef);
852 else if (ObjCInterfaceDecl *ObjCInterface
853 = dyn_cast_or_null<ObjCInterfaceDecl>(Decl))
854 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000855
856 if (CXXRecordDecl *CXXRecord = dyn_cast_or_null<CXXRecordDecl>(Decl))
857 Decl->TypeForDecl = new CXXRecordType(CXXRecord);
858 else if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +0000859 Decl->TypeForDecl = new RecordType(Record);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000860 else if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +0000861 Decl->TypeForDecl = new EnumType(Enum);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000862 else
Douglas Gregor1d661552008-04-13 21:07:44 +0000863 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +0000864
865 Types.push_back(Decl->TypeForDecl);
866 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +0000867}
868
Chris Lattner4b009652007-07-25 00:24:17 +0000869/// getTypedefType - Return the unique reference to the type for the
870/// specified typename decl.
871QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
872 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
873
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000874 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000875 Decl->TypeForDecl = new TypedefType(Type::TypeName, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000876 Types.push_back(Decl->TypeForDecl);
877 return QualType(Decl->TypeForDecl, 0);
878}
879
Ted Kremenek42730c52008-01-07 19:49:32 +0000880/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff81f1bba2007-09-06 21:24:23 +0000881/// specified ObjC interface decl.
Ted Kremenek42730c52008-01-07 19:49:32 +0000882QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
Steve Naroff81f1bba2007-09-06 21:24:23 +0000883 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
884
Ted Kremenek42730c52008-01-07 19:49:32 +0000885 Decl->TypeForDecl = new ObjCInterfaceType(Type::ObjCInterface, Decl);
Steve Naroff81f1bba2007-09-06 21:24:23 +0000886 Types.push_back(Decl->TypeForDecl);
887 return QualType(Decl->TypeForDecl, 0);
888}
889
Chris Lattnere1352302008-04-07 04:56:42 +0000890/// CmpProtocolNames - Comparison predicate for sorting protocols
891/// alphabetically.
892static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
893 const ObjCProtocolDecl *RHS) {
894 return strcmp(LHS->getName(), RHS->getName()) < 0;
895}
896
897static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
898 unsigned &NumProtocols) {
899 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
900
901 // Sort protocols, keyed by name.
902 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
903
904 // Remove duplicates.
905 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
906 NumProtocols = ProtocolsEnd-Protocols;
907}
908
909
Chris Lattnerb0c6a1f2008-04-07 04:44:08 +0000910/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
911/// the given interface decl and the conforming protocol list.
Ted Kremenek42730c52008-01-07 19:49:32 +0000912QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
913 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +0000914 // Sort the protocol list alphabetically to canonicalize it.
915 SortAndUniqueProtocols(Protocols, NumProtocols);
916
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000917 llvm::FoldingSetNodeID ID;
Chris Lattner7cdcb252008-04-07 06:38:24 +0000918 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000919
920 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000921 if (ObjCQualifiedInterfaceType *QT =
922 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000923 return QualType(QT, 0);
924
925 // No Match;
Ted Kremenek42730c52008-01-07 19:49:32 +0000926 ObjCQualifiedInterfaceType *QType =
927 new ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000928 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +0000929 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000930 return QualType(QType, 0);
931}
932
Chris Lattnere1352302008-04-07 04:56:42 +0000933/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
934/// and the conforming protocol list.
Chris Lattner4a68fe02008-07-26 00:46:50 +0000935QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000936 unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +0000937 // Sort the protocol list alphabetically to canonicalize it.
938 SortAndUniqueProtocols(Protocols, NumProtocols);
939
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000940 llvm::FoldingSetNodeID ID;
Ted Kremenek42730c52008-01-07 19:49:32 +0000941 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000942
943 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000944 if (ObjCQualifiedIdType *QT =
Chris Lattner4a68fe02008-07-26 00:46:50 +0000945 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000946 return QualType(QT, 0);
947
948 // No Match;
Chris Lattner4a68fe02008-07-26 00:46:50 +0000949 ObjCQualifiedIdType *QType = new ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000950 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +0000951 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000952 return QualType(QType, 0);
953}
954
Steve Naroff0604dd92007-08-01 18:02:17 +0000955/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
956/// TypeOfExpr AST's (since expression's are never shared). For example,
957/// multiple declarations that refer to "typeof(x)" all contain different
958/// DeclRefExpr's. This doesn't effect the type checker, since it operates
959/// on canonical type's (which are always unique).
Steve Naroff11b649c2007-08-01 17:20:42 +0000960QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000961 QualType Canonical = getCanonicalType(tofExpr->getType());
Steve Naroff0604dd92007-08-01 18:02:17 +0000962 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
963 Types.push_back(toe);
964 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000965}
966
Steve Naroff0604dd92007-08-01 18:02:17 +0000967/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
968/// TypeOfType AST's. The only motivation to unique these nodes would be
969/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
970/// an issue. This doesn't effect the type checker, since it operates
971/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +0000972QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000973 QualType Canonical = getCanonicalType(tofType);
Steve Naroff0604dd92007-08-01 18:02:17 +0000974 TypeOfType *tot = new TypeOfType(tofType, Canonical);
975 Types.push_back(tot);
976 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000977}
978
Chris Lattner4b009652007-07-25 00:24:17 +0000979/// getTagDeclType - Return the unique reference to the type for the
980/// specified TagDecl (struct/union/class/enum) decl.
981QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +0000982 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +0000983 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +0000984}
985
986/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
987/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
988/// needs to agree with the definition in <stddef.h>.
989QualType ASTContext::getSizeType() const {
990 // On Darwin, size_t is defined as a "long unsigned int".
991 // FIXME: should derive from "Target".
992 return UnsignedLongTy;
993}
994
Eli Friedmanfdd35d72008-02-12 08:29:21 +0000995/// getWcharType - Return the unique type for "wchar_t" (C99 7.17), the
996/// width of characters in wide strings, The value is target dependent and
997/// needs to agree with the definition in <stddef.h>.
998QualType ASTContext::getWcharType() const {
999 // On Darwin, wchar_t is defined as a "int".
1000 // FIXME: should derive from "Target".
1001 return IntTy;
1002}
1003
Chris Lattner4b009652007-07-25 00:24:17 +00001004/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1005/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1006QualType ASTContext::getPointerDiffType() const {
1007 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug...
1008 // FIXME: should derive from "Target".
1009 return IntTy;
1010}
1011
Chris Lattner19eb97e2008-04-02 05:18:44 +00001012//===----------------------------------------------------------------------===//
1013// Type Operators
1014//===----------------------------------------------------------------------===//
1015
Chris Lattner3dae6f42008-04-06 22:41:35 +00001016/// getCanonicalType - Return the canonical (structural) type corresponding to
1017/// the specified potentially non-canonical type. The non-canonical version
1018/// of a type may have many "decorated" versions of types. Decorators can
1019/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1020/// to be free of any of these, allowing two canonical types to be compared
1021/// for exact equality with a simple pointer comparison.
1022QualType ASTContext::getCanonicalType(QualType T) {
1023 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001024
1025 // If the result has type qualifiers, make sure to canonicalize them as well.
1026 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1027 if (TypeQuals == 0) return CanType;
1028
1029 // If the type qualifiers are on an array type, get the canonical type of the
1030 // array with the qualifiers applied to the element type.
1031 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1032 if (!AT)
1033 return CanType.getQualifiedType(TypeQuals);
1034
1035 // Get the canonical version of the element with the extra qualifiers on it.
1036 // This can recursively sink qualifiers through multiple levels of arrays.
1037 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1038 NewEltTy = getCanonicalType(NewEltTy);
1039
1040 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1041 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1042 CAT->getIndexTypeQualifier());
1043 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1044 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1045 IAT->getIndexTypeQualifier());
1046
1047 // FIXME: What is the ownership of size expressions in VLAs?
1048 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1049 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1050 VAT->getSizeModifier(),
1051 VAT->getIndexTypeQualifier());
1052}
1053
1054
1055const ArrayType *ASTContext::getAsArrayType(QualType T) {
1056 // Handle the non-qualified case efficiently.
1057 if (T.getCVRQualifiers() == 0) {
1058 // Handle the common positive case fast.
1059 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1060 return AT;
1061 }
1062
1063 // Handle the common negative case fast, ignoring CVR qualifiers.
1064 QualType CType = T->getCanonicalTypeInternal();
1065
1066 // Make sure to look through type qualifiers (like ASQuals) for the negative
1067 // test.
1068 if (!isa<ArrayType>(CType) &&
1069 !isa<ArrayType>(CType.getUnqualifiedType()))
1070 return 0;
1071
1072 // Apply any CVR qualifiers from the array type to the element type. This
1073 // implements C99 6.7.3p8: "If the specification of an array type includes
1074 // any type qualifiers, the element type is so qualified, not the array type."
1075
1076 // If we get here, we either have type qualifiers on the type, or we have
1077 // sugar such as a typedef in the way. If we have type qualifiers on the type
1078 // we must propagate them down into the elemeng type.
1079 unsigned CVRQuals = T.getCVRQualifiers();
1080 unsigned AddrSpace = 0;
1081 Type *Ty = T.getTypePtr();
1082
1083 // Rip through ASQualType's and typedefs to get to a concrete type.
1084 while (1) {
1085 if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty)) {
1086 AddrSpace = ASQT->getAddressSpace();
1087 Ty = ASQT->getBaseType();
1088 } else {
1089 T = Ty->getDesugaredType();
1090 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1091 break;
1092 CVRQuals |= T.getCVRQualifiers();
1093 Ty = T.getTypePtr();
1094 }
1095 }
1096
1097 // If we have a simple case, just return now.
1098 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1099 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1100 return ATy;
1101
1102 // Otherwise, we have an array and we have qualifiers on it. Push the
1103 // qualifiers into the array element type and return a new array type.
1104 // Get the canonical version of the element with the extra qualifiers on it.
1105 // This can recursively sink qualifiers through multiple levels of arrays.
1106 QualType NewEltTy = ATy->getElementType();
1107 if (AddrSpace)
1108 NewEltTy = getASQualType(NewEltTy, AddrSpace);
1109 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1110
1111 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1112 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1113 CAT->getSizeModifier(),
1114 CAT->getIndexTypeQualifier()));
1115 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1116 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1117 IAT->getSizeModifier(),
1118 IAT->getIndexTypeQualifier()));
1119
1120 // FIXME: What is the ownership of size expressions in VLAs?
1121 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1122 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1123 VAT->getSizeModifier(),
1124 VAT->getIndexTypeQualifier()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00001125}
1126
1127
Chris Lattner19eb97e2008-04-02 05:18:44 +00001128/// getArrayDecayedType - Return the properly qualified result of decaying the
1129/// specified array type to a pointer. This operation is non-trivial when
1130/// handling typedefs etc. The canonical type of "T" must be an array type,
1131/// this returns a pointer to a properly qualified element of the array.
1132///
1133/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1134QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001135 // Get the element type with 'getAsArrayType' so that we don't lose any
1136 // typedefs in the element type of the array. This also handles propagation
1137 // of type qualifiers from the array type into the element type if present
1138 // (C99 6.7.3p8).
1139 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1140 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00001141
Chris Lattnera1923f62008-08-04 07:31:14 +00001142 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001143
1144 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00001145 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001146}
1147
Chris Lattner4b009652007-07-25 00:24:17 +00001148/// getFloatingRank - Return a relative rank for floating point types.
1149/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001150static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001151 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00001152 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00001153
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001154 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00001155 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00001156 case BuiltinType::Float: return FloatRank;
1157 case BuiltinType::Double: return DoubleRank;
1158 case BuiltinType::LongDouble: return LongDoubleRank;
1159 }
1160}
1161
Steve Narofffa0c4532007-08-27 01:41:48 +00001162/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1163/// point or a complex type (based on typeDomain/typeSize).
1164/// 'typeDomain' is a real floating point or complex type.
1165/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00001166QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1167 QualType Domain) const {
1168 FloatingRank EltRank = getFloatingRank(Size);
1169 if (Domain->isComplexType()) {
1170 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00001171 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00001172 case FloatRank: return FloatComplexTy;
1173 case DoubleRank: return DoubleComplexTy;
1174 case LongDoubleRank: return LongDoubleComplexTy;
1175 }
Chris Lattner4b009652007-07-25 00:24:17 +00001176 }
Chris Lattner7794ae22008-04-06 23:58:54 +00001177
1178 assert(Domain->isRealFloatingType() && "Unknown domain!");
1179 switch (EltRank) {
1180 default: assert(0 && "getFloatingRank(): illegal value for rank");
1181 case FloatRank: return FloatTy;
1182 case DoubleRank: return DoubleTy;
1183 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00001184 }
Chris Lattner4b009652007-07-25 00:24:17 +00001185}
1186
Chris Lattner51285d82008-04-06 23:55:33 +00001187/// getFloatingTypeOrder - Compare the rank of the two specified floating
1188/// point types, ignoring the domain of the type (i.e. 'double' ==
1189/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1190/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001191int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1192 FloatingRank LHSR = getFloatingRank(LHS);
1193 FloatingRank RHSR = getFloatingRank(RHS);
1194
1195 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001196 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00001197 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001198 return 1;
1199 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00001200}
1201
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001202/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1203/// routine will assert if passed a built-in type that isn't an integer or enum,
1204/// or if it is not canonicalized.
1205static unsigned getIntegerRank(Type *T) {
1206 assert(T->isCanonical() && "T should be canonicalized");
1207 if (isa<EnumType>(T))
1208 return 4;
1209
1210 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00001211 default: assert(0 && "getIntegerRank(): not a built-in integer");
1212 case BuiltinType::Bool:
1213 return 1;
1214 case BuiltinType::Char_S:
1215 case BuiltinType::Char_U:
1216 case BuiltinType::SChar:
1217 case BuiltinType::UChar:
1218 return 2;
1219 case BuiltinType::Short:
1220 case BuiltinType::UShort:
1221 return 3;
1222 case BuiltinType::Int:
1223 case BuiltinType::UInt:
1224 return 4;
1225 case BuiltinType::Long:
1226 case BuiltinType::ULong:
1227 return 5;
1228 case BuiltinType::LongLong:
1229 case BuiltinType::ULongLong:
1230 return 6;
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001231 }
1232}
1233
Chris Lattner51285d82008-04-06 23:55:33 +00001234/// getIntegerTypeOrder - Returns the highest ranked integer type:
1235/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
1236/// LHS < RHS, return -1.
1237int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001238 Type *LHSC = getCanonicalType(LHS).getTypePtr();
1239 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00001240 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001241
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001242 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1243 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00001244
Chris Lattner51285d82008-04-06 23:55:33 +00001245 unsigned LHSRank = getIntegerRank(LHSC);
1246 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00001247
Chris Lattner51285d82008-04-06 23:55:33 +00001248 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
1249 if (LHSRank == RHSRank) return 0;
1250 return LHSRank > RHSRank ? 1 : -1;
1251 }
Chris Lattner4b009652007-07-25 00:24:17 +00001252
Chris Lattner51285d82008-04-06 23:55:33 +00001253 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1254 if (LHSUnsigned) {
1255 // If the unsigned [LHS] type is larger, return it.
1256 if (LHSRank >= RHSRank)
1257 return 1;
1258
1259 // If the signed type can represent all values of the unsigned type, it
1260 // wins. Because we are dealing with 2's complement and types that are
1261 // powers of two larger than each other, this is always safe.
1262 return -1;
1263 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001264
Chris Lattner51285d82008-04-06 23:55:33 +00001265 // If the unsigned [RHS] type is larger, return it.
1266 if (RHSRank >= LHSRank)
1267 return -1;
1268
1269 // If the signed type can represent all values of the unsigned type, it
1270 // wins. Because we are dealing with 2's complement and types that are
1271 // powers of two larger than each other, this is always safe.
1272 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001273}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001274
1275// getCFConstantStringType - Return the type used for constant CFStrings.
1276QualType ASTContext::getCFConstantStringType() {
1277 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00001278 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001279 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Chris Lattner58114f02008-03-15 21:32:50 +00001280 &Idents.get("NSConstantString"), 0);
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001281 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001282
1283 // const int *isa;
1284 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001285 // int flags;
1286 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001287 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001288 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001289 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001290 FieldTypes[3] = LongTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001291 // Create fields
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001292 FieldDecl *FieldDecls[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001293
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001294 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001295 FieldDecls[i] = FieldDecl::Create(*this, SourceLocation(), 0,
Chris Lattner81db64a2008-03-16 00:16:02 +00001296 FieldTypes[i]);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001297
1298 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
1299 }
1300
1301 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00001302}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001303
Anders Carlssone3f02572007-10-29 06:33:42 +00001304// This returns true if a type has been typedefed to BOOL:
1305// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00001306static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00001307 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnercb034cb2007-10-30 20:27:44 +00001308 return !strcmp(TT->getDecl()->getName(), "BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001309
1310 return false;
1311}
1312
Ted Kremenek42730c52008-01-07 19:49:32 +00001313/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001314/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00001315int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001316 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001317
1318 // Make all integer and enum types at least as large as an int
1319 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00001320 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001321 // Treat arrays as pointers, since that's how they're passed in.
1322 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00001323 sz = getTypeSize(VoidPtrTy);
1324 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001325}
1326
Ted Kremenek42730c52008-01-07 19:49:32 +00001327/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001328/// declaration.
Ted Kremenek42730c52008-01-07 19:49:32 +00001329void ASTContext::getObjCEncodingForMethodDecl(ObjCMethodDecl *Decl,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001330 std::string& S)
1331{
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001332 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00001333 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001334 // Encode result type.
Fariborz Jahanian248db262008-01-22 22:44:46 +00001335 getObjCEncodingForType(Decl->getResultType(), S, EncodingRecordTypes);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001336 // Compute size of all parameters.
1337 // Start with computing size of a pointer in number of bytes.
1338 // FIXME: There might(should) be a better way of doing this computation!
1339 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001340 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001341 // The first two arguments (self and _cmd) are pointers; account for
1342 // their size.
1343 int ParmOffset = 2 * PtrSize;
1344 int NumOfParams = Decl->getNumParams();
1345 for (int i = 0; i < NumOfParams; i++) {
1346 QualType PType = Decl->getParamDecl(i)->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001347 int sz = getObjCEncodingTypeSize (PType);
1348 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001349 ParmOffset += sz;
1350 }
1351 S += llvm::utostr(ParmOffset);
1352 S += "@0:";
1353 S += llvm::utostr(PtrSize);
1354
1355 // Argument types.
1356 ParmOffset = 2 * PtrSize;
1357 for (int i = 0; i < NumOfParams; i++) {
1358 QualType PType = Decl->getParamDecl(i)->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001359 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001360 // 'in', 'inout', etc.
Ted Kremenek42730c52008-01-07 19:49:32 +00001361 getObjCEncodingForTypeQualifier(
1362 Decl->getParamDecl(i)->getObjCDeclQualifier(), S);
Fariborz Jahanian248db262008-01-22 22:44:46 +00001363 getObjCEncodingForType(PType, S, EncodingRecordTypes);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001364 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00001365 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001366 }
1367}
1368
Fariborz Jahanian248db262008-01-22 22:44:46 +00001369void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Chris Lattnera1923f62008-08-04 07:31:14 +00001370 llvm::SmallVector<const RecordType *, 8> &ERType) const {
Anders Carlssone3f02572007-10-29 06:33:42 +00001371 // FIXME: This currently doesn't encode:
1372 // @ An object (whether statically typed or typed id)
1373 // # A class object (Class)
1374 // : A method selector (SEL)
1375 // {name=type...} A structure
1376 // (name=type...) A union
1377 // bnum A bit field of num bits
1378
1379 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001380 char encoding;
1381 switch (BT->getKind()) {
Chris Lattner2bf1d6c2008-04-06 22:05:18 +00001382 default: assert(0 && "Unhandled builtin type kind");
1383 case BuiltinType::Void: encoding = 'v'; break;
1384 case BuiltinType::Bool: encoding = 'B'; break;
Anders Carlsson36f07d82007-10-29 05:01:08 +00001385 case BuiltinType::Char_U:
Chris Lattner2bf1d6c2008-04-06 22:05:18 +00001386 case BuiltinType::UChar: encoding = 'C'; break;
1387 case BuiltinType::UShort: encoding = 'S'; break;
1388 case BuiltinType::UInt: encoding = 'I'; break;
1389 case BuiltinType::ULong: encoding = 'L'; break;
1390 case BuiltinType::ULongLong: encoding = 'Q'; break;
Anders Carlsson36f07d82007-10-29 05:01:08 +00001391 case BuiltinType::Char_S:
Chris Lattner2bf1d6c2008-04-06 22:05:18 +00001392 case BuiltinType::SChar: encoding = 'c'; break;
1393 case BuiltinType::Short: encoding = 's'; break;
1394 case BuiltinType::Int: encoding = 'i'; break;
1395 case BuiltinType::Long: encoding = 'l'; break;
1396 case BuiltinType::LongLong: encoding = 'q'; break;
1397 case BuiltinType::Float: encoding = 'f'; break;
1398 case BuiltinType::Double: encoding = 'd'; break;
1399 case BuiltinType::LongDouble: encoding = 'd'; break;
Anders Carlsson36f07d82007-10-29 05:01:08 +00001400 }
1401
1402 S += encoding;
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001403 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001404 else if (T->isObjCQualifiedIdType()) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001405 // Treat id<P...> same as 'id' for encoding purposes.
Fariborz Jahanian248db262008-01-22 22:44:46 +00001406 return getObjCEncodingForType(getObjCIdType(), S, ERType);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001407
1408 }
1409 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001410 QualType PointeeTy = PT->getPointeeType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001411 if (isObjCIdType(PointeeTy) || PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001412 S += '@';
1413 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00001414 } else if (isObjCClassType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001415 S += '#';
1416 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00001417 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001418 S += ':';
1419 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001420 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00001421
1422 if (PointeeTy->isCharType()) {
1423 // char pointer types should be encoded as '*' unless it is a
1424 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00001425 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001426 S += '*';
1427 return;
1428 }
1429 }
1430
1431 S += '^';
Fariborz Jahanian248db262008-01-22 22:44:46 +00001432 getObjCEncodingForType(PT->getPointeeType(), S, ERType);
Chris Lattnera1923f62008-08-04 07:31:14 +00001433 } else if (const ArrayType *AT =
1434 // Ignore type qualifiers etc.
1435 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001436 S += '[';
1437
1438 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1439 S += llvm::utostr(CAT->getSize().getZExtValue());
1440 else
1441 assert(0 && "Unhandled array type!");
1442
Fariborz Jahanian248db262008-01-22 22:44:46 +00001443 getObjCEncodingForType(AT->getElementType(), S, ERType);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001444 S += ']';
Anders Carlsson5695bb72007-10-30 00:06:20 +00001445 } else if (T->getAsFunctionType()) {
1446 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001447 } else if (const RecordType *RTy = T->getAsRecordType()) {
1448 RecordDecl *RDecl= RTy->getDecl();
1449 S += '{';
1450 S += RDecl->getName();
Fariborz Jahanian248db262008-01-22 22:44:46 +00001451 bool found = false;
1452 for (unsigned i = 0, e = ERType.size(); i != e; ++i)
1453 if (ERType[i] == RTy) {
1454 found = true;
1455 break;
1456 }
1457 if (!found) {
1458 ERType.push_back(RTy);
1459 S += '=';
1460 for (int i = 0; i < RDecl->getNumMembers(); i++) {
1461 FieldDecl *field = RDecl->getMember(i);
1462 getObjCEncodingForType(field->getType(), S, ERType);
1463 }
1464 assert(ERType.back() == RTy && "Record Type stack mismatch.");
1465 ERType.pop_back();
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00001466 }
1467 S += '}';
Steve Naroff49af3f32007-12-12 22:30:11 +00001468 } else if (T->isEnumeralType()) {
1469 S += 'i';
Anders Carlsson36f07d82007-10-29 05:01:08 +00001470 } else
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001471 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001472}
1473
Ted Kremenek42730c52008-01-07 19:49:32 +00001474void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00001475 std::string& S) const {
1476 if (QT & Decl::OBJC_TQ_In)
1477 S += 'n';
1478 if (QT & Decl::OBJC_TQ_Inout)
1479 S += 'N';
1480 if (QT & Decl::OBJC_TQ_Out)
1481 S += 'o';
1482 if (QT & Decl::OBJC_TQ_Bycopy)
1483 S += 'O';
1484 if (QT & Decl::OBJC_TQ_Byref)
1485 S += 'R';
1486 if (QT & Decl::OBJC_TQ_Oneway)
1487 S += 'V';
1488}
1489
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001490void ASTContext::setBuiltinVaListType(QualType T)
1491{
1492 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1493
1494 BuiltinVaListType = T;
1495}
1496
Ted Kremenek42730c52008-01-07 19:49:32 +00001497void ASTContext::setObjCIdType(TypedefDecl *TD)
Steve Naroff9d12c902007-10-15 14:41:52 +00001498{
Ted Kremenek42730c52008-01-07 19:49:32 +00001499 assert(ObjCIdType.isNull() && "'id' type already set!");
Steve Naroff9d12c902007-10-15 14:41:52 +00001500
Ted Kremenek42730c52008-01-07 19:49:32 +00001501 ObjCIdType = getTypedefType(TD);
Steve Naroff9d12c902007-10-15 14:41:52 +00001502
1503 // typedef struct objc_object *id;
1504 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1505 assert(ptr && "'id' incorrectly typed");
1506 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1507 assert(rec && "'id' incorrectly typed");
1508 IdStructType = rec;
1509}
1510
Ted Kremenek42730c52008-01-07 19:49:32 +00001511void ASTContext::setObjCSelType(TypedefDecl *TD)
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001512{
Ted Kremenek42730c52008-01-07 19:49:32 +00001513 assert(ObjCSelType.isNull() && "'SEL' type already set!");
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001514
Ted Kremenek42730c52008-01-07 19:49:32 +00001515 ObjCSelType = getTypedefType(TD);
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001516
1517 // typedef struct objc_selector *SEL;
1518 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1519 assert(ptr && "'SEL' incorrectly typed");
1520 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1521 assert(rec && "'SEL' incorrectly typed");
1522 SelStructType = rec;
1523}
1524
Ted Kremenek42730c52008-01-07 19:49:32 +00001525void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001526{
Ted Kremenek42730c52008-01-07 19:49:32 +00001527 assert(ObjCProtoType.isNull() && "'Protocol' type already set!");
1528 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001529}
1530
Ted Kremenek42730c52008-01-07 19:49:32 +00001531void ASTContext::setObjCClassType(TypedefDecl *TD)
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001532{
Ted Kremenek42730c52008-01-07 19:49:32 +00001533 assert(ObjCClassType.isNull() && "'Class' type already set!");
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001534
Ted Kremenek42730c52008-01-07 19:49:32 +00001535 ObjCClassType = getTypedefType(TD);
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001536
1537 // typedef struct objc_class *Class;
1538 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1539 assert(ptr && "'Class' incorrectly typed");
1540 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1541 assert(rec && "'Class' incorrectly typed");
1542 ClassStructType = rec;
1543}
1544
Ted Kremenek42730c52008-01-07 19:49:32 +00001545void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
1546 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00001547 "'NSConstantString' type already set!");
1548
Ted Kremenek42730c52008-01-07 19:49:32 +00001549 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00001550}
1551
Ted Kremenek118930e2008-07-24 23:58:27 +00001552
1553//===----------------------------------------------------------------------===//
1554// Type Predicates.
1555//===----------------------------------------------------------------------===//
1556
1557/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
1558/// to an object type. This includes "id" and "Class" (two 'special' pointers
1559/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
1560/// ID type).
1561bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
1562 if (Ty->isObjCQualifiedIdType())
1563 return true;
1564
1565 if (!Ty->isPointerType())
1566 return false;
1567
1568 // Check to see if this is 'id' or 'Class', both of which are typedefs for
1569 // pointer types. This looks for the typedef specifically, not for the
1570 // underlying type.
1571 if (Ty == getObjCIdType() || Ty == getObjCClassType())
1572 return true;
1573
1574 // If this a pointer to an interface (e.g. NSString*), it is ok.
1575 return Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType();
1576}
1577
Chris Lattner6ff358b2008-04-07 06:51:04 +00001578//===----------------------------------------------------------------------===//
1579// Type Compatibility Testing
1580//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00001581
Chris Lattner390564e2008-04-07 06:49:41 +00001582/// C99 6.2.7p1: If both are complete types, then the following additional
1583/// requirements apply.
1584/// FIXME (handle compatibility across source files).
1585static bool areCompatTagTypes(TagType *LHS, TagType *RHS,
1586 const ASTContext &C) {
Steve Naroff4a5e2072007-11-07 06:03:51 +00001587 // "Class" and "id" are compatible built-in structure types.
Chris Lattner390564e2008-04-07 06:49:41 +00001588 if (C.isObjCIdType(QualType(LHS, 0)) && C.isObjCClassType(QualType(RHS, 0)) ||
1589 C.isObjCClassType(QualType(LHS, 0)) && C.isObjCIdType(QualType(RHS, 0)))
Steve Naroff4a5e2072007-11-07 06:03:51 +00001590 return true;
Eli Friedmane7fb03a2008-02-15 06:03:44 +00001591
Chris Lattner390564e2008-04-07 06:49:41 +00001592 // Within a translation unit a tag type is only compatible with itself. Self
1593 // equality is already handled by the time we get here.
1594 assert(LHS != RHS && "Self equality not handled!");
1595 return false;
Steve Naroff85f0dc52007-10-15 20:41:53 +00001596}
1597
1598bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) {
1599 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be
1600 // identically qualified and both shall be pointers to compatible types.
Chris Lattner35fef522008-02-20 20:55:12 +00001601 if (lhs.getCVRQualifiers() != rhs.getCVRQualifiers() ||
1602 lhs.getAddressSpace() != rhs.getAddressSpace())
Steve Naroff85f0dc52007-10-15 20:41:53 +00001603 return false;
1604
Chris Lattner25168a52008-07-26 21:30:36 +00001605 QualType ltype = lhs->getAsPointerType()->getPointeeType();
1606 QualType rtype = rhs->getAsPointerType()->getPointeeType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00001607
1608 return typesAreCompatible(ltype, rtype);
1609}
1610
Steve Naroff85f0dc52007-10-15 20:41:53 +00001611bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) {
Chris Lattner25168a52008-07-26 21:30:36 +00001612 const FunctionType *lbase = lhs->getAsFunctionType();
1613 const FunctionType *rbase = rhs->getAsFunctionType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00001614 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1615 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1616
1617 // first check the return types (common between C99 and K&R).
1618 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType()))
1619 return false;
1620
1621 if (lproto && rproto) { // two C99 style function prototypes
1622 unsigned lproto_nargs = lproto->getNumArgs();
1623 unsigned rproto_nargs = rproto->getNumArgs();
1624
1625 if (lproto_nargs != rproto_nargs)
1626 return false;
1627
1628 // both prototypes have the same number of arguments.
1629 if ((lproto->isVariadic() && !rproto->isVariadic()) ||
1630 (rproto->isVariadic() && !lproto->isVariadic()))
1631 return false;
1632
1633 // The use of ellipsis agree...now check the argument types.
1634 for (unsigned i = 0; i < lproto_nargs; i++)
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001635 // C99 6.7.5.3p15: ...and each parameter declared with qualified type
1636 // is taken as having the unqualified version of it's declared type.
Steve Naroffdec17fe2008-01-29 00:15:50 +00001637 if (!typesAreCompatible(lproto->getArgType(i).getUnqualifiedType(),
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001638 rproto->getArgType(i).getUnqualifiedType()))
Steve Naroff85f0dc52007-10-15 20:41:53 +00001639 return false;
1640 return true;
1641 }
Chris Lattner1d78a862008-04-07 07:01:58 +00001642
Steve Naroff85f0dc52007-10-15 20:41:53 +00001643 if (!lproto && !rproto) // two K&R style function decls, nothing to do.
1644 return true;
1645
1646 // we have a mixture of K&R style with C99 prototypes
1647 const FunctionTypeProto *proto = lproto ? lproto : rproto;
Steve Naroff85f0dc52007-10-15 20:41:53 +00001648 if (proto->isVariadic())
1649 return false;
1650
1651 // FIXME: Each parameter type T in the prototype must be compatible with the
1652 // type resulting from applying the usual argument conversions to T.
1653 return true;
1654}
1655
Chris Lattnerf0d2ee02008-04-07 06:56:55 +00001656// C99 6.7.5.2p6
1657static bool areCompatArrayTypes(ArrayType *LHS, ArrayType *RHS, ASTContext &C) {
Chris Lattnerf0d2ee02008-04-07 06:56:55 +00001658 // Constant arrays must be the same size to be compatible.
1659 if (const ConstantArrayType* LCAT = dyn_cast<ConstantArrayType>(LHS))
1660 if (const ConstantArrayType* RCAT = dyn_cast<ConstantArrayType>(RHS))
1661 if (RCAT->getSize() != LCAT->getSize())
1662 return false;
Eli Friedman1e7537832008-02-06 04:53:22 +00001663
Chris Lattnerc8971d72008-04-07 06:58:21 +00001664 // Compatible arrays must have compatible element types
1665 return C.typesAreCompatible(LHS->getElementType(), RHS->getElementType());
Steve Naroff85f0dc52007-10-15 20:41:53 +00001666}
1667
Chris Lattner6ff358b2008-04-07 06:51:04 +00001668/// areCompatVectorTypes - Return true if the two specified vector types are
1669/// compatible.
1670static bool areCompatVectorTypes(const VectorType *LHS,
1671 const VectorType *RHS) {
1672 assert(LHS->isCanonical() && RHS->isCanonical());
1673 return LHS->getElementType() == RHS->getElementType() &&
1674 LHS->getNumElements() == RHS->getNumElements();
1675}
1676
1677/// areCompatObjCInterfaces - Return true if the two interface types are
1678/// compatible for assignment from RHS to LHS. This handles validation of any
1679/// protocol qualifiers on the LHS or RHS.
1680///
Chris Lattner1d78a862008-04-07 07:01:58 +00001681static bool areCompatObjCInterfaces(const ObjCInterfaceType *LHS,
1682 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00001683 // Verify that the base decls are compatible: the RHS must be a subclass of
1684 // the LHS.
1685 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
1686 return false;
1687
1688 // RHS must have a superset of the protocols in the LHS. If the LHS is not
1689 // protocol qualified at all, then we are good.
1690 if (!isa<ObjCQualifiedInterfaceType>(LHS))
1691 return true;
1692
1693 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
1694 // isn't a superset.
1695 if (!isa<ObjCQualifiedInterfaceType>(RHS))
1696 return true; // FIXME: should return false!
1697
1698 // Finally, we must have two protocol-qualified interfaces.
1699 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
1700 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
1701 ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin();
1702 ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end();
1703 ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin();
1704 ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end();
1705
1706 // All protocols in LHS must have a presence in RHS. Since the protocol lists
1707 // are both sorted alphabetically and have no duplicates, we can scan RHS and
1708 // LHS in a single parallel scan until we run out of elements in LHS.
1709 assert(LHSPI != LHSPE && "Empty LHS protocol list?");
1710 ObjCProtocolDecl *LHSProto = *LHSPI;
1711
1712 while (RHSPI != RHSPE) {
1713 ObjCProtocolDecl *RHSProto = *RHSPI++;
1714 // If the RHS has a protocol that the LHS doesn't, ignore it.
1715 if (RHSProto != LHSProto)
1716 continue;
1717
1718 // Otherwise, the RHS does have this element.
1719 ++LHSPI;
1720 if (LHSPI == LHSPE)
1721 return true; // All protocols in LHS exist in RHS.
1722
1723 LHSProto = *LHSPI;
1724 }
1725
1726 // If we got here, we didn't find one of the LHS's protocols in the RHS list.
1727 return false;
1728}
1729
1730
Steve Naroff85f0dc52007-10-15 20:41:53 +00001731/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1732/// both shall have the identically qualified version of a compatible type.
1733/// C99 6.2.7p1: Two types have compatible types if their types are the
1734/// same. See 6.7.[2,3,5] for additional rules.
Chris Lattner855fed42008-04-07 04:07:56 +00001735bool ASTContext::typesAreCompatible(QualType LHS_NC, QualType RHS_NC) {
Chris Lattner25168a52008-07-26 21:30:36 +00001736 QualType LHS = getCanonicalType(LHS_NC);
1737 QualType RHS = getCanonicalType(RHS_NC);
Chris Lattner4d5670b2008-04-03 05:07:04 +00001738
Bill Wendling6a9d8542007-12-03 07:33:35 +00001739 // C++ [expr]: If an expression initially has the type "reference to T", the
1740 // type is adjusted to "T" prior to any further analysis, the expression
1741 // designates the object or function denoted by the reference, and the
1742 // expression is an lvalue.
Chris Lattner855fed42008-04-07 04:07:56 +00001743 if (ReferenceType *RT = dyn_cast<ReferenceType>(LHS))
1744 LHS = RT->getPointeeType();
1745 if (ReferenceType *RT = dyn_cast<ReferenceType>(RHS))
1746 RHS = RT->getPointeeType();
Chris Lattnerc38d4522008-01-14 05:45:46 +00001747
Chris Lattnerd47d6042008-04-07 05:37:56 +00001748 // If two types are identical, they are compatible.
1749 if (LHS == RHS)
1750 return true;
1751
1752 // If qualifiers differ, the types are different.
Chris Lattnerb5709e22008-04-07 05:43:21 +00001753 unsigned LHSAS = LHS.getAddressSpace(), RHSAS = RHS.getAddressSpace();
1754 if (LHS.getCVRQualifiers() != RHS.getCVRQualifiers() || LHSAS != RHSAS)
Chris Lattnerd47d6042008-04-07 05:37:56 +00001755 return false;
Chris Lattnerb5709e22008-04-07 05:43:21 +00001756
1757 // Strip off ASQual's if present.
1758 if (LHSAS) {
1759 LHS = LHS.getUnqualifiedType();
1760 RHS = RHS.getUnqualifiedType();
1761 }
Chris Lattnerd47d6042008-04-07 05:37:56 +00001762
Chris Lattner855fed42008-04-07 04:07:56 +00001763 Type::TypeClass LHSClass = LHS->getTypeClass();
1764 Type::TypeClass RHSClass = RHS->getTypeClass();
Chris Lattnerc38d4522008-01-14 05:45:46 +00001765
1766 // We want to consider the two function types to be the same for these
1767 // comparisons, just force one to the other.
1768 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
1769 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00001770
1771 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00001772 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
1773 LHSClass = Type::ConstantArray;
1774 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
1775 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00001776
Nate Begemanaf6ed502008-04-18 23:10:10 +00001777 // Canonicalize ExtVector -> Vector.
1778 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
1779 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00001780
Chris Lattner7cdcb252008-04-07 06:38:24 +00001781 // Consider qualified interfaces and interfaces the same.
1782 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
1783 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
1784
Chris Lattnerb5709e22008-04-07 05:43:21 +00001785 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00001786 if (LHSClass != RHSClass) {
Chris Lattner7cdcb252008-04-07 06:38:24 +00001787 // ID is compatible with all interface types.
1788 if (isa<ObjCInterfaceType>(LHS))
1789 return isObjCIdType(RHS);
1790 if (isa<ObjCInterfaceType>(RHS))
1791 return isObjCIdType(LHS);
Steve Naroff44549772008-06-04 15:07:33 +00001792
1793 // ID is compatible with all qualified id types.
1794 if (isa<ObjCQualifiedIdType>(LHS)) {
1795 if (const PointerType *PT = RHS->getAsPointerType())
1796 return isObjCIdType(PT->getPointeeType());
1797 }
1798 if (isa<ObjCQualifiedIdType>(RHS)) {
1799 if (const PointerType *PT = LHS->getAsPointerType())
1800 return isObjCIdType(PT->getPointeeType());
1801 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00001802 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
1803 // a signed integer type, or an unsigned integer type.
Chris Lattner855fed42008-04-07 04:07:56 +00001804 if (LHS->isEnumeralType() && RHS->isIntegralType()) {
1805 EnumDecl* EDecl = cast<EnumType>(LHS)->getDecl();
1806 return EDecl->getIntegerType() == RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00001807 }
Chris Lattner855fed42008-04-07 04:07:56 +00001808 if (RHS->isEnumeralType() && LHS->isIntegralType()) {
1809 EnumDecl* EDecl = cast<EnumType>(RHS)->getDecl();
1810 return EDecl->getIntegerType() == LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00001811 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00001812
Steve Naroff85f0dc52007-10-15 20:41:53 +00001813 return false;
1814 }
Chris Lattnerb5709e22008-04-07 05:43:21 +00001815
Steve Naroffc88babe2008-01-09 22:43:08 +00001816 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00001817 switch (LHSClass) {
Chris Lattnerb5709e22008-04-07 05:43:21 +00001818 case Type::ASQual:
1819 case Type::FunctionProto:
1820 case Type::VariableArray:
1821 case Type::IncompleteArray:
1822 case Type::Reference:
Chris Lattner7cdcb252008-04-07 06:38:24 +00001823 case Type::ObjCQualifiedInterface:
Chris Lattnerb5709e22008-04-07 05:43:21 +00001824 assert(0 && "Canonicalized away above");
Chris Lattnerc38d4522008-01-14 05:45:46 +00001825 case Type::Pointer:
Chris Lattner855fed42008-04-07 04:07:56 +00001826 return pointerTypesAreCompatible(LHS, RHS);
Chris Lattnerc38d4522008-01-14 05:45:46 +00001827 case Type::ConstantArray:
Chris Lattnerf0d2ee02008-04-07 06:56:55 +00001828 return areCompatArrayTypes(cast<ArrayType>(LHS), cast<ArrayType>(RHS),
1829 *this);
Chris Lattnerc38d4522008-01-14 05:45:46 +00001830 case Type::FunctionNoProto:
Chris Lattner855fed42008-04-07 04:07:56 +00001831 return functionTypesAreCompatible(LHS, RHS);
Chris Lattnerc38d4522008-01-14 05:45:46 +00001832 case Type::Tagged: // handle structures, unions
Chris Lattner390564e2008-04-07 06:49:41 +00001833 return areCompatTagTypes(cast<TagType>(LHS), cast<TagType>(RHS), *this);
Chris Lattnerc38d4522008-01-14 05:45:46 +00001834 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00001835 // Only exactly equal builtin types are compatible, which is tested above.
1836 return false;
1837 case Type::Vector:
1838 return areCompatVectorTypes(cast<VectorType>(LHS), cast<VectorType>(RHS));
Chris Lattnerc38d4522008-01-14 05:45:46 +00001839 case Type::ObjCInterface:
Chris Lattner7cdcb252008-04-07 06:38:24 +00001840 return areCompatObjCInterfaces(cast<ObjCInterfaceType>(LHS),
1841 cast<ObjCInterfaceType>(RHS));
Chris Lattnerc38d4522008-01-14 05:45:46 +00001842 default:
1843 assert(0 && "unexpected type");
Steve Naroff85f0dc52007-10-15 20:41:53 +00001844 }
1845 return true; // should never get here...
1846}
Ted Kremenek738e6c02007-10-31 17:10:13 +00001847
Chris Lattner1d78a862008-04-07 07:01:58 +00001848//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00001849// Integer Predicates
1850//===----------------------------------------------------------------------===//
1851unsigned ASTContext::getIntWidth(QualType T) {
1852 if (T == BoolTy)
1853 return 1;
1854 // At the moment, only bool has padding bits
1855 return (unsigned)getTypeSize(T);
1856}
1857
1858QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
1859 assert(T->isSignedIntegerType() && "Unexpected type");
1860 if (const EnumType* ETy = T->getAsEnumType())
1861 T = ETy->getDecl()->getIntegerType();
1862 const BuiltinType* BTy = T->getAsBuiltinType();
1863 assert (BTy && "Unexpected signed integer type");
1864 switch (BTy->getKind()) {
1865 case BuiltinType::Char_S:
1866 case BuiltinType::SChar:
1867 return UnsignedCharTy;
1868 case BuiltinType::Short:
1869 return UnsignedShortTy;
1870 case BuiltinType::Int:
1871 return UnsignedIntTy;
1872 case BuiltinType::Long:
1873 return UnsignedLongTy;
1874 case BuiltinType::LongLong:
1875 return UnsignedLongLongTy;
1876 default:
1877 assert(0 && "Unexpected signed integer type");
1878 return QualType();
1879 }
1880}
1881
1882
1883//===----------------------------------------------------------------------===//
Chris Lattner1d78a862008-04-07 07:01:58 +00001884// Serialization Support
1885//===----------------------------------------------------------------------===//
1886
Ted Kremenek738e6c02007-10-31 17:10:13 +00001887/// Emit - Serialize an ASTContext object to Bitcode.
1888void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremenek842126e2008-06-04 15:55:15 +00001889 S.Emit(LangOpts);
Ted Kremenek9af4d5c2007-10-31 20:00:03 +00001890 S.EmitRef(SourceMgr);
1891 S.EmitRef(Target);
1892 S.EmitRef(Idents);
1893 S.EmitRef(Selectors);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001894
Ted Kremenek68228a92007-10-31 22:44:07 +00001895 // Emit the size of the type vector so that we can reserve that size
1896 // when we reconstitute the ASTContext object.
Ted Kremenek0199d9f2007-11-06 22:26:16 +00001897 S.EmitInt(Types.size());
1898
Ted Kremenek034a78c2007-11-13 22:02:55 +00001899 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
1900 I!=E;++I)
1901 (*I)->Emit(S);
Ted Kremenek0199d9f2007-11-06 22:26:16 +00001902
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001903 S.EmitOwnedPtr(TUDecl);
1904
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00001905 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001906}
1907
Ted Kremenekacba3612007-11-13 00:25:37 +00001908ASTContext* ASTContext::Create(llvm::Deserializer& D) {
Ted Kremenek842126e2008-06-04 15:55:15 +00001909
1910 // Read the language options.
1911 LangOptions LOpts;
1912 LOpts.Read(D);
1913
Ted Kremenek68228a92007-10-31 22:44:07 +00001914 SourceManager &SM = D.ReadRef<SourceManager>();
1915 TargetInfo &t = D.ReadRef<TargetInfo>();
1916 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
1917 SelectorTable &sels = D.ReadRef<SelectorTable>();
Chris Lattnereee57c02008-04-04 06:12:32 +00001918
Ted Kremenek68228a92007-10-31 22:44:07 +00001919 unsigned size_reserve = D.ReadInt();
1920
Ted Kremenek842126e2008-06-04 15:55:15 +00001921 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels, size_reserve);
Ted Kremenek68228a92007-10-31 22:44:07 +00001922
Ted Kremenek034a78c2007-11-13 22:02:55 +00001923 for (unsigned i = 0; i < size_reserve; ++i)
1924 Type::Create(*A,i,D);
Chris Lattnereee57c02008-04-04 06:12:32 +00001925
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001926 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
1927
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00001928 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
Ted Kremenek68228a92007-10-31 22:44:07 +00001929
1930 return A;
1931}