blob: 93ec288270e43ab5271c2aa25149836cb38af8b9 [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"
20
Chris Lattner4b009652007-07-25 00:24:17 +000021using namespace clang;
22
23enum FloatingRank {
24 FloatRank, DoubleRank, LongDoubleRank
25};
26
27ASTContext::~ASTContext() {
28 // Deallocate all the types.
29 while (!Types.empty()) {
30 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(Types.back())) {
31 // Destroy the object, but don't call delete. These are malloc'd.
32 FT->~FunctionTypeProto();
33 free(FT);
34 } else {
35 delete Types.back();
36 }
37 Types.pop_back();
38 }
39}
40
41void ASTContext::PrintStats() const {
42 fprintf(stderr, "*** AST Context Stats:\n");
43 fprintf(stderr, " %d types total.\n", (int)Types.size());
44 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
45 unsigned NumVector = 0, NumComplex = 0;
46 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
47
48 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Steve Naroff948fd372007-09-17 14:16:13 +000049 unsigned NumObjcInterfaces = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000050
51 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
52 Type *T = Types[i];
53 if (isa<BuiltinType>(T))
54 ++NumBuiltin;
55 else if (isa<PointerType>(T))
56 ++NumPointer;
57 else if (isa<ReferenceType>(T))
58 ++NumReference;
59 else if (isa<ComplexType>(T))
60 ++NumComplex;
61 else if (isa<ArrayType>(T))
62 ++NumArray;
63 else if (isa<VectorType>(T))
64 ++NumVector;
65 else if (isa<FunctionTypeNoProto>(T))
66 ++NumFunctionNP;
67 else if (isa<FunctionTypeProto>(T))
68 ++NumFunctionP;
69 else if (isa<TypedefType>(T))
70 ++NumTypeName;
71 else if (TagType *TT = dyn_cast<TagType>(T)) {
72 ++NumTagged;
73 switch (TT->getDecl()->getKind()) {
74 default: assert(0 && "Unknown tagged type!");
75 case Decl::Struct: ++NumTagStruct; break;
76 case Decl::Union: ++NumTagUnion; break;
77 case Decl::Class: ++NumTagClass; break;
78 case Decl::Enum: ++NumTagEnum; break;
79 }
Steve Naroff948fd372007-09-17 14:16:13 +000080 } else if (isa<ObjcInterfaceType>(T))
81 ++NumObjcInterfaces;
82 else {
Chris Lattner4b009652007-07-25 00:24:17 +000083 assert(0 && "Unknown type!");
84 }
85 }
86
87 fprintf(stderr, " %d builtin types\n", NumBuiltin);
88 fprintf(stderr, " %d pointer types\n", NumPointer);
89 fprintf(stderr, " %d reference types\n", NumReference);
90 fprintf(stderr, " %d complex types\n", NumComplex);
91 fprintf(stderr, " %d array types\n", NumArray);
92 fprintf(stderr, " %d vector types\n", NumVector);
93 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
94 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
95 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
96 fprintf(stderr, " %d tagged types\n", NumTagged);
97 fprintf(stderr, " %d struct types\n", NumTagStruct);
98 fprintf(stderr, " %d union types\n", NumTagUnion);
99 fprintf(stderr, " %d class types\n", NumTagClass);
100 fprintf(stderr, " %d enum types\n", NumTagEnum);
Steve Naroff948fd372007-09-17 14:16:13 +0000101 fprintf(stderr, " %d interface types\n", NumObjcInterfaces);
Chris Lattner4b009652007-07-25 00:24:17 +0000102 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
103 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
104 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
105 NumFunctionP*sizeof(FunctionTypeProto)+
106 NumFunctionNP*sizeof(FunctionTypeNoProto)+
107 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)));
108}
109
110
111void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
112 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr());
113}
114
Chris Lattner4b009652007-07-25 00:24:17 +0000115void ASTContext::InitBuiltinTypes() {
116 assert(VoidTy.isNull() && "Context reinitialized?");
117
118 // C99 6.2.5p19.
119 InitBuiltinType(VoidTy, BuiltinType::Void);
120
121 // C99 6.2.5p2.
122 InitBuiltinType(BoolTy, BuiltinType::Bool);
123 // C99 6.2.5p3.
124 if (Target.isCharSigned(SourceLocation()))
125 InitBuiltinType(CharTy, BuiltinType::Char_S);
126 else
127 InitBuiltinType(CharTy, BuiltinType::Char_U);
128 // C99 6.2.5p4.
129 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
130 InitBuiltinType(ShortTy, BuiltinType::Short);
131 InitBuiltinType(IntTy, BuiltinType::Int);
132 InitBuiltinType(LongTy, BuiltinType::Long);
133 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
134
135 // C99 6.2.5p6.
136 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
137 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
138 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
139 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
140 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
141
142 // C99 6.2.5p10.
143 InitBuiltinType(FloatTy, BuiltinType::Float);
144 InitBuiltinType(DoubleTy, BuiltinType::Double);
145 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
146
147 // C99 6.2.5p11.
148 FloatComplexTy = getComplexType(FloatTy);
149 DoubleComplexTy = getComplexType(DoubleTy);
150 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Steve Naroff9d12c902007-10-15 14:41:52 +0000151
152 BuiltinVaListType = QualType();
153 ObjcIdType = QualType();
154 IdStructType = 0;
Steve Narofff2e30312007-10-15 23:35:17 +0000155 ObjcConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000156
157 // void * type
158 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000159}
160
161//===----------------------------------------------------------------------===//
162// Type Sizing and Analysis
163//===----------------------------------------------------------------------===//
164
165/// getTypeSize - Return the size of the specified type, in bits. This method
166/// does not work on incomplete types.
167std::pair<uint64_t, unsigned>
168ASTContext::getTypeInfo(QualType T, SourceLocation L) {
169 T = T.getCanonicalType();
170 uint64_t Size;
171 unsigned Align;
172 switch (T->getTypeClass()) {
173 case Type::TypeName: assert(0 && "Not a canonical type!");
174 case Type::FunctionNoProto:
175 case Type::FunctionProto:
176 default:
177 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000178 case Type::VariableArray:
179 assert(0 && "VLAs not implemented yet!");
180 case Type::ConstantArray: {
181 ConstantArrayType *CAT = cast<ConstantArrayType>(T);
182
Chris Lattner4b009652007-07-25 00:24:17 +0000183 std::pair<uint64_t, unsigned> EltInfo =
Steve Naroff83c13012007-08-30 01:06:46 +0000184 getTypeInfo(CAT->getElementType(), L);
185 Size = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000186 Align = EltInfo.second;
187 break;
188 }
189 case Type::Vector: {
190 std::pair<uint64_t, unsigned> EltInfo =
191 getTypeInfo(cast<VectorType>(T)->getElementType(), L);
192 Size = EltInfo.first*cast<VectorType>(T)->getNumElements();
193 // FIXME: Vector alignment is not the alignment of its elements.
194 Align = EltInfo.second;
195 break;
196 }
197
198 case Type::Builtin: {
199 // FIXME: need to use TargetInfo to derive the target specific sizes. This
200 // implementation will suffice for play with vector support.
Chris Lattner858eece2007-09-22 18:29:59 +0000201 const llvm::fltSemantics *F;
Chris Lattner4b009652007-07-25 00:24:17 +0000202 switch (cast<BuiltinType>(T)->getKind()) {
203 default: assert(0 && "Unknown builtin type!");
204 case BuiltinType::Void:
205 assert(0 && "Incomplete types have no size!");
206 case BuiltinType::Bool: Target.getBoolInfo(Size, Align, L); break;
207 case BuiltinType::Char_S:
208 case BuiltinType::Char_U:
209 case BuiltinType::UChar:
210 case BuiltinType::SChar: Target.getCharInfo(Size, Align, L); break;
211 case BuiltinType::UShort:
212 case BuiltinType::Short: Target.getShortInfo(Size, Align, L); break;
213 case BuiltinType::UInt:
214 case BuiltinType::Int: Target.getIntInfo(Size, Align, L); break;
215 case BuiltinType::ULong:
216 case BuiltinType::Long: Target.getLongInfo(Size, Align, L); break;
217 case BuiltinType::ULongLong:
218 case BuiltinType::LongLong: Target.getLongLongInfo(Size, Align, L); break;
Chris Lattner858eece2007-09-22 18:29:59 +0000219 case BuiltinType::Float: Target.getFloatInfo(Size, Align, F, L); break;
220 case BuiltinType::Double: Target.getDoubleInfo(Size, Align, F, L);break;
221 case BuiltinType::LongDouble:Target.getLongDoubleInfo(Size,Align,F,L);break;
Chris Lattner4b009652007-07-25 00:24:17 +0000222 }
223 break;
224 }
225 case Type::Pointer: Target.getPointerInfo(Size, Align, L); break;
226 case Type::Reference:
227 // "When applied to a reference or a reference type, the result is the size
228 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
229 // FIXME: This is wrong for struct layout!
230 return getTypeInfo(cast<ReferenceType>(T)->getReferenceeType(), L);
231
232 case Type::Complex: {
233 // Complex types have the same alignment as their elements, but twice the
234 // size.
235 std::pair<uint64_t, unsigned> EltInfo =
236 getTypeInfo(cast<ComplexType>(T)->getElementType(), L);
237 Size = EltInfo.first*2;
238 Align = EltInfo.second;
239 break;
240 }
241 case Type::Tagged:
Chris Lattnereb56d292007-08-27 17:38:00 +0000242 TagType *TT = cast<TagType>(T);
243 if (RecordType *RT = dyn_cast<RecordType>(TT)) {
244 const RecordLayout &Layout = getRecordLayout(RT->getDecl(), L);
245 Size = Layout.getSize();
246 Align = Layout.getAlignment();
247 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(TT->getDecl())) {
Chris Lattner90a018d2007-08-28 18:24:31 +0000248 return getTypeInfo(ED->getIntegerType(), L);
Chris Lattnereb56d292007-08-27 17:38:00 +0000249 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000250 assert(0 && "Unimplemented type sizes!");
Chris Lattnereb56d292007-08-27 17:38:00 +0000251 }
Chris Lattner4b009652007-07-25 00:24:17 +0000252 break;
253 }
254
255 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
256 return std::make_pair(Size, Align);
257}
258
259/// getRecordLayout - Get or compute information about the layout of the
260/// specified record (struct/union/class), which indicates its size and field
261/// position information.
262const RecordLayout &ASTContext::getRecordLayout(const RecordDecl *D,
263 SourceLocation L) {
264 assert(D->isDefinition() && "Cannot get layout of forward declarations!");
265
266 // Look up this layout, if already laid out, return what we have.
267 const RecordLayout *&Entry = RecordLayoutInfo[D];
268 if (Entry) return *Entry;
269
270 // Allocate and assign into RecordLayoutInfo here. The "Entry" reference can
271 // be invalidated (dangle) if the RecordLayoutInfo hashtable is inserted into.
272 RecordLayout *NewEntry = new RecordLayout();
273 Entry = NewEntry;
274
275 uint64_t *FieldOffsets = new uint64_t[D->getNumMembers()];
276 uint64_t RecordSize = 0;
277 unsigned RecordAlign = 8; // Default alignment = 1 byte = 8 bits.
278
279 if (D->getKind() != Decl::Union) {
280 // Layout each field, for now, just sequentially, respecting alignment. In
281 // the future, this will need to be tweakable by targets.
282 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
283 const FieldDecl *FD = D->getMember(i);
284 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType(), L);
285 uint64_t FieldSize = FieldInfo.first;
286 unsigned FieldAlign = FieldInfo.second;
287
288 // Round up the current record size to the field's alignment boundary.
289 RecordSize = (RecordSize+FieldAlign-1) & ~(FieldAlign-1);
290
291 // Place this field at the current location.
292 FieldOffsets[i] = RecordSize;
293
294 // Reserve space for this field.
295 RecordSize += FieldSize;
296
297 // Remember max struct/class alignment.
298 RecordAlign = std::max(RecordAlign, FieldAlign);
299 }
300
301 // Finally, round the size of the total struct up to the alignment of the
302 // struct itself.
303 RecordSize = (RecordSize+RecordAlign-1) & ~(RecordAlign-1);
304 } else {
305 // Union layout just puts each member at the start of the record.
306 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
307 const FieldDecl *FD = D->getMember(i);
308 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType(), L);
309 uint64_t FieldSize = FieldInfo.first;
310 unsigned FieldAlign = FieldInfo.second;
311
312 // Round up the current record size to the field's alignment boundary.
313 RecordSize = std::max(RecordSize, FieldSize);
314
315 // Place this field at the start of the record.
316 FieldOffsets[i] = 0;
317
318 // Remember max struct/class alignment.
319 RecordAlign = std::max(RecordAlign, FieldAlign);
320 }
321 }
322
323 NewEntry->SetLayout(RecordSize, RecordAlign, FieldOffsets);
324 return *NewEntry;
325}
326
Chris Lattner4b009652007-07-25 00:24:17 +0000327//===----------------------------------------------------------------------===//
328// Type creation/memoization methods
329//===----------------------------------------------------------------------===//
330
331
332/// getComplexType - Return the uniqued reference to the type for a complex
333/// number with the specified element type.
334QualType ASTContext::getComplexType(QualType T) {
335 // Unique pointers, to guarantee there is only one pointer of a particular
336 // structure.
337 llvm::FoldingSetNodeID ID;
338 ComplexType::Profile(ID, T);
339
340 void *InsertPos = 0;
341 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
342 return QualType(CT, 0);
343
344 // If the pointee type isn't canonical, this won't be a canonical type either,
345 // so fill in the canonical type field.
346 QualType Canonical;
347 if (!T->isCanonical()) {
348 Canonical = getComplexType(T.getCanonicalType());
349
350 // Get the new insert position for the node we care about.
351 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
352 assert(NewIP == 0 && "Shouldn't be in the map!");
353 }
354 ComplexType *New = new ComplexType(T, Canonical);
355 Types.push_back(New);
356 ComplexTypes.InsertNode(New, InsertPos);
357 return QualType(New, 0);
358}
359
360
361/// getPointerType - Return the uniqued reference to the type for a pointer to
362/// the specified type.
363QualType ASTContext::getPointerType(QualType T) {
364 // Unique pointers, to guarantee there is only one pointer of a particular
365 // structure.
366 llvm::FoldingSetNodeID ID;
367 PointerType::Profile(ID, T);
368
369 void *InsertPos = 0;
370 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
371 return QualType(PT, 0);
372
373 // If the pointee type isn't canonical, this won't be a canonical type either,
374 // so fill in the canonical type field.
375 QualType Canonical;
376 if (!T->isCanonical()) {
377 Canonical = getPointerType(T.getCanonicalType());
378
379 // Get the new insert position for the node we care about.
380 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
381 assert(NewIP == 0 && "Shouldn't be in the map!");
382 }
383 PointerType *New = new PointerType(T, Canonical);
384 Types.push_back(New);
385 PointerTypes.InsertNode(New, InsertPos);
386 return QualType(New, 0);
387}
388
389/// getReferenceType - Return the uniqued reference to the type for a reference
390/// to the specified type.
391QualType ASTContext::getReferenceType(QualType T) {
392 // Unique pointers, to guarantee there is only one pointer of a particular
393 // structure.
394 llvm::FoldingSetNodeID ID;
395 ReferenceType::Profile(ID, T);
396
397 void *InsertPos = 0;
398 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
399 return QualType(RT, 0);
400
401 // If the referencee type isn't canonical, this won't be a canonical type
402 // either, so fill in the canonical type field.
403 QualType Canonical;
404 if (!T->isCanonical()) {
405 Canonical = getReferenceType(T.getCanonicalType());
406
407 // Get the new insert position for the node we care about.
408 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
409 assert(NewIP == 0 && "Shouldn't be in the map!");
410 }
411
412 ReferenceType *New = new ReferenceType(T, Canonical);
413 Types.push_back(New);
414 ReferenceTypes.InsertNode(New, InsertPos);
415 return QualType(New, 0);
416}
417
Steve Naroff83c13012007-08-30 01:06:46 +0000418/// getConstantArrayType - Return the unique reference to the type for an
419/// array of the specified element type.
420QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +0000421 const llvm::APInt &ArySize,
422 ArrayType::ArraySizeModifier ASM,
423 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +0000424 llvm::FoldingSetNodeID ID;
Steve Naroff83c13012007-08-30 01:06:46 +0000425 ConstantArrayType::Profile(ID, EltTy, ArySize);
Chris Lattner4b009652007-07-25 00:24:17 +0000426
427 void *InsertPos = 0;
Steve Naroff83c13012007-08-30 01:06:46 +0000428 if (ConstantArrayType *ATP = ArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000429 return QualType(ATP, 0);
430
431 // If the element type isn't canonical, this won't be a canonical type either,
432 // so fill in the canonical type field.
433 QualType Canonical;
434 if (!EltTy->isCanonical()) {
Steve Naroff24c9b982007-08-30 18:10:14 +0000435 Canonical = getConstantArrayType(EltTy.getCanonicalType(), ArySize,
436 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +0000437 // Get the new insert position for the node we care about.
Steve Naroff83c13012007-08-30 01:06:46 +0000438 ConstantArrayType *NewIP = ArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000439 assert(NewIP == 0 && "Shouldn't be in the map!");
440 }
441
Steve Naroff24c9b982007-08-30 18:10:14 +0000442 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
443 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +0000444 ArrayTypes.InsertNode(New, InsertPos);
445 Types.push_back(New);
446 return QualType(New, 0);
447}
448
Steve Naroffe2579e32007-08-30 18:14:25 +0000449/// getVariableArrayType - Returns a non-unique reference to the type for a
450/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +0000451QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
452 ArrayType::ArraySizeModifier ASM,
453 unsigned EltTypeQuals) {
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000454 if (NumElts) {
455 // Since we don't unique expressions, it isn't possible to unique VLA's
456 // that have an expression provided for their size.
457
Ted Kremenek2058dc42007-10-30 16:41:53 +0000458 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
459 ASM, EltTypeQuals);
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000460
Ted Kremenek2058dc42007-10-30 16:41:53 +0000461 CompleteVariableArrayTypes.push_back(New);
Ted Kremenek3793e1a2007-10-29 23:37:31 +0000462 Types.push_back(New);
463 return QualType(New, 0);
464 }
465 else {
466 // No size is provided for the VLA. These we can unique.
467 llvm::FoldingSetNodeID ID;
468 VariableArrayType::Profile(ID, EltTy);
469
470 void *InsertPos = 0;
471 if (VariableArrayType *ATP =
472 IncompleteVariableArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
473 return QualType(ATP, 0);
474
475 // If the element type isn't canonical, this won't be a canonical type
476 // either, so fill in the canonical type field.
477 QualType Canonical;
478
479 if (!EltTy->isCanonical()) {
480 Canonical = getVariableArrayType(EltTy.getCanonicalType(), NumElts,
481 ASM, EltTypeQuals);
482
483 // Get the new insert position for the node we care about.
484 VariableArrayType *NewIP =
485 IncompleteVariableArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
486
487 assert(NewIP == 0 && "Shouldn't be in the map!");
488 }
489
490 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
491 ASM, EltTypeQuals);
492
493 IncompleteVariableArrayTypes.InsertNode(New, InsertPos);
494 Types.push_back(New);
495 return QualType(New, 0);
496 }
Steve Naroff83c13012007-08-30 01:06:46 +0000497}
498
Chris Lattner4b009652007-07-25 00:24:17 +0000499/// getVectorType - Return the unique reference to a vector type of
500/// the specified element type and size. VectorType must be a built-in type.
501QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
502 BuiltinType *baseType;
503
504 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
505 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
506
507 // Check if we've already instantiated a vector of this type.
508 llvm::FoldingSetNodeID ID;
509 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
510 void *InsertPos = 0;
511 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
512 return QualType(VTP, 0);
513
514 // If the element type isn't canonical, this won't be a canonical type either,
515 // so fill in the canonical type field.
516 QualType Canonical;
517 if (!vecType->isCanonical()) {
518 Canonical = getVectorType(vecType.getCanonicalType(), NumElts);
519
520 // Get the new insert position for the node we care about.
521 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
522 assert(NewIP == 0 && "Shouldn't be in the map!");
523 }
524 VectorType *New = new VectorType(vecType, NumElts, Canonical);
525 VectorTypes.InsertNode(New, InsertPos);
526 Types.push_back(New);
527 return QualType(New, 0);
528}
529
530/// getOCUVectorType - Return the unique reference to an OCU vector type of
531/// the specified element type and size. VectorType must be a built-in type.
532QualType ASTContext::getOCUVectorType(QualType vecType, unsigned NumElts) {
533 BuiltinType *baseType;
534
535 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
536 assert(baseType != 0 && "getOCUVectorType(): Expecting a built-in type");
537
538 // Check if we've already instantiated a vector of this type.
539 llvm::FoldingSetNodeID ID;
540 VectorType::Profile(ID, vecType, NumElts, Type::OCUVector);
541 void *InsertPos = 0;
542 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
543 return QualType(VTP, 0);
544
545 // If the element type isn't canonical, this won't be a canonical type either,
546 // so fill in the canonical type field.
547 QualType Canonical;
548 if (!vecType->isCanonical()) {
549 Canonical = getOCUVectorType(vecType.getCanonicalType(), NumElts);
550
551 // Get the new insert position for the node we care about.
552 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
553 assert(NewIP == 0 && "Shouldn't be in the map!");
554 }
555 OCUVectorType *New = new OCUVectorType(vecType, NumElts, Canonical);
556 VectorTypes.InsertNode(New, InsertPos);
557 Types.push_back(New);
558 return QualType(New, 0);
559}
560
561/// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
562///
563QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
564 // Unique functions, to guarantee there is only one function of a particular
565 // structure.
566 llvm::FoldingSetNodeID ID;
567 FunctionTypeNoProto::Profile(ID, ResultTy);
568
569 void *InsertPos = 0;
570 if (FunctionTypeNoProto *FT =
571 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
572 return QualType(FT, 0);
573
574 QualType Canonical;
575 if (!ResultTy->isCanonical()) {
576 Canonical = getFunctionTypeNoProto(ResultTy.getCanonicalType());
577
578 // Get the new insert position for the node we care about.
579 FunctionTypeNoProto *NewIP =
580 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
581 assert(NewIP == 0 && "Shouldn't be in the map!");
582 }
583
584 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
585 Types.push_back(New);
586 FunctionTypeProtos.InsertNode(New, InsertPos);
587 return QualType(New, 0);
588}
589
590/// getFunctionType - Return a normal function type with a typed argument
591/// list. isVariadic indicates whether the argument list includes '...'.
592QualType ASTContext::getFunctionType(QualType ResultTy, QualType *ArgArray,
593 unsigned NumArgs, bool isVariadic) {
594 // Unique functions, to guarantee there is only one function of a particular
595 // structure.
596 llvm::FoldingSetNodeID ID;
597 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic);
598
599 void *InsertPos = 0;
600 if (FunctionTypeProto *FTP =
601 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
602 return QualType(FTP, 0);
603
604 // Determine whether the type being created is already canonical or not.
605 bool isCanonical = ResultTy->isCanonical();
606 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
607 if (!ArgArray[i]->isCanonical())
608 isCanonical = false;
609
610 // If this type isn't canonical, get the canonical version of it.
611 QualType Canonical;
612 if (!isCanonical) {
613 llvm::SmallVector<QualType, 16> CanonicalArgs;
614 CanonicalArgs.reserve(NumArgs);
615 for (unsigned i = 0; i != NumArgs; ++i)
616 CanonicalArgs.push_back(ArgArray[i].getCanonicalType());
617
618 Canonical = getFunctionType(ResultTy.getCanonicalType(),
619 &CanonicalArgs[0], NumArgs,
620 isVariadic);
621
622 // Get the new insert position for the node we care about.
623 FunctionTypeProto *NewIP =
624 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
625 assert(NewIP == 0 && "Shouldn't be in the map!");
626 }
627
628 // FunctionTypeProto objects are not allocated with new because they have a
629 // variable size array (for parameter types) at the end of them.
630 FunctionTypeProto *FTP =
631 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) +
632 NumArgs*sizeof(QualType));
633 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
634 Canonical);
635 Types.push_back(FTP);
636 FunctionTypeProtos.InsertNode(FTP, InsertPos);
637 return QualType(FTP, 0);
638}
639
640/// getTypedefType - Return the unique reference to the type for the
641/// specified typename decl.
642QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
643 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
644
645 QualType Canonical = Decl->getUnderlyingType().getCanonicalType();
646 Decl->TypeForDecl = new TypedefType(Decl, Canonical);
647 Types.push_back(Decl->TypeForDecl);
648 return QualType(Decl->TypeForDecl, 0);
649}
650
Steve Naroff81f1bba2007-09-06 21:24:23 +0000651/// getObjcInterfaceType - Return the unique reference to the type for the
652/// specified ObjC interface decl.
653QualType ASTContext::getObjcInterfaceType(ObjcInterfaceDecl *Decl) {
654 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
655
656 Decl->TypeForDecl = new ObjcInterfaceType(Decl);
657 Types.push_back(Decl->TypeForDecl);
658 return QualType(Decl->TypeForDecl, 0);
659}
660
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000661/// getObjcQualifiedInterfaceType - Return a
662/// ObjcQualifiedInterfaceType type for the given interface decl and
663/// the conforming protocol list.
664QualType ASTContext::getObjcQualifiedInterfaceType(ObjcInterfaceDecl *Decl,
665 ObjcProtocolDecl **Protocols, unsigned NumProtocols) {
666 ObjcInterfaceType *IType =
667 cast<ObjcInterfaceType>(getObjcInterfaceType(Decl));
668
669 llvm::FoldingSetNodeID ID;
670 ObjcQualifiedInterfaceType::Profile(ID, IType, Protocols, NumProtocols);
671
672 void *InsertPos = 0;
673 if (ObjcQualifiedInterfaceType *QT =
674 ObjcQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
675 return QualType(QT, 0);
676
677 // No Match;
Chris Lattnerd855a6e2007-10-11 03:36:41 +0000678 ObjcQualifiedInterfaceType *QType =
679 new ObjcQualifiedInterfaceType(IType, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +0000680 Types.push_back(QType);
681 ObjcQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
682 return QualType(QType, 0);
683}
684
Steve Naroff0604dd92007-08-01 18:02:17 +0000685/// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
686/// TypeOfExpr AST's (since expression's are never shared). For example,
687/// multiple declarations that refer to "typeof(x)" all contain different
688/// DeclRefExpr's. This doesn't effect the type checker, since it operates
689/// on canonical type's (which are always unique).
Steve Naroff11b649c2007-08-01 17:20:42 +0000690QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
Steve Naroff7cbb1462007-07-31 12:34:36 +0000691 QualType Canonical = tofExpr->getType().getCanonicalType();
Steve Naroff0604dd92007-08-01 18:02:17 +0000692 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
693 Types.push_back(toe);
694 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000695}
696
Steve Naroff0604dd92007-08-01 18:02:17 +0000697/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
698/// TypeOfType AST's. The only motivation to unique these nodes would be
699/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
700/// an issue. This doesn't effect the type checker, since it operates
701/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +0000702QualType ASTContext::getTypeOfType(QualType tofType) {
703 QualType Canonical = tofType.getCanonicalType();
Steve Naroff0604dd92007-08-01 18:02:17 +0000704 TypeOfType *tot = new TypeOfType(tofType, Canonical);
705 Types.push_back(tot);
706 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +0000707}
708
Chris Lattner4b009652007-07-25 00:24:17 +0000709/// getTagDeclType - Return the unique reference to the type for the
710/// specified TagDecl (struct/union/class/enum) decl.
711QualType ASTContext::getTagDeclType(TagDecl *Decl) {
712 // The decl stores the type cache.
713 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
714
715 Decl->TypeForDecl = new TagType(Decl, QualType());
716 Types.push_back(Decl->TypeForDecl);
717 return QualType(Decl->TypeForDecl, 0);
718}
719
720/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
721/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
722/// needs to agree with the definition in <stddef.h>.
723QualType ASTContext::getSizeType() const {
724 // On Darwin, size_t is defined as a "long unsigned int".
725 // FIXME: should derive from "Target".
726 return UnsignedLongTy;
727}
728
729/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
730/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
731QualType ASTContext::getPointerDiffType() const {
732 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug...
733 // FIXME: should derive from "Target".
734 return IntTy;
735}
736
737/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
738/// routine will assert if passed a built-in type that isn't an integer or enum.
739static int getIntegerRank(QualType t) {
740 if (const TagType *TT = dyn_cast<TagType>(t.getCanonicalType())) {
741 assert(TT->getDecl()->getKind() == Decl::Enum && "not an int or enum");
742 return 4;
743 }
744
745 const BuiltinType *BT = cast<BuiltinType>(t.getCanonicalType());
746 switch (BT->getKind()) {
747 default:
748 assert(0 && "getIntegerRank(): not a built-in integer");
749 case BuiltinType::Bool:
750 return 1;
751 case BuiltinType::Char_S:
752 case BuiltinType::Char_U:
753 case BuiltinType::SChar:
754 case BuiltinType::UChar:
755 return 2;
756 case BuiltinType::Short:
757 case BuiltinType::UShort:
758 return 3;
759 case BuiltinType::Int:
760 case BuiltinType::UInt:
761 return 4;
762 case BuiltinType::Long:
763 case BuiltinType::ULong:
764 return 5;
765 case BuiltinType::LongLong:
766 case BuiltinType::ULongLong:
767 return 6;
768 }
769}
770
771/// getFloatingRank - Return a relative rank for floating point types.
772/// This routine will assert if passed a built-in type that isn't a float.
773static int getFloatingRank(QualType T) {
774 T = T.getCanonicalType();
775 if (ComplexType *CT = dyn_cast<ComplexType>(T))
776 return getFloatingRank(CT->getElementType());
777
778 switch (cast<BuiltinType>(T)->getKind()) {
779 default: assert(0 && "getFloatingPointRank(): not a floating type");
780 case BuiltinType::Float: return FloatRank;
781 case BuiltinType::Double: return DoubleRank;
782 case BuiltinType::LongDouble: return LongDoubleRank;
783 }
784}
785
Steve Narofffa0c4532007-08-27 01:41:48 +0000786/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
787/// point or a complex type (based on typeDomain/typeSize).
788/// 'typeDomain' is a real floating point or complex type.
789/// 'typeSize' is a real floating point or complex type.
Steve Naroff3cf497f2007-08-27 01:27:54 +0000790QualType ASTContext::getFloatingTypeOfSizeWithinDomain(
791 QualType typeSize, QualType typeDomain) const {
792 if (typeDomain->isComplexType()) {
793 switch (getFloatingRank(typeSize)) {
Steve Narofffa0c4532007-08-27 01:41:48 +0000794 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +0000795 case FloatRank: return FloatComplexTy;
796 case DoubleRank: return DoubleComplexTy;
797 case LongDoubleRank: return LongDoubleComplexTy;
798 }
Chris Lattner4b009652007-07-25 00:24:17 +0000799 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000800 if (typeDomain->isRealFloatingType()) {
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 FloatTy;
804 case DoubleRank: return DoubleTy;
805 case LongDoubleRank: return LongDoubleTy;
806 }
807 }
808 assert(0 && "getFloatingTypeOfSizeWithinDomain(): illegal domain");
Chris Lattner1d2b4612007-09-16 19:23:47 +0000809 //an invalid return value, but the assert
810 //will ensure that this code is never reached.
811 return VoidTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000812}
813
Steve Naroff45fc9822007-08-27 15:30:22 +0000814/// compareFloatingType - Handles 3 different combos:
815/// float/float, float/complex, complex/complex.
816/// If lt > rt, return 1. If lt == rt, return 0. If lt < rt, return -1.
817int ASTContext::compareFloatingType(QualType lt, QualType rt) {
818 if (getFloatingRank(lt) == getFloatingRank(rt))
819 return 0;
820 if (getFloatingRank(lt) > getFloatingRank(rt))
821 return 1;
822 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +0000823}
824
825// maxIntegerType - Returns the highest ranked integer type. Handles 3 case:
826// unsigned/unsigned, signed/signed, signed/unsigned. C99 6.3.1.8p1.
827QualType ASTContext::maxIntegerType(QualType lhs, QualType rhs) {
828 if (lhs == rhs) return lhs;
829
830 bool t1Unsigned = lhs->isUnsignedIntegerType();
831 bool t2Unsigned = rhs->isUnsignedIntegerType();
832
833 if ((t1Unsigned && t2Unsigned) || (!t1Unsigned && !t2Unsigned))
834 return getIntegerRank(lhs) >= getIntegerRank(rhs) ? lhs : rhs;
835
836 // We have two integer types with differing signs
837 QualType unsignedType = t1Unsigned ? lhs : rhs;
838 QualType signedType = t1Unsigned ? rhs : lhs;
839
840 if (getIntegerRank(unsignedType) >= getIntegerRank(signedType))
841 return unsignedType;
842 else {
843 // FIXME: Need to check if the signed type can represent all values of the
844 // unsigned type. If it can, then the result is the signed type.
845 // If it can't, then the result is the unsigned version of the signed type.
846 // Should probably add a helper that returns a signed integer type from
847 // an unsigned (and vice versa). C99 6.3.1.8.
848 return signedType;
849 }
850}
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000851
852// getCFConstantStringType - Return the type used for constant CFStrings.
853QualType ASTContext::getCFConstantStringType() {
854 if (!CFConstantStringTypeDecl) {
855 CFConstantStringTypeDecl = new RecordDecl(Decl::Struct, SourceLocation(),
856 &Idents.get("__builtin_CFString"),
857 0);
858
859 QualType FieldTypes[4];
860
861 // const int *isa;
862 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
863 // int flags;
864 FieldTypes[1] = IntTy;
865 // const char *str;
866 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
867 // long length;
868 FieldTypes[3] = LongTy;
869 // Create fields
870 FieldDecl *FieldDecls[4];
871
872 for (unsigned i = 0; i < 4; ++i)
Steve Naroffdc1ad762007-09-14 02:20:46 +0000873 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000874
875 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
876 }
877
878 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +0000879}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000880
Anders Carlssone3f02572007-10-29 06:33:42 +0000881// This returns true if a type has been typedefed to BOOL:
882// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +0000883static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +0000884 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnercb034cb2007-10-30 20:27:44 +0000885 return !strcmp(TT->getDecl()->getName(), "BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +0000886
887 return false;
888}
889
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000890/// getObjcEncodingTypeSize returns size of type for objective-c encoding
891/// purpose.
892int ASTContext::getObjcEncodingTypeSize(QualType type) {
893 SourceLocation Loc;
894 uint64_t sz = getTypeSize(type, Loc);
895
896 // Make all integer and enum types at least as large as an int
897 if (sz > 0 && type->isIntegralType())
898 sz = std::max(sz, getTypeSize(IntTy, Loc));
899 // Treat arrays as pointers, since that's how they're passed in.
900 else if (type->isArrayType())
901 sz = getTypeSize(VoidPtrTy, Loc);
902 return sz / getTypeSize(CharTy, Loc);
903}
904
905/// getObjcEncodingForMethodDecl - Return the encoded type for this method
906/// declaration.
907void ASTContext::getObjcEncodingForMethodDecl(ObjcMethodDecl *Decl,
908 std::string& S)
909{
910 // TODO: First encode type qualifer, 'in', 'inout', etc. for the return type.
911 // Encode result type.
912 getObjcEncodingForType(Decl->getResultType(), S);
913 // Compute size of all parameters.
914 // Start with computing size of a pointer in number of bytes.
915 // FIXME: There might(should) be a better way of doing this computation!
916 SourceLocation Loc;
917 int PtrSize = getTypeSize(VoidPtrTy, Loc) / getTypeSize(CharTy, Loc);
918 // The first two arguments (self and _cmd) are pointers; account for
919 // their size.
920 int ParmOffset = 2 * PtrSize;
921 int NumOfParams = Decl->getNumParams();
922 for (int i = 0; i < NumOfParams; i++) {
923 QualType PType = Decl->getParamDecl(i)->getType();
924 int sz = getObjcEncodingTypeSize (PType);
925 assert (sz > 0 && "getObjcEncodingForMethodDecl - Incomplete param type");
926 ParmOffset += sz;
927 }
928 S += llvm::utostr(ParmOffset);
929 S += "@0:";
930 S += llvm::utostr(PtrSize);
931
932 // Argument types.
933 ParmOffset = 2 * PtrSize;
934 for (int i = 0; i < NumOfParams; i++) {
935 QualType PType = Decl->getParamDecl(i)->getType();
936 // TODO: Process argument qualifiers for user supplied arguments; such as,
937 // 'in', 'inout', etc.
938 getObjcEncodingForType(PType, S);
939 S += llvm::utostr(ParmOffset);
940 ParmOffset += getObjcEncodingTypeSize(PType);
941 }
942}
943
Anders Carlsson36f07d82007-10-29 05:01:08 +0000944void ASTContext::getObjcEncodingForType(QualType T, std::string& S) const
945{
Anders Carlssone3f02572007-10-29 06:33:42 +0000946 // FIXME: This currently doesn't encode:
947 // @ An object (whether statically typed or typed id)
948 // # A class object (Class)
949 // : A method selector (SEL)
950 // {name=type...} A structure
951 // (name=type...) A union
952 // bnum A bit field of num bits
953
954 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +0000955 char encoding;
956 switch (BT->getKind()) {
957 case BuiltinType::Void:
958 encoding = 'v';
959 break;
960 case BuiltinType::Bool:
961 encoding = 'B';
962 break;
963 case BuiltinType::Char_U:
964 case BuiltinType::UChar:
965 encoding = 'C';
966 break;
967 case BuiltinType::UShort:
968 encoding = 'S';
969 break;
970 case BuiltinType::UInt:
971 encoding = 'I';
972 break;
973 case BuiltinType::ULong:
974 encoding = 'L';
975 break;
976 case BuiltinType::ULongLong:
977 encoding = 'Q';
978 break;
979 case BuiltinType::Char_S:
980 case BuiltinType::SChar:
981 encoding = 'c';
982 break;
983 case BuiltinType::Short:
984 encoding = 's';
985 break;
986 case BuiltinType::Int:
987 encoding = 'i';
988 break;
989 case BuiltinType::Long:
990 encoding = 'l';
991 break;
992 case BuiltinType::LongLong:
993 encoding = 'q';
994 break;
995 case BuiltinType::Float:
996 encoding = 'f';
997 break;
998 case BuiltinType::Double:
999 encoding = 'd';
1000 break;
1001 case BuiltinType::LongDouble:
1002 encoding = 'd';
1003 break;
1004 default:
1005 assert(0 && "Unhandled builtin type kind");
1006 }
1007
1008 S += encoding;
Anders Carlssone3f02572007-10-29 06:33:42 +00001009 } else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001010 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00001011 if (isObjcIdType(PointeeTy)) {
1012 S += '@';
1013 return;
1014 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00001015
1016 if (PointeeTy->isCharType()) {
1017 // char pointer types should be encoded as '*' unless it is a
1018 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00001019 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001020 S += '*';
1021 return;
1022 }
1023 }
1024
1025 S += '^';
1026 getObjcEncodingForType(PT->getPointeeType(), S);
Anders Carlssone3f02572007-10-29 06:33:42 +00001027 } else if (const ArrayType *AT = T->getAsArrayType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00001028 S += '[';
1029
1030 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1031 S += llvm::utostr(CAT->getSize().getZExtValue());
1032 else
1033 assert(0 && "Unhandled array type!");
1034
1035 getObjcEncodingForType(AT->getElementType(), S);
1036 S += ']';
Anders Carlsson5695bb72007-10-30 00:06:20 +00001037 } else if (T->getAsFunctionType()) {
1038 S += '?';
Anders Carlsson36f07d82007-10-29 05:01:08 +00001039 } else
Anders Carlssone3f02572007-10-29 06:33:42 +00001040 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00001041}
1042
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001043void ASTContext::setBuiltinVaListType(QualType T)
1044{
1045 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1046
1047 BuiltinVaListType = T;
1048}
1049
Steve Naroff9d12c902007-10-15 14:41:52 +00001050void ASTContext::setObjcIdType(TypedefDecl *TD)
1051{
1052 assert(ObjcIdType.isNull() && "'id' type already set!");
1053
1054 ObjcIdType = getTypedefType(TD);
1055
1056 // typedef struct objc_object *id;
1057 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1058 assert(ptr && "'id' incorrectly typed");
1059 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1060 assert(rec && "'id' incorrectly typed");
1061 IdStructType = rec;
1062}
1063
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001064void ASTContext::setObjcSelType(TypedefDecl *TD)
1065{
1066 assert(ObjcSelType.isNull() && "'SEL' type already set!");
1067
1068 ObjcSelType = getTypedefType(TD);
1069
1070 // typedef struct objc_selector *SEL;
1071 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1072 assert(ptr && "'SEL' incorrectly typed");
1073 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1074 assert(rec && "'SEL' incorrectly typed");
1075 SelStructType = rec;
1076}
1077
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001078void ASTContext::setObjcProtoType(TypedefDecl *TD)
1079{
1080 assert(ObjcProtoType.isNull() && "'Protocol' type already set!");
1081
1082 // typedef struct Protocol Protocol;
1083 ObjcProtoType = TD->getUnderlyingType();
1084 // Protocol * type
1085 ObjcProtoType = getPointerType(ObjcProtoType);
1086 ProtoStructType = TD->getUnderlyingType()->getAsStructureType();
1087}
1088
Steve Narofff2e30312007-10-15 23:35:17 +00001089void ASTContext::setObjcConstantStringInterface(ObjcInterfaceDecl *Decl) {
1090 assert(ObjcConstantStringType.isNull() &&
1091 "'NSConstantString' type already set!");
1092
1093 ObjcConstantStringType = getObjcInterfaceType(Decl);
1094}
1095
Steve Naroff85f0dc52007-10-15 20:41:53 +00001096bool ASTContext::builtinTypesAreCompatible(QualType lhs, QualType rhs) {
1097 const BuiltinType *lBuiltin = lhs->getAsBuiltinType();
1098 const BuiltinType *rBuiltin = rhs->getAsBuiltinType();
1099
1100 return lBuiltin->getKind() == rBuiltin->getKind();
1101}
1102
1103
1104bool ASTContext::objcTypesAreCompatible(QualType lhs, QualType rhs) {
1105 if (lhs->isObjcInterfaceType() && isObjcIdType(rhs))
1106 return true;
1107 else if (isObjcIdType(lhs) && rhs->isObjcInterfaceType())
1108 return true;
1109 return false;
1110}
1111
1112bool ASTContext::interfaceTypesAreCompatible(QualType lhs, QualType rhs) {
1113 return true; // FIXME: IMPLEMENT.
1114}
1115
1116// C99 6.2.7p1: If both are complete types, then the following additional
1117// requirements apply...FIXME (handle compatibility across source files).
1118bool ASTContext::tagTypesAreCompatible(QualType lhs, QualType rhs) {
1119 TagDecl *ldecl = cast<TagType>(lhs.getCanonicalType())->getDecl();
1120 TagDecl *rdecl = cast<TagType>(rhs.getCanonicalType())->getDecl();
1121
1122 if (ldecl->getKind() == Decl::Struct && rdecl->getKind() == Decl::Struct) {
1123 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1124 return true;
1125 }
1126 if (ldecl->getKind() == Decl::Union && rdecl->getKind() == Decl::Union) {
1127 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1128 return true;
1129 }
1130 return false;
1131}
1132
1133bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) {
1134 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be
1135 // identically qualified and both shall be pointers to compatible types.
1136 if (lhs.getQualifiers() != rhs.getQualifiers())
1137 return false;
1138
1139 QualType ltype = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
1140 QualType rtype = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
1141
1142 return typesAreCompatible(ltype, rtype);
1143}
1144
1145// C++ 5.17p6: When the left opperand of an assignment operator denotes a
1146// reference to T, the operation assigns to the object of type T denoted by the
1147// reference.
1148bool ASTContext::referenceTypesAreCompatible(QualType lhs, QualType rhs) {
1149 QualType ltype = lhs;
1150
1151 if (lhs->isReferenceType())
1152 ltype = cast<ReferenceType>(lhs.getCanonicalType())->getReferenceeType();
1153
1154 QualType rtype = rhs;
1155
1156 if (rhs->isReferenceType())
1157 rtype = cast<ReferenceType>(rhs.getCanonicalType())->getReferenceeType();
1158
1159 return typesAreCompatible(ltype, rtype);
1160}
1161
1162bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) {
1163 const FunctionType *lbase = cast<FunctionType>(lhs.getCanonicalType());
1164 const FunctionType *rbase = cast<FunctionType>(rhs.getCanonicalType());
1165 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1166 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1167
1168 // first check the return types (common between C99 and K&R).
1169 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType()))
1170 return false;
1171
1172 if (lproto && rproto) { // two C99 style function prototypes
1173 unsigned lproto_nargs = lproto->getNumArgs();
1174 unsigned rproto_nargs = rproto->getNumArgs();
1175
1176 if (lproto_nargs != rproto_nargs)
1177 return false;
1178
1179 // both prototypes have the same number of arguments.
1180 if ((lproto->isVariadic() && !rproto->isVariadic()) ||
1181 (rproto->isVariadic() && !lproto->isVariadic()))
1182 return false;
1183
1184 // The use of ellipsis agree...now check the argument types.
1185 for (unsigned i = 0; i < lproto_nargs; i++)
1186 if (!typesAreCompatible(lproto->getArgType(i), rproto->getArgType(i)))
1187 return false;
1188 return true;
1189 }
1190 if (!lproto && !rproto) // two K&R style function decls, nothing to do.
1191 return true;
1192
1193 // we have a mixture of K&R style with C99 prototypes
1194 const FunctionTypeProto *proto = lproto ? lproto : rproto;
1195
1196 if (proto->isVariadic())
1197 return false;
1198
1199 // FIXME: Each parameter type T in the prototype must be compatible with the
1200 // type resulting from applying the usual argument conversions to T.
1201 return true;
1202}
1203
1204bool ASTContext::arrayTypesAreCompatible(QualType lhs, QualType rhs) {
1205 QualType ltype = cast<ArrayType>(lhs.getCanonicalType())->getElementType();
1206 QualType rtype = cast<ArrayType>(rhs.getCanonicalType())->getElementType();
1207
1208 if (!typesAreCompatible(ltype, rtype))
1209 return false;
1210
1211 // FIXME: If both types specify constant sizes, then the sizes must also be
1212 // the same. Even if the sizes are the same, GCC produces an error.
1213 return true;
1214}
1215
1216/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1217/// both shall have the identically qualified version of a compatible type.
1218/// C99 6.2.7p1: Two types have compatible types if their types are the
1219/// same. See 6.7.[2,3,5] for additional rules.
1220bool ASTContext::typesAreCompatible(QualType lhs, QualType rhs) {
1221 QualType lcanon = lhs.getCanonicalType();
1222 QualType rcanon = rhs.getCanonicalType();
1223
1224 // If two types are identical, they are are compatible
1225 if (lcanon == rcanon)
1226 return true;
1227
1228 // If the canonical type classes don't match, they can't be compatible
1229 if (lcanon->getTypeClass() != rcanon->getTypeClass()) {
1230 // For Objective-C, it is possible for two types to be compatible
1231 // when their classes don't match (when dealing with "id"). If either type
1232 // is an interface, we defer to objcTypesAreCompatible().
1233 if (lcanon->isObjcInterfaceType() || rcanon->isObjcInterfaceType())
1234 return objcTypesAreCompatible(lcanon, rcanon);
1235 return false;
1236 }
1237 switch (lcanon->getTypeClass()) {
1238 case Type::Pointer:
1239 return pointerTypesAreCompatible(lcanon, rcanon);
1240 case Type::Reference:
1241 return referenceTypesAreCompatible(lcanon, rcanon);
1242 case Type::ConstantArray:
1243 case Type::VariableArray:
1244 return arrayTypesAreCompatible(lcanon, rcanon);
1245 case Type::FunctionNoProto:
1246 case Type::FunctionProto:
1247 return functionTypesAreCompatible(lcanon, rcanon);
1248 case Type::Tagged: // handle structures, unions
1249 return tagTypesAreCompatible(lcanon, rcanon);
1250 case Type::Builtin:
1251 return builtinTypesAreCompatible(lcanon, rcanon);
1252 case Type::ObjcInterface:
1253 return interfaceTypesAreCompatible(lcanon, rcanon);
1254 default:
1255 assert(0 && "unexpected type");
1256 }
1257 return true; // should never get here...
1258}