blob: 816a50b29c4be8d1552317c6fb0876f507fc3809 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
Steve Naroff3fafa102007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/Basic/TargetInfo.h"
18#include "llvm/ADT/SmallVector.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000019#include "llvm/ADT/StringExtras.h"
Ted Kremenek738e6c02007-10-31 17:10:13 +000020#include "llvm/Bitcode/Serialize.h"
21#include "llvm/Bitcode/Deserialize.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000022
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24
25enum FloatingRank {
26 FloatRank, DoubleRank, LongDoubleRank
27};
28
29ASTContext::~ASTContext() {
30 // Deallocate all the types.
31 while (!Types.empty()) {
32 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(Types.back())) {
33 // Destroy the object, but don't call delete. These are malloc'd.
34 FT->~FunctionTypeProto();
35 free(FT);
36 } else {
37 delete Types.back();
38 }
39 Types.pop_back();
40 }
41}
42
43void ASTContext::PrintStats() const {
44 fprintf(stderr, "*** AST Context Stats:\n");
45 fprintf(stderr, " %d types total.\n", (int)Types.size());
46 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
47 unsigned NumVector = 0, NumComplex = 0;
48 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
49
50 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Steve Naroff948fd372007-09-17 14:16:13 +000051 unsigned NumObjcInterfaces = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000052
53 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
54 Type *T = Types[i];
55 if (isa<BuiltinType>(T))
56 ++NumBuiltin;
57 else if (isa<PointerType>(T))
58 ++NumPointer;
59 else if (isa<ReferenceType>(T))
60 ++NumReference;
61 else if (isa<ComplexType>(T))
62 ++NumComplex;
63 else if (isa<ArrayType>(T))
64 ++NumArray;
65 else if (isa<VectorType>(T))
66 ++NumVector;
67 else if (isa<FunctionTypeNoProto>(T))
68 ++NumFunctionNP;
69 else if (isa<FunctionTypeProto>(T))
70 ++NumFunctionP;
71 else if (isa<TypedefType>(T))
72 ++NumTypeName;
73 else if (TagType *TT = dyn_cast<TagType>(T)) {
74 ++NumTagged;
75 switch (TT->getDecl()->getKind()) {
76 default: assert(0 && "Unknown tagged type!");
77 case Decl::Struct: ++NumTagStruct; break;
78 case Decl::Union: ++NumTagUnion; break;
79 case Decl::Class: ++NumTagClass; break;
80 case Decl::Enum: ++NumTagEnum; break;
81 }
Steve Naroff948fd372007-09-17 14:16:13 +000082 } else if (isa<ObjcInterfaceType>(T))
83 ++NumObjcInterfaces;
84 else {
Chris Lattner4b009652007-07-25 00:24:17 +000085 assert(0 && "Unknown type!");
86 }
87 }
88
89 fprintf(stderr, " %d builtin types\n", NumBuiltin);
90 fprintf(stderr, " %d pointer types\n", NumPointer);
91 fprintf(stderr, " %d reference types\n", NumReference);
92 fprintf(stderr, " %d complex types\n", NumComplex);
93 fprintf(stderr, " %d array types\n", NumArray);
94 fprintf(stderr, " %d vector types\n", NumVector);
95 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
96 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
97 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
98 fprintf(stderr, " %d tagged types\n", NumTagged);
99 fprintf(stderr, " %d struct types\n", NumTagStruct);
100 fprintf(stderr, " %d union types\n", NumTagUnion);
101 fprintf(stderr, " %d class types\n", NumTagClass);
102 fprintf(stderr, " %d enum types\n", NumTagEnum);
Steve Naroff948fd372007-09-17 14:16:13 +0000103 fprintf(stderr, " %d interface types\n", NumObjcInterfaces);
Chris Lattner4b009652007-07-25 00:24:17 +0000104 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
105 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
106 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
107 NumFunctionP*sizeof(FunctionTypeProto)+
108 NumFunctionNP*sizeof(FunctionTypeNoProto)+
109 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)));
110}
111
112
113void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
114 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr());
115}
116
Chris Lattner4b009652007-07-25 00:24:17 +0000117void ASTContext::InitBuiltinTypes() {
118 assert(VoidTy.isNull() && "Context reinitialized?");
119
120 // C99 6.2.5p19.
121 InitBuiltinType(VoidTy, BuiltinType::Void);
122
123 // C99 6.2.5p2.
124 InitBuiltinType(BoolTy, BuiltinType::Bool);
125 // C99 6.2.5p3.
126 if (Target.isCharSigned(SourceLocation()))
127 InitBuiltinType(CharTy, BuiltinType::Char_S);
128 else
129 InitBuiltinType(CharTy, BuiltinType::Char_U);
130 // C99 6.2.5p4.
131 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
132 InitBuiltinType(ShortTy, BuiltinType::Short);
133 InitBuiltinType(IntTy, BuiltinType::Int);
134 InitBuiltinType(LongTy, BuiltinType::Long);
135 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
136
137 // C99 6.2.5p6.
138 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
139 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
140 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
141 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
142 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
143
144 // C99 6.2.5p10.
145 InitBuiltinType(FloatTy, BuiltinType::Float);
146 InitBuiltinType(DoubleTy, BuiltinType::Double);
147 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
148
149 // C99 6.2.5p11.
150 FloatComplexTy = getComplexType(FloatTy);
151 DoubleComplexTy = getComplexType(DoubleTy);
152 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Steve Naroff9d12c902007-10-15 14:41:52 +0000153
154 BuiltinVaListType = QualType();
155 ObjcIdType = QualType();
156 IdStructType = 0;
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000157 ObjcClassType = QualType();
158 ClassStructType = 0;
159
Steve Narofff2e30312007-10-15 23:35:17 +0000160 ObjcConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000161
162 // void * type
163 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000164}
165
166//===----------------------------------------------------------------------===//
167// Type Sizing and Analysis
168//===----------------------------------------------------------------------===//
169
170/// getTypeSize - Return the size of the specified type, in bits. This method
171/// does not work on incomplete types.
172std::pair<uint64_t, unsigned>
173ASTContext::getTypeInfo(QualType T, SourceLocation L) {
174 T = T.getCanonicalType();
175 uint64_t Size;
176 unsigned Align;
177 switch (T->getTypeClass()) {
178 case Type::TypeName: assert(0 && "Not a canonical type!");
179 case Type::FunctionNoProto:
180 case Type::FunctionProto:
181 default:
182 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000183 case Type::VariableArray:
184 assert(0 && "VLAs not implemented yet!");
185 case Type::ConstantArray: {
186 ConstantArrayType *CAT = cast<ConstantArrayType>(T);
187
Chris Lattner4b009652007-07-25 00:24:17 +0000188 std::pair<uint64_t, unsigned> EltInfo =
Steve Naroff83c13012007-08-30 01:06:46 +0000189 getTypeInfo(CAT->getElementType(), L);
190 Size = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000191 Align = EltInfo.second;
192 break;
193 }
194 case Type::Vector: {
195 std::pair<uint64_t, unsigned> EltInfo =
196 getTypeInfo(cast<VectorType>(T)->getElementType(), L);
197 Size = EltInfo.first*cast<VectorType>(T)->getNumElements();
198 // FIXME: Vector alignment is not the alignment of its elements.
199 Align = EltInfo.second;
200 break;
201 }
202
203 case Type::Builtin: {
204 // FIXME: need to use TargetInfo to derive the target specific sizes. This
205 // implementation will suffice for play with vector support.
Chris Lattner858eece2007-09-22 18:29:59 +0000206 const llvm::fltSemantics *F;
Chris Lattner4b009652007-07-25 00:24:17 +0000207 switch (cast<BuiltinType>(T)->getKind()) {
208 default: assert(0 && "Unknown builtin type!");
209 case BuiltinType::Void:
210 assert(0 && "Incomplete types have no size!");
211 case BuiltinType::Bool: Target.getBoolInfo(Size, Align, L); break;
212 case BuiltinType::Char_S:
213 case BuiltinType::Char_U:
214 case BuiltinType::UChar:
215 case BuiltinType::SChar: Target.getCharInfo(Size, Align, L); break;
216 case BuiltinType::UShort:
217 case BuiltinType::Short: Target.getShortInfo(Size, Align, L); break;
218 case BuiltinType::UInt:
219 case BuiltinType::Int: Target.getIntInfo(Size, Align, L); break;
220 case BuiltinType::ULong:
221 case BuiltinType::Long: Target.getLongInfo(Size, Align, L); break;
222 case BuiltinType::ULongLong:
223 case BuiltinType::LongLong: Target.getLongLongInfo(Size, Align, L); break;
Chris Lattner858eece2007-09-22 18:29:59 +0000224 case BuiltinType::Float: Target.getFloatInfo(Size, Align, F, L); break;
225 case BuiltinType::Double: Target.getDoubleInfo(Size, Align, F, L);break;
226 case BuiltinType::LongDouble:Target.getLongDoubleInfo(Size,Align,F,L);break;
Chris Lattner4b009652007-07-25 00:24:17 +0000227 }
228 break;
229 }
230 case Type::Pointer: Target.getPointerInfo(Size, Align, L); break;
231 case Type::Reference:
232 // "When applied to a reference or a reference type, the result is the size
233 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
234 // FIXME: This is wrong for struct layout!
235 return getTypeInfo(cast<ReferenceType>(T)->getReferenceeType(), L);
236
237 case Type::Complex: {
238 // Complex types have the same alignment as their elements, but twice the
239 // size.
240 std::pair<uint64_t, unsigned> EltInfo =
241 getTypeInfo(cast<ComplexType>(T)->getElementType(), L);
242 Size = EltInfo.first*2;
243 Align = EltInfo.second;
244 break;
245 }
246 case Type::Tagged:
Chris Lattnereb56d292007-08-27 17:38:00 +0000247 TagType *TT = cast<TagType>(T);
248 if (RecordType *RT = dyn_cast<RecordType>(TT)) {
249 const RecordLayout &Layout = getRecordLayout(RT->getDecl(), L);
250 Size = Layout.getSize();
251 Align = Layout.getAlignment();
252 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(TT->getDecl())) {
Chris Lattner90a018d2007-08-28 18:24:31 +0000253 return getTypeInfo(ED->getIntegerType(), L);
Chris Lattnereb56d292007-08-27 17:38:00 +0000254 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000255 assert(0 && "Unimplemented type sizes!");
Chris Lattnereb56d292007-08-27 17:38:00 +0000256 }
Chris Lattner4b009652007-07-25 00:24:17 +0000257 break;
258 }
259
260 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
261 return std::make_pair(Size, Align);
262}
263
264/// getRecordLayout - Get or compute information about the layout of the
265/// specified record (struct/union/class), which indicates its size and field
266/// position information.
267const RecordLayout &ASTContext::getRecordLayout(const RecordDecl *D,
268 SourceLocation L) {
269 assert(D->isDefinition() && "Cannot get layout of forward declarations!");
270
271 // Look up this layout, if already laid out, return what we have.
272 const RecordLayout *&Entry = RecordLayoutInfo[D];
273 if (Entry) return *Entry;
274
275 // Allocate and assign into RecordLayoutInfo here. The "Entry" reference can
276 // be invalidated (dangle) if the RecordLayoutInfo hashtable is inserted into.
277 RecordLayout *NewEntry = new RecordLayout();
278 Entry = NewEntry;
279
280 uint64_t *FieldOffsets = new uint64_t[D->getNumMembers()];
281 uint64_t RecordSize = 0;
282 unsigned RecordAlign = 8; // Default alignment = 1 byte = 8 bits.
283
284 if (D->getKind() != Decl::Union) {
285 // Layout each field, for now, just sequentially, respecting alignment. In
286 // the future, this will need to be tweakable by targets.
287 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
288 const FieldDecl *FD = D->getMember(i);
289 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType(), L);
290 uint64_t FieldSize = FieldInfo.first;
291 unsigned FieldAlign = FieldInfo.second;
292
293 // Round up the current record size to the field's alignment boundary.
294 RecordSize = (RecordSize+FieldAlign-1) & ~(FieldAlign-1);
295
296 // Place this field at the current location.
297 FieldOffsets[i] = RecordSize;
298
299 // Reserve space for this field.
300 RecordSize += FieldSize;
301
302 // Remember max struct/class alignment.
303 RecordAlign = std::max(RecordAlign, FieldAlign);
304 }
305
306 // Finally, round the size of the total struct up to the alignment of the
307 // struct itself.
308 RecordSize = (RecordSize+RecordAlign-1) & ~(RecordAlign-1);
309 } else {
310 // Union layout just puts each member at the start of the record.
311 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
312 const FieldDecl *FD = D->getMember(i);
313 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType(), L);
314 uint64_t FieldSize = FieldInfo.first;
315 unsigned FieldAlign = FieldInfo.second;
316
317 // Round up the current record size to the field's alignment boundary.
318 RecordSize = std::max(RecordSize, FieldSize);
319
320 // Place this field at the start of the record.
321 FieldOffsets[i] = 0;
322
323 // Remember max struct/class alignment.
324 RecordAlign = std::max(RecordAlign, FieldAlign);
325 }
326 }
327
328 NewEntry->SetLayout(RecordSize, RecordAlign, FieldOffsets);
329 return *NewEntry;
330}
331
Chris Lattner4b009652007-07-25 00:24:17 +0000332//===----------------------------------------------------------------------===//
333// Type creation/memoization methods
334//===----------------------------------------------------------------------===//
335
336
337/// getComplexType - Return the uniqued reference to the type for a complex
338/// number with the specified element type.
339QualType ASTContext::getComplexType(QualType T) {
340 // Unique pointers, to guarantee there is only one pointer of a particular
341 // structure.
342 llvm::FoldingSetNodeID ID;
343 ComplexType::Profile(ID, T);
344
345 void *InsertPos = 0;
346 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
347 return QualType(CT, 0);
348
349 // If the pointee type isn't canonical, this won't be a canonical type either,
350 // so fill in the canonical type field.
351 QualType Canonical;
352 if (!T->isCanonical()) {
353 Canonical = getComplexType(T.getCanonicalType());
354
355 // Get the new insert position for the node we care about.
356 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
357 assert(NewIP == 0 && "Shouldn't be in the map!");
358 }
359 ComplexType *New = new ComplexType(T, Canonical);
360 Types.push_back(New);
361 ComplexTypes.InsertNode(New, InsertPos);
362 return QualType(New, 0);
363}
364
365
366/// getPointerType - Return the uniqued reference to the type for a pointer to
367/// the specified type.
368QualType ASTContext::getPointerType(QualType T) {
369 // Unique pointers, to guarantee there is only one pointer of a particular
370 // structure.
371 llvm::FoldingSetNodeID ID;
372 PointerType::Profile(ID, T);
373
374 void *InsertPos = 0;
375 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
376 return QualType(PT, 0);
377
378 // If the pointee type isn't canonical, this won't be a canonical type either,
379 // so fill in the canonical type field.
380 QualType Canonical;
381 if (!T->isCanonical()) {
382 Canonical = getPointerType(T.getCanonicalType());
383
384 // Get the new insert position for the node we care about.
385 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
386 assert(NewIP == 0 && "Shouldn't be in the map!");
387 }
388 PointerType *New = new PointerType(T, Canonical);
389 Types.push_back(New);
390 PointerTypes.InsertNode(New, InsertPos);
391 return QualType(New, 0);
392}
393
394/// getReferenceType - Return the uniqued reference to the type for a reference
395/// to the specified type.
396QualType ASTContext::getReferenceType(QualType T) {
397 // Unique pointers, to guarantee there is only one pointer of a particular
398 // structure.
399 llvm::FoldingSetNodeID ID;
400 ReferenceType::Profile(ID, T);
401
402 void *InsertPos = 0;
403 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
404 return QualType(RT, 0);
405
406 // If the referencee type isn't canonical, this won't be a canonical type
407 // either, so fill in the canonical type field.
408 QualType Canonical;
409 if (!T->isCanonical()) {
410 Canonical = getReferenceType(T.getCanonicalType());
411
412 // Get the new insert position for the node we care about.
413 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
414 assert(NewIP == 0 && "Shouldn't be in the map!");
415 }
416
417 ReferenceType *New = new ReferenceType(T, Canonical);
418 Types.push_back(New);
419 ReferenceTypes.InsertNode(New, InsertPos);
420 return QualType(New, 0);
421}
422
Steve Naroff83c13012007-08-30 01:06:46 +0000423/// getConstantArrayType - Return the unique reference to the type for an
424/// array of the specified element type.
425QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +0000426 const llvm::APInt &ArySize,
427 ArrayType::ArraySizeModifier ASM,
428 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +0000429 llvm::FoldingSetNodeID ID;
Steve Naroff83c13012007-08-30 01:06:46 +0000430 ConstantArrayType::Profile(ID, EltTy, ArySize);
Chris Lattner4b009652007-07-25 00:24:17 +0000431
432 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +0000433 if (ConstantArrayType *ATP =
434 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000435 return QualType(ATP, 0);
436
437 // If the element type isn't canonical, this won't be a canonical type either,
438 // so fill in the canonical type field.
439 QualType Canonical;
440 if (!EltTy->isCanonical()) {
Steve Naroff24c9b982007-08-30 18:10:14 +0000441 Canonical = getConstantArrayType(EltTy.getCanonicalType(), ArySize,
442 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +0000443 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +0000444 ConstantArrayType *NewIP =
445 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
446
Chris Lattner4b009652007-07-25 00:24:17 +0000447 assert(NewIP == 0 && "Shouldn't be in the map!");
448 }
449
Steve Naroff24c9b982007-08-30 18:10:14 +0000450 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
451 ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +0000452 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000453 Types.push_back(New);
454 return QualType(New, 0);
455}
456
Steve Naroffe2579e32007-08-30 18:14:25 +0000457/// getVariableArrayType - Returns a non-unique reference to the type for a
458/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +0000459QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
460 ArrayType::ArraySizeModifier ASM,
461 unsigned EltTypeQuals) {
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000462 if (NumElts) {
463 // Since we don't unique expressions, it isn't possible to unique VLA's
464 // that have an expression provided for their size.
465
Ted Kremenek2058dc42007-10-30 16:41:53 +0000466 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
467 ASM, EltTypeQuals);
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000468
Ted Kremenek2058dc42007-10-30 16:41:53 +0000469 CompleteVariableArrayTypes.push_back(New);
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000470 Types.push_back(New);
471 return QualType(New, 0);
472 }
473 else {
474 // No size is provided for the VLA. These we can unique.
475 llvm::FoldingSetNodeID ID;
476 VariableArrayType::Profile(ID, EltTy);
477
478 void *InsertPos = 0;
479 if (VariableArrayType *ATP =
480 IncompleteVariableArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
481 return QualType(ATP, 0);
482
483 // If the element type isn't canonical, this won't be a canonical type
484 // either, so fill in the canonical type field.
485 QualType Canonical;
486
487 if (!EltTy->isCanonical()) {
488 Canonical = getVariableArrayType(EltTy.getCanonicalType(), NumElts,
489 ASM, EltTypeQuals);
490
491 // Get the new insert position for the node we care about.
492 VariableArrayType *NewIP =
493 IncompleteVariableArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
494
495 assert(NewIP == 0 && "Shouldn't be in the map!");
496 }
497
498 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
499 ASM, EltTypeQuals);
500
501 IncompleteVariableArrayTypes.InsertNode(New, InsertPos);
502 Types.push_back(New);
503 return QualType(New, 0);
504 }
Steve Naroff83c13012007-08-30 01:06:46 +0000505}
506
Chris Lattner4b009652007-07-25 00:24:17 +0000507/// getVectorType - Return the unique reference to a vector type of
508/// the specified element type and size. VectorType must be a built-in type.
509QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
510 BuiltinType *baseType;
511
512 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
513 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
514
515 // Check if we've already instantiated a vector of this type.
516 llvm::FoldingSetNodeID ID;
517 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
518 void *InsertPos = 0;
519 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
520 return QualType(VTP, 0);
521
522 // If the element type isn't canonical, this won't be a canonical type either,
523 // so fill in the canonical type field.
524 QualType Canonical;
525 if (!vecType->isCanonical()) {
526 Canonical = getVectorType(vecType.getCanonicalType(), NumElts);
527
528 // Get the new insert position for the node we care about.
529 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
530 assert(NewIP == 0 && "Shouldn't be in the map!");
531 }
532 VectorType *New = new VectorType(vecType, NumElts, Canonical);
533 VectorTypes.InsertNode(New, InsertPos);
534 Types.push_back(New);
535 return QualType(New, 0);
536}
537
538/// getOCUVectorType - Return the unique reference to an OCU vector type of
539/// the specified element type and size. VectorType must be a built-in type.
540QualType ASTContext::getOCUVectorType(QualType vecType, unsigned NumElts) {
541 BuiltinType *baseType;
542
543 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
544 assert(baseType != 0 && "getOCUVectorType(): Expecting a built-in type");
545
546 // Check if we've already instantiated a vector of this type.
547 llvm::FoldingSetNodeID ID;
548 VectorType::Profile(ID, vecType, NumElts, Type::OCUVector);
549 void *InsertPos = 0;
550 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
551 return QualType(VTP, 0);
552
553 // If the element type isn't canonical, this won't be a canonical type either,
554 // so fill in the canonical type field.
555 QualType Canonical;
556 if (!vecType->isCanonical()) {
557 Canonical = getOCUVectorType(vecType.getCanonicalType(), NumElts);
558
559 // Get the new insert position for the node we care about.
560 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
561 assert(NewIP == 0 && "Shouldn't be in the map!");
562 }
563 OCUVectorType *New = new OCUVectorType(vecType, NumElts, Canonical);
564 VectorTypes.InsertNode(New, InsertPos);
565 Types.push_back(New);
566 return QualType(New, 0);
567}
568
569/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
570///
571QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
572 // Unique functions, to guarantee there is only one function of a particular
573 // structure.
574 llvm::FoldingSetNodeID ID;
575 FunctionTypeNoProto::Profile(ID, ResultTy);
576
577 void *InsertPos = 0;
578 if (FunctionTypeNoProto *FT =
579 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
580 return QualType(FT, 0);
581
582 QualType Canonical;
583 if (!ResultTy->isCanonical()) {
584 Canonical = getFunctionTypeNoProto(ResultTy.getCanonicalType());
585
586 // Get the new insert position for the node we care about.
587 FunctionTypeNoProto *NewIP =
588 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
589 assert(NewIP == 0 && "Shouldn't be in the map!");
590 }
591
592 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
593 Types.push_back(New);
594 FunctionTypeProtos.InsertNode(New, InsertPos);
595 return QualType(New, 0);
596}
597
598/// getFunctionType - Return a normal function type with a typed argument
599/// list. isVariadic indicates whether the argument list includes '...'.
600QualType ASTContext::getFunctionType(QualType ResultTy, QualType *ArgArray,
601 unsigned NumArgs, bool isVariadic) {
602 // Unique functions, to guarantee there is only one function of a particular
603 // structure.
604 llvm::FoldingSetNodeID ID;
605 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic);
606
607 void *InsertPos = 0;
608 if (FunctionTypeProto *FTP =
609 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
610 return QualType(FTP, 0);
611
612 // Determine whether the type being created is already canonical or not.
613 bool isCanonical = ResultTy->isCanonical();
614 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
615 if (!ArgArray[i]->isCanonical())
616 isCanonical = false;
617
618 // If this type isn't canonical, get the canonical version of it.
619 QualType Canonical;
620 if (!isCanonical) {
621 llvm::SmallVector<QualType, 16> CanonicalArgs;
622 CanonicalArgs.reserve(NumArgs);
623 for (unsigned i = 0; i != NumArgs; ++i)
624 CanonicalArgs.push_back(ArgArray[i].getCanonicalType());
625
626 Canonical = getFunctionType(ResultTy.getCanonicalType(),
627 &CanonicalArgs[0], NumArgs,
628 isVariadic);
629
630 // Get the new insert position for the node we care about.
631 FunctionTypeProto *NewIP =
632 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
633 assert(NewIP == 0 && "Shouldn't be in the map!");
634 }
635
636 // FunctionTypeProto objects are not allocated with new because they have a
637 // variable size array (for parameter types) at the end of them.
638 FunctionTypeProto *FTP =
639 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) +
640 NumArgs*sizeof(QualType));
641 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
642 Canonical);
643 Types.push_back(FTP);
644 FunctionTypeProtos.InsertNode(FTP, InsertPos);
645 return QualType(FTP, 0);
646}
647
648/// getTypedefType - Return the unique reference to the type for the
649/// specified typename decl.
650QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
651 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
652
653 QualType Canonical = Decl->getUnderlyingType().getCanonicalType();
654 Decl->TypeForDecl = new TypedefType(Decl, Canonical);
655 Types.push_back(Decl->TypeForDecl);
656 return QualType(Decl->TypeForDecl, 0);
657}
658
Steve Naroff81f1bba2007-09-06 21:24:23 +0000659/// getObjcInterfaceType - Return the unique reference to the type for the
660/// specified ObjC interface decl.
661QualType ASTContext::getObjcInterfaceType(ObjcInterfaceDecl *Decl) {
662 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
663
664 Decl->TypeForDecl = new ObjcInterfaceType(Decl);
665 Types.push_back(Decl->TypeForDecl);
666 return QualType(Decl->TypeForDecl, 0);
667}
668
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000669/// getObjcQualifiedInterfaceType - Return a
670/// ObjcQualifiedInterfaceType type for the given interface decl and
671/// the conforming protocol list.
672QualType ASTContext::getObjcQualifiedInterfaceType(ObjcInterfaceDecl *Decl,
673 ObjcProtocolDecl **Protocols, unsigned NumProtocols) {
674 ObjcInterfaceType *IType =
675 cast<ObjcInterfaceType>(getObjcInterfaceType(Decl));
676
677 llvm::FoldingSetNodeID ID;
678 ObjcQualifiedInterfaceType::Profile(ID, IType, Protocols, NumProtocols);
679
680 void *InsertPos = 0;
681 if (ObjcQualifiedInterfaceType *QT =
682 ObjcQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
683 return QualType(QT, 0);
684
685 // No Match;
Chris Lattnerd855a6e2007-10-11 03:36:41 +0000686 ObjcQualifiedInterfaceType *QType =
687 new ObjcQualifiedInterfaceType(IType, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000688 Types.push_back(QType);
689 ObjcQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
690 return QualType(QType, 0);
691}
692
Steve Naroff0604dd92007-08-01 18:02:17 +0000693/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
694/// TypeOfExpr AST's (since expression's are never shared). For example,
695/// multiple declarations that refer to "typeof(x)" all contain different
696/// DeclRefExpr's. This doesn't effect the type checker, since it operates
697/// on canonical type's (which are always unique).
Steve Naroff11b649c2007-08-01 17:20:42 +0000698QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
Steve Naroff7cbb1462007-07-31 12:34:36 +0000699 QualType Canonical = tofExpr->getType().getCanonicalType();
Steve Naroff0604dd92007-08-01 18:02:17 +0000700 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
701 Types.push_back(toe);
702 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000703}
704
Steve Naroff0604dd92007-08-01 18:02:17 +0000705/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
706/// TypeOfType AST's. The only motivation to unique these nodes would be
707/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
708/// an issue. This doesn't effect the type checker, since it operates
709/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +0000710QualType ASTContext::getTypeOfType(QualType tofType) {
711 QualType Canonical = tofType.getCanonicalType();
Steve Naroff0604dd92007-08-01 18:02:17 +0000712 TypeOfType *tot = new TypeOfType(tofType, Canonical);
713 Types.push_back(tot);
714 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000715}
716
Chris Lattner4b009652007-07-25 00:24:17 +0000717/// getTagDeclType - Return the unique reference to the type for the
718/// specified TagDecl (struct/union/class/enum) decl.
719QualType ASTContext::getTagDeclType(TagDecl *Decl) {
720 // The decl stores the type cache.
721 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
722
723 Decl->TypeForDecl = new TagType(Decl, QualType());
724 Types.push_back(Decl->TypeForDecl);
725 return QualType(Decl->TypeForDecl, 0);
726}
727
728/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
729/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
730/// needs to agree with the definition in <stddef.h>.
731QualType ASTContext::getSizeType() const {
732 // On Darwin, size_t is defined as a "long unsigned int".
733 // FIXME: should derive from "Target".
734 return UnsignedLongTy;
735}
736
737/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
738/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
739QualType ASTContext::getPointerDiffType() const {
740 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug...
741 // FIXME: should derive from "Target".
742 return IntTy;
743}
744
745/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
746/// routine will assert if passed a built-in type that isn't an integer or enum.
747static int getIntegerRank(QualType t) {
748 if (const TagType *TT = dyn_cast<TagType>(t.getCanonicalType())) {
749 assert(TT->getDecl()->getKind() == Decl::Enum && "not an int or enum");
750 return 4;
751 }
752
753 const BuiltinType *BT = cast<BuiltinType>(t.getCanonicalType());
754 switch (BT->getKind()) {
755 default:
756 assert(0 && "getIntegerRank(): not a built-in integer");
757 case BuiltinType::Bool:
758 return 1;
759 case BuiltinType::Char_S:
760 case BuiltinType::Char_U:
761 case BuiltinType::SChar:
762 case BuiltinType::UChar:
763 return 2;
764 case BuiltinType::Short:
765 case BuiltinType::UShort:
766 return 3;
767 case BuiltinType::Int:
768 case BuiltinType::UInt:
769 return 4;
770 case BuiltinType::Long:
771 case BuiltinType::ULong:
772 return 5;
773 case BuiltinType::LongLong:
774 case BuiltinType::ULongLong:
775 return 6;
776 }
777}
778
779/// getFloatingRank - Return a relative rank for floating point types.
780/// This routine will assert if passed a built-in type that isn't a float.
781static int getFloatingRank(QualType T) {
782 T = T.getCanonicalType();
783 if (ComplexType *CT = dyn_cast<ComplexType>(T))
784 return getFloatingRank(CT->getElementType());
785
786 switch (cast<BuiltinType>(T)->getKind()) {
787 default: assert(0 && "getFloatingPointRank(): not a floating type");
788 case BuiltinType::Float: return FloatRank;
789 case BuiltinType::Double: return DoubleRank;
790 case BuiltinType::LongDouble: return LongDoubleRank;
791 }
792}
793
Steve Narofffa0c4532007-08-27 01:41:48 +0000794/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
795/// point or a complex type (based on typeDomain/typeSize).
796/// 'typeDomain' is a real floating point or complex type.
797/// 'typeSize' is a real floating point or complex type.
Steve Naroff3cf497f2007-08-27 01:27:54 +0000798QualType ASTContext::getFloatingTypeOfSizeWithinDomain(
799 QualType typeSize, QualType typeDomain) const {
800 if (typeDomain->isComplexType()) {
801 switch (getFloatingRank(typeSize)) {
Steve Narofffa0c4532007-08-27 01:41:48 +0000802 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +0000803 case FloatRank: return FloatComplexTy;
804 case DoubleRank: return DoubleComplexTy;
805 case LongDoubleRank: return LongDoubleComplexTy;
806 }
Chris Lattner4b009652007-07-25 00:24:17 +0000807 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000808 if (typeDomain->isRealFloatingType()) {
809 switch (getFloatingRank(typeSize)) {
Steve Narofffa0c4532007-08-27 01:41:48 +0000810 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +0000811 case FloatRank: return FloatTy;
812 case DoubleRank: return DoubleTy;
813 case LongDoubleRank: return LongDoubleTy;
814 }
815 }
816 assert(0 && "getFloatingTypeOfSizeWithinDomain(): illegal domain");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000817 //an invalid return value, but the assert
818 //will ensure that this code is never reached.
819 return VoidTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000820}
821
Steve Naroff45fc9822007-08-27 15:30:22 +0000822/// compareFloatingType - Handles 3 different combos:
823/// float/float, float/complex, complex/complex.
824/// If lt > rt, return 1. If lt == rt, return 0. If lt < rt, return -1.
825int ASTContext::compareFloatingType(QualType lt, QualType rt) {
826 if (getFloatingRank(lt) == getFloatingRank(rt))
827 return 0;
828 if (getFloatingRank(lt) > getFloatingRank(rt))
829 return 1;
830 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +0000831}
832
833// maxIntegerType - Returns the highest ranked integer type. Handles 3 case:
834// unsigned/unsigned, signed/signed, signed/unsigned. C99 6.3.1.8p1.
835QualType ASTContext::maxIntegerType(QualType lhs, QualType rhs) {
836 if (lhs == rhs) return lhs;
837
838 bool t1Unsigned = lhs->isUnsignedIntegerType();
839 bool t2Unsigned = rhs->isUnsignedIntegerType();
840
841 if ((t1Unsigned && t2Unsigned) || (!t1Unsigned && !t2Unsigned))
842 return getIntegerRank(lhs) >= getIntegerRank(rhs) ? lhs : rhs;
843
844 // We have two integer types with differing signs
845 QualType unsignedType = t1Unsigned ? lhs : rhs;
846 QualType signedType = t1Unsigned ? rhs : lhs;
847
848 if (getIntegerRank(unsignedType) >= getIntegerRank(signedType))
849 return unsignedType;
850 else {
851 // FIXME: Need to check if the signed type can represent all values of the
852 // unsigned type. If it can, then the result is the signed type.
853 // If it can't, then the result is the unsigned version of the signed type.
854 // Should probably add a helper that returns a signed integer type from
855 // an unsigned (and vice versa). C99 6.3.1.8.
856 return signedType;
857 }
858}
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000859
860// getCFConstantStringType - Return the type used for constant CFStrings.
861QualType ASTContext::getCFConstantStringType() {
862 if (!CFConstantStringTypeDecl) {
863 CFConstantStringTypeDecl = new RecordDecl(Decl::Struct, SourceLocation(),
864 &Idents.get("__builtin_CFString"),
865 0);
866
867 QualType FieldTypes[4];
868
869 // const int *isa;
870 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
871 // int flags;
872 FieldTypes[1] = IntTy;
873 // const char *str;
874 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
875 // long length;
876 FieldTypes[3] = LongTy;
877 // Create fields
878 FieldDecl *FieldDecls[4];
879
880 for (unsigned i = 0; i < 4; ++i)
Steve Naroffdc1ad762007-09-14 02:20:46 +0000881 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000882
883 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
884 }
885
886 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +0000887}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000888
Anders Carlssone3f02572007-10-29 06:33:42 +0000889// This returns true if a type has been typedefed to BOOL:
890// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +0000891static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +0000892 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnercb034cb2007-10-30 20:27:44 +0000893 return !strcmp(TT->getDecl()->getName(), "BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +0000894
895 return false;
896}
897
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000898/// getObjcEncodingTypeSize returns size of type for objective-c encoding
899/// purpose.
900int ASTContext::getObjcEncodingTypeSize(QualType type) {
901 SourceLocation Loc;
902 uint64_t sz = getTypeSize(type, Loc);
903
904 // Make all integer and enum types at least as large as an int
905 if (sz > 0 && type->isIntegralType())
906 sz = std::max(sz, getTypeSize(IntTy, Loc));
907 // Treat arrays as pointers, since that's how they're passed in.
908 else if (type->isArrayType())
909 sz = getTypeSize(VoidPtrTy, Loc);
910 return sz / getTypeSize(CharTy, Loc);
911}
912
913/// getObjcEncodingForMethodDecl - Return the encoded type for this method
914/// declaration.
915void ASTContext::getObjcEncodingForMethodDecl(ObjcMethodDecl *Decl,
916 std::string& S)
917{
918 // TODO: First encode type qualifer, 'in', 'inout', etc. for the return type.
919 // Encode result type.
920 getObjcEncodingForType(Decl->getResultType(), S);
921 // Compute size of all parameters.
922 // Start with computing size of a pointer in number of bytes.
923 // FIXME: There might(should) be a better way of doing this computation!
924 SourceLocation Loc;
925 int PtrSize = getTypeSize(VoidPtrTy, Loc) / getTypeSize(CharTy, Loc);
926 // The first two arguments (self and _cmd) are pointers; account for
927 // their size.
928 int ParmOffset = 2 * PtrSize;
929 int NumOfParams = Decl->getNumParams();
930 for (int i = 0; i < NumOfParams; i++) {
931 QualType PType = Decl->getParamDecl(i)->getType();
932 int sz = getObjcEncodingTypeSize (PType);
933 assert (sz > 0 && "getObjcEncodingForMethodDecl - Incomplete param type");
934 ParmOffset += sz;
935 }
936 S += llvm::utostr(ParmOffset);
937 S += "@0:";
938 S += llvm::utostr(PtrSize);
939
940 // Argument types.
941 ParmOffset = 2 * PtrSize;
942 for (int i = 0; i < NumOfParams; i++) {
943 QualType PType = Decl->getParamDecl(i)->getType();
944 // TODO: Process argument qualifiers for user supplied arguments; such as,
945 // 'in', 'inout', etc.
946 getObjcEncodingForType(PType, S);
947 S += llvm::utostr(ParmOffset);
948 ParmOffset += getObjcEncodingTypeSize(PType);
949 }
950}
951
Anders Carlsson36f07d82007-10-29 05:01:08 +0000952void ASTContext::getObjcEncodingForType(QualType T, std::string& S) const
953{
Anders Carlssone3f02572007-10-29 06:33:42 +0000954 // FIXME: This currently doesn't encode:
955 // @ An object (whether statically typed or typed id)
956 // # A class object (Class)
957 // : A method selector (SEL)
958 // {name=type...} A structure
959 // (name=type...) A union
960 // bnum A bit field of num bits
961
962 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000963 char encoding;
964 switch (BT->getKind()) {
965 case BuiltinType::Void:
966 encoding = 'v';
967 break;
968 case BuiltinType::Bool:
969 encoding = 'B';
970 break;
971 case BuiltinType::Char_U:
972 case BuiltinType::UChar:
973 encoding = 'C';
974 break;
975 case BuiltinType::UShort:
976 encoding = 'S';
977 break;
978 case BuiltinType::UInt:
979 encoding = 'I';
980 break;
981 case BuiltinType::ULong:
982 encoding = 'L';
983 break;
984 case BuiltinType::ULongLong:
985 encoding = 'Q';
986 break;
987 case BuiltinType::Char_S:
988 case BuiltinType::SChar:
989 encoding = 'c';
990 break;
991 case BuiltinType::Short:
992 encoding = 's';
993 break;
994 case BuiltinType::Int:
995 encoding = 'i';
996 break;
997 case BuiltinType::Long:
998 encoding = 'l';
999 break;
1000 case BuiltinType::LongLong:
1001 encoding = 'q';
1002 break;
1003 case BuiltinType::Float:
1004 encoding = 'f';
1005 break;
1006 case BuiltinType::Double:
1007 encoding = 'd';
1008 break;
1009 case BuiltinType::LongDouble:
1010 encoding = 'd';
1011 break;
1012 default:
1013 assert(0 && "Unhandled builtin type kind");
1014 }
1015
1016 S += encoding;
Anders Carlssone3f02572007-10-29 06:33:42 +00001017 } else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001018 QualType PointeeTy = PT->getPointeeType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001019 if (isObjcIdType(PointeeTy) || PointeeTy->isObjcInterfaceType()) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001020 S += '@';
1021 return;
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001022 } else if (isObjcClassType(PointeeTy)) {
1023 S += '#';
1024 return;
1025 } else if (isObjcSelType(PointeeTy)) {
1026 S += ':';
1027 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001028 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00001029
1030 if (PointeeTy->isCharType()) {
1031 // char pointer types should be encoded as '*' unless it is a
1032 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00001033 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001034 S += '*';
1035 return;
1036 }
1037 }
1038
1039 S += '^';
1040 getObjcEncodingForType(PT->getPointeeType(), S);
Anders Carlssone3f02572007-10-29 06:33:42 +00001041 } else if (const ArrayType *AT = T->getAsArrayType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001042 S += '[';
1043
1044 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1045 S += llvm::utostr(CAT->getSize().getZExtValue());
1046 else
1047 assert(0 && "Unhandled array type!");
1048
1049 getObjcEncodingForType(AT->getElementType(), S);
1050 S += ']';
Anders Carlsson5695bb72007-10-30 00:06:20 +00001051 } else if (T->getAsFunctionType()) {
1052 S += '?';
Anders Carlsson36f07d82007-10-29 05:01:08 +00001053 } else
Anders Carlssone3f02572007-10-29 06:33:42 +00001054 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001055}
1056
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001057void ASTContext::setBuiltinVaListType(QualType T)
1058{
1059 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1060
1061 BuiltinVaListType = T;
1062}
1063
Steve Naroff9d12c902007-10-15 14:41:52 +00001064void ASTContext::setObjcIdType(TypedefDecl *TD)
1065{
1066 assert(ObjcIdType.isNull() && "'id' type already set!");
1067
1068 ObjcIdType = getTypedefType(TD);
1069
1070 // typedef struct objc_object *id;
1071 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1072 assert(ptr && "'id' incorrectly typed");
1073 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1074 assert(rec && "'id' incorrectly typed");
1075 IdStructType = rec;
1076}
1077
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001078void ASTContext::setObjcSelType(TypedefDecl *TD)
1079{
1080 assert(ObjcSelType.isNull() && "'SEL' type already set!");
1081
1082 ObjcSelType = getTypedefType(TD);
1083
1084 // typedef struct objc_selector *SEL;
1085 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1086 assert(ptr && "'SEL' incorrectly typed");
1087 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1088 assert(rec && "'SEL' incorrectly typed");
1089 SelStructType = rec;
1090}
1091
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001092void ASTContext::setObjcProtoType(TypedefDecl *TD)
1093{
1094 assert(ObjcProtoType.isNull() && "'Protocol' type already set!");
1095
1096 // typedef struct Protocol Protocol;
1097 ObjcProtoType = TD->getUnderlyingType();
1098 // Protocol * type
1099 ObjcProtoType = getPointerType(ObjcProtoType);
1100 ProtoStructType = TD->getUnderlyingType()->getAsStructureType();
1101}
1102
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00001103void ASTContext::setObjcClassType(TypedefDecl *TD)
1104{
1105 assert(ObjcClassType.isNull() && "'Class' type already set!");
1106
1107 ObjcClassType = getTypedefType(TD);
1108
1109 // typedef struct objc_class *Class;
1110 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1111 assert(ptr && "'Class' incorrectly typed");
1112 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1113 assert(rec && "'Class' incorrectly typed");
1114 ClassStructType = rec;
1115}
1116
Steve Narofff2e30312007-10-15 23:35:17 +00001117void ASTContext::setObjcConstantStringInterface(ObjcInterfaceDecl *Decl) {
1118 assert(ObjcConstantStringType.isNull() &&
1119 "'NSConstantString' type already set!");
1120
1121 ObjcConstantStringType = getObjcInterfaceType(Decl);
1122}
1123
Steve Naroff85f0dc52007-10-15 20:41:53 +00001124bool ASTContext::builtinTypesAreCompatible(QualType lhs, QualType rhs) {
1125 const BuiltinType *lBuiltin = lhs->getAsBuiltinType();
1126 const BuiltinType *rBuiltin = rhs->getAsBuiltinType();
1127
1128 return lBuiltin->getKind() == rBuiltin->getKind();
1129}
1130
1131
1132bool ASTContext::objcTypesAreCompatible(QualType lhs, QualType rhs) {
1133 if (lhs->isObjcInterfaceType() && isObjcIdType(rhs))
1134 return true;
1135 else if (isObjcIdType(lhs) && rhs->isObjcInterfaceType())
1136 return true;
1137 return false;
1138}
1139
1140bool ASTContext::interfaceTypesAreCompatible(QualType lhs, QualType rhs) {
1141 return true; // FIXME: IMPLEMENT.
1142}
1143
1144// C99 6.2.7p1: If both are complete types, then the following additional
1145// requirements apply...FIXME (handle compatibility across source files).
1146bool ASTContext::tagTypesAreCompatible(QualType lhs, QualType rhs) {
1147 TagDecl *ldecl = cast<TagType>(lhs.getCanonicalType())->getDecl();
1148 TagDecl *rdecl = cast<TagType>(rhs.getCanonicalType())->getDecl();
1149
1150 if (ldecl->getKind() == Decl::Struct && rdecl->getKind() == Decl::Struct) {
1151 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1152 return true;
1153 }
1154 if (ldecl->getKind() == Decl::Union && rdecl->getKind() == Decl::Union) {
1155 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1156 return true;
1157 }
1158 return false;
1159}
1160
1161bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) {
1162 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be
1163 // identically qualified and both shall be pointers to compatible types.
1164 if (lhs.getQualifiers() != rhs.getQualifiers())
1165 return false;
1166
1167 QualType ltype = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
1168 QualType rtype = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
1169
1170 return typesAreCompatible(ltype, rtype);
1171}
1172
1173// C++ 5.17p6: When the left opperand of an assignment operator denotes a
1174// reference to T, the operation assigns to the object of type T denoted by the
1175// reference.
1176bool ASTContext::referenceTypesAreCompatible(QualType lhs, QualType rhs) {
1177 QualType ltype = lhs;
1178
1179 if (lhs->isReferenceType())
1180 ltype = cast<ReferenceType>(lhs.getCanonicalType())->getReferenceeType();
1181
1182 QualType rtype = rhs;
1183
1184 if (rhs->isReferenceType())
1185 rtype = cast<ReferenceType>(rhs.getCanonicalType())->getReferenceeType();
1186
1187 return typesAreCompatible(ltype, rtype);
1188}
1189
1190bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) {
1191 const FunctionType *lbase = cast<FunctionType>(lhs.getCanonicalType());
1192 const FunctionType *rbase = cast<FunctionType>(rhs.getCanonicalType());
1193 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1194 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1195
1196 // first check the return types (common between C99 and K&R).
1197 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType()))
1198 return false;
1199
1200 if (lproto && rproto) { // two C99 style function prototypes
1201 unsigned lproto_nargs = lproto->getNumArgs();
1202 unsigned rproto_nargs = rproto->getNumArgs();
1203
1204 if (lproto_nargs != rproto_nargs)
1205 return false;
1206
1207 // both prototypes have the same number of arguments.
1208 if ((lproto->isVariadic() && !rproto->isVariadic()) ||
1209 (rproto->isVariadic() && !lproto->isVariadic()))
1210 return false;
1211
1212 // The use of ellipsis agree...now check the argument types.
1213 for (unsigned i = 0; i < lproto_nargs; i++)
1214 if (!typesAreCompatible(lproto->getArgType(i), rproto->getArgType(i)))
1215 return false;
1216 return true;
1217 }
1218 if (!lproto && !rproto) // two K&R style function decls, nothing to do.
1219 return true;
1220
1221 // we have a mixture of K&R style with C99 prototypes
1222 const FunctionTypeProto *proto = lproto ? lproto : rproto;
1223
1224 if (proto->isVariadic())
1225 return false;
1226
1227 // FIXME: Each parameter type T in the prototype must be compatible with the
1228 // type resulting from applying the usual argument conversions to T.
1229 return true;
1230}
1231
1232bool ASTContext::arrayTypesAreCompatible(QualType lhs, QualType rhs) {
1233 QualType ltype = cast<ArrayType>(lhs.getCanonicalType())->getElementType();
1234 QualType rtype = cast<ArrayType>(rhs.getCanonicalType())->getElementType();
1235
1236 if (!typesAreCompatible(ltype, rtype))
1237 return false;
1238
1239 // FIXME: If both types specify constant sizes, then the sizes must also be
1240 // the same. Even if the sizes are the same, GCC produces an error.
1241 return true;
1242}
1243
1244/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1245/// both shall have the identically qualified version of a compatible type.
1246/// C99 6.2.7p1: Two types have compatible types if their types are the
1247/// same. See 6.7.[2,3,5] for additional rules.
1248bool ASTContext::typesAreCompatible(QualType lhs, QualType rhs) {
1249 QualType lcanon = lhs.getCanonicalType();
1250 QualType rcanon = rhs.getCanonicalType();
1251
1252 // If two types are identical, they are are compatible
1253 if (lcanon == rcanon)
1254 return true;
1255
1256 // If the canonical type classes don't match, they can't be compatible
1257 if (lcanon->getTypeClass() != rcanon->getTypeClass()) {
1258 // For Objective-C, it is possible for two types to be compatible
1259 // when their classes don't match (when dealing with "id"). If either type
1260 // is an interface, we defer to objcTypesAreCompatible().
1261 if (lcanon->isObjcInterfaceType() || rcanon->isObjcInterfaceType())
1262 return objcTypesAreCompatible(lcanon, rcanon);
1263 return false;
1264 }
1265 switch (lcanon->getTypeClass()) {
1266 case Type::Pointer:
1267 return pointerTypesAreCompatible(lcanon, rcanon);
1268 case Type::Reference:
1269 return referenceTypesAreCompatible(lcanon, rcanon);
1270 case Type::ConstantArray:
1271 case Type::VariableArray:
1272 return arrayTypesAreCompatible(lcanon, rcanon);
1273 case Type::FunctionNoProto:
1274 case Type::FunctionProto:
1275 return functionTypesAreCompatible(lcanon, rcanon);
1276 case Type::Tagged: // handle structures, unions
1277 return tagTypesAreCompatible(lcanon, rcanon);
1278 case Type::Builtin:
1279 return builtinTypesAreCompatible(lcanon, rcanon);
1280 case Type::ObjcInterface:
1281 return interfaceTypesAreCompatible(lcanon, rcanon);
1282 default:
1283 assert(0 && "unexpected type");
1284 }
1285 return true; // should never get here...
1286}
Ted Kremenek738e6c02007-10-31 17:10:13 +00001287
1288
1289template <typename T>
1290static inline void EmitSet(const llvm::FoldingSet<T>& set, llvm::Serializer& S) {
1291 S.EmitInt(set.size());
1292 llvm::FoldingSet<T>& Set = const_cast<llvm::FoldingSet<T>&>(set);
1293
1294 for (typename llvm::FoldingSet<T>::iterator I=Set.begin(), E=Set.end();
1295 I!=E; ++I)
1296 S.Emit(*I);
1297}
1298
1299/// Emit - Serialize an ASTContext object to Bitcode.
1300void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremenek9af4d5c2007-10-31 20:00:03 +00001301 S.EmitRef(SourceMgr);
1302 S.EmitRef(Target);
1303 S.EmitRef(Idents);
1304 S.EmitRef(Selectors);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001305 // FIXME: BuildinInfo
1306
1307 EmitSet(ComplexTypes,S);
1308 EmitSet(PointerTypes,S);
1309 EmitSet(ReferenceTypes,S);
1310 EmitSet(ConstantArrayTypes,S);
Ted Kremenekc8253192007-10-31 17:50:23 +00001311 EmitSet(IncompleteVariableArrayTypes,S);
1312
Ted Kremenek738e6c02007-10-31 17:10:13 +00001313 S.EmitInt(CompleteVariableArrayTypes.size());
1314 for (unsigned i = 0; i < CompleteVariableArrayTypes.size(); ++i)
Ted Kremenekc8253192007-10-31 17:50:23 +00001315 S.Emit(*CompleteVariableArrayTypes[i]);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001316
1317 EmitSet(VectorTypes,S);
Ted Kremenekc8253192007-10-31 17:50:23 +00001318 EmitSet(FunctionTypeNoProtos,S);
1319 EmitSet(FunctionTypeProtos,S);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001320 // FIXME: EmitSet(ObjcQualifiedInterfaceTypes,S);
1321 // FIXME: RecourdLayoutInfo
1322 // FIXME: Builtins.
1323
1324}
1325
1326