blob: 72511bd7b01fcf79b2635e198b1d3d74b6f92d5c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
18#include "llvm/ADT/SmallVector.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000019#include "llvm/ADT/StringExtras.h"
20
Reid Spencer5f016e22007-07-11 17:01:13 +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;
Chris Lattner6d87fc62007-07-18 05:50:59 +000045 unsigned NumVector = 0, NumComplex = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000046 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
47
48 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Steve Naroff3f128ad2007-09-17 14:16:13 +000049 unsigned NumObjcInterfaces = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +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;
Chris Lattner6d87fc62007-07-18 05:50:59 +000059 else if (isa<ComplexType>(T))
60 ++NumComplex;
Reid Spencer5f016e22007-07-11 17:01:13 +000061 else if (isa<ArrayType>(T))
62 ++NumArray;
Chris Lattner6d87fc62007-07-18 05:50:59 +000063 else if (isa<VectorType>(T))
64 ++NumVector;
Reid Spencer5f016e22007-07-11 17:01:13 +000065 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 Naroff3f128ad2007-09-17 14:16:13 +000080 } else if (isa<ObjcInterfaceType>(T))
81 ++NumObjcInterfaces;
82 else {
Reid Spencer5f016e22007-07-11 17:01:13 +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);
Chris Lattner6d87fc62007-07-18 05:50:59 +000090 fprintf(stderr, " %d complex types\n", NumComplex);
Reid Spencer5f016e22007-07-11 17:01:13 +000091 fprintf(stderr, " %d array types\n", NumArray);
Chris Lattner6d87fc62007-07-18 05:50:59 +000092 fprintf(stderr, " %d vector types\n", NumVector);
Reid Spencer5f016e22007-07-11 17:01:13 +000093 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 Naroff3f128ad2007-09-17 14:16:13 +0000101 fprintf(stderr, " %d interface types\n", NumObjcInterfaces);
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
103 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
Chris Lattner6d87fc62007-07-18 05:50:59 +0000104 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff7e219e42007-10-15 14:41:52 +0000151
152 BuiltinVaListType = QualType();
153 ObjcIdType = QualType();
154 IdStructType = 0;
Steve Naroff21988912007-10-15 23:35:17 +0000155 ObjcConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000156
157 // void * type
158 VoidPtrTy = getPointerType(VoidTy);
Reid Spencer5f016e22007-07-11 17:01:13 +0000159}
160
Chris Lattner464175b2007-07-18 17:52:12 +0000161//===----------------------------------------------------------------------===//
162// Type Sizing and Analysis
163//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000164
165/// getTypeSize - Return the size of the specified type, in bits. This method
166/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000167std::pair<uint64_t, unsigned>
168ASTContext::getTypeInfo(QualType T, SourceLocation L) {
Chris Lattnera7674d82007-07-13 22:13:22 +0000169 T = T.getCanonicalType();
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000170 uint64_t Size;
171 unsigned Align;
Chris Lattnera7674d82007-07-13 22:13:22 +0000172 switch (T->getTypeClass()) {
Chris Lattner030d8842007-07-19 22:06:24 +0000173 case Type::TypeName: assert(0 && "Not a canonical type!");
Chris Lattner692233e2007-07-13 22:27:08 +0000174 case Type::FunctionNoProto:
175 case Type::FunctionProto:
Chris Lattner5d2a6302007-07-18 18:26:58 +0000176 default:
Chris Lattnerb1c2df92007-07-20 18:13:33 +0000177 assert(0 && "Incomplete types have no size!");
Steve Narofffb22d962007-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 Lattner030d8842007-07-19 22:06:24 +0000183 std::pair<uint64_t, unsigned> EltInfo =
Steve Narofffb22d962007-08-30 01:06:46 +0000184 getTypeInfo(CAT->getElementType(), L);
185 Size = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +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 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000197
Chris Lattnera7674d82007-07-13 22:13:22 +0000198 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 Lattner525a0502007-09-22 18:29:59 +0000201 const llvm::fltSemantics *F;
Chris Lattnera7674d82007-07-13 22:13:22 +0000202 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000203 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000204 case BuiltinType::Void:
205 assert(0 && "Incomplete types have no size!");
206 case BuiltinType::Bool: Target.getBoolInfo(Size, Align, L); break;
Chris Lattner692233e2007-07-13 22:27:08 +0000207 case BuiltinType::Char_S:
208 case BuiltinType::Char_U:
209 case BuiltinType::UChar:
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000210 case BuiltinType::SChar: Target.getCharInfo(Size, Align, L); break;
Chris Lattner692233e2007-07-13 22:27:08 +0000211 case BuiltinType::UShort:
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000212 case BuiltinType::Short: Target.getShortInfo(Size, Align, L); break;
Chris Lattner692233e2007-07-13 22:27:08 +0000213 case BuiltinType::UInt:
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000214 case BuiltinType::Int: Target.getIntInfo(Size, Align, L); break;
Chris Lattner692233e2007-07-13 22:27:08 +0000215 case BuiltinType::ULong:
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000216 case BuiltinType::Long: Target.getLongInfo(Size, Align, L); break;
Chris Lattner692233e2007-07-13 22:27:08 +0000217 case BuiltinType::ULongLong:
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000218 case BuiltinType::LongLong: Target.getLongLongInfo(Size, Align, L); break;
Chris Lattner525a0502007-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 Lattnera7674d82007-07-13 22:13:22 +0000222 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000223 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000224 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000225 case Type::Pointer: Target.getPointerInfo(Size, Align, L); break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000226 case Type::Reference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000227 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000228 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
229 // FIXME: This is wrong for struct layout!
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000230 return getTypeInfo(cast<ReferenceType>(T)->getReferenceeType(), L);
Chris Lattner5d2a6302007-07-18 18:26:58 +0000231
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 Lattner6cd862c2007-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 Lattnere00b18c2007-08-28 18:24:31 +0000248 return getTypeInfo(ED->getIntegerType(), L);
Chris Lattner6cd862c2007-08-27 17:38:00 +0000249 } else {
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000250 assert(0 && "Unimplemented type sizes!");
Chris Lattner6cd862c2007-08-27 17:38:00 +0000251 }
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000252 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000253 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000254
Chris Lattner464175b2007-07-18 17:52:12 +0000255 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000256 return std::make_pair(Size, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000257}
258
Chris Lattner464175b2007-07-18 17:52:12 +0000259/// 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 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000322
323 NewEntry->SetLayout(RecordSize, RecordAlign, FieldOffsets);
324 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000325}
326
Chris Lattnera7674d82007-07-13 22:13:22 +0000327//===----------------------------------------------------------------------===//
328// Type creation/memoization methods
329//===----------------------------------------------------------------------===//
330
331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332/// 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 Narofffb22d962007-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 Naroffc9406122007-08-30 18:10:14 +0000421 const llvm::APInt &ArySize,
422 ArrayType::ArraySizeModifier ASM,
423 unsigned EltTypeQuals) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 llvm::FoldingSetNodeID ID;
Steve Narofffb22d962007-08-30 01:06:46 +0000425 ConstantArrayType::Profile(ID, EltTy, ArySize);
Reid Spencer5f016e22007-07-11 17:01:13 +0000426
427 void *InsertPos = 0;
Steve Narofffb22d962007-08-30 01:06:46 +0000428 if (ConstantArrayType *ATP = ArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc9406122007-08-30 18:10:14 +0000435 Canonical = getConstantArrayType(EltTy.getCanonicalType(), ArySize,
436 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 // Get the new insert position for the node we care about.
Steve Narofffb22d962007-08-30 01:06:46 +0000438 ConstantArrayType *NewIP = ArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 assert(NewIP == 0 && "Shouldn't be in the map!");
440 }
441
Steve Naroffc9406122007-08-30 18:10:14 +0000442 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
443 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 ArrayTypes.InsertNode(New, InsertPos);
445 Types.push_back(New);
446 return QualType(New, 0);
447}
448
Steve Naroffbdbf7b02007-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 Naroffc9406122007-08-30 18:10:14 +0000451QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
452 ArrayType::ArraySizeModifier ASM,
453 unsigned EltTypeQuals) {
Ted Kremenek2bd24ba2007-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
458 ArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
459 ASM, EltTypeQuals);
460
461 // FIXME: Also add non-uniqued VLAs into a list of their own.
462 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 Narofffb22d962007-08-30 01:06:46 +0000497}
498
Steve Naroff73322922007-07-18 18:00:27 +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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 BuiltinType *baseType;
503
504 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +0000505 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
507 // Check if we've already instantiated a vector of this type.
508 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +0000509 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 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()) {
Steve Naroff73322922007-07-18 18:00:27 +0000518 Canonical = getVectorType(vecType.getCanonicalType(), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000519
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
Steve Naroff73322922007-07-18 18:00:27 +0000530/// 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
Reid Spencer5f016e22007-07-11 17:01:13 +0000561/// 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) +
Chris Lattner942cfd32007-07-20 18:48:28 +0000632 NumArgs*sizeof(QualType));
Reid Spencer5f016e22007-07-11 17:01:13 +0000633 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 Naroff3536b442007-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 Jahanian4b6c9052007-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 Lattner00bb2832007-10-11 03:36:41 +0000678 ObjcQualifiedInterfaceType *QType =
679 new ObjcQualifiedInterfaceType(IType, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +0000680 Types.push_back(QType);
681 ObjcQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
682 return QualType(QType, 0);
683}
684
Steve Naroff9752f252007-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 Naroff8d1a3b82007-08-01 17:20:42 +0000690QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
Steve Naroffd1861fd2007-07-31 12:34:36 +0000691 QualType Canonical = tofExpr->getType().getCanonicalType();
Steve Naroff9752f252007-08-01 18:02:17 +0000692 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
693 Types.push_back(toe);
694 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +0000695}
696
Steve Naroff9752f252007-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 Naroffd1861fd2007-07-31 12:34:36 +0000702QualType ASTContext::getTypeOfType(QualType tofType) {
703 QualType Canonical = tofType.getCanonicalType();
Steve Naroff9752f252007-08-01 18:02:17 +0000704 TypeOfType *tot = new TypeOfType(tofType, Canonical);
705 Types.push_back(tot);
706 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +0000707}
708
Reid Spencer5f016e22007-07-11 17:01:13 +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
Chris Lattner8b9023b2007-07-13 03:05:23 +0000729/// 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
Reid Spencer5f016e22007-07-11 17:01:13 +0000737/// 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 Naroff716c7302007-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 Narofff1448a02007-08-27 01:27:54 +0000790QualType ASTContext::getFloatingTypeOfSizeWithinDomain(
791 QualType typeSize, QualType typeDomain) const {
792 if (typeDomain->isComplexType()) {
793 switch (getFloatingRank(typeSize)) {
Steve Naroff716c7302007-08-27 01:41:48 +0000794 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +0000795 case FloatRank: return FloatComplexTy;
796 case DoubleRank: return DoubleComplexTy;
797 case LongDoubleRank: return LongDoubleComplexTy;
798 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 }
Steve Narofff1448a02007-08-27 01:27:54 +0000800 if (typeDomain->isRealFloatingType()) {
801 switch (getFloatingRank(typeSize)) {
Steve Naroff716c7302007-08-27 01:41:48 +0000802 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-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 Lattnerb1776cb2007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000812}
813
Steve Narofffb0d4962007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlsson71993dd2007-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 Narofff38661e2007-09-14 02:20:46 +0000873 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000874
875 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
876 }
877
878 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +0000879}
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000880
Anders Carlssone8c49532007-10-29 06:33:42 +0000881// This returns true if a type has been typedefed to BOOL:
882// typedef <type> BOOL;
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000883static bool isTypeTypedefedAsBOOL(QualType T)
884{
Anders Carlssone8c49532007-10-29 06:33:42 +0000885 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000886 if (!strcmp(TT->getDecl()->getName(), "BOOL"))
887 return true;
888
889 return false;
890}
891
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000892/// getObjcEncodingTypeSize returns size of type for objective-c encoding
893/// purpose.
894int ASTContext::getObjcEncodingTypeSize(QualType type) {
895 SourceLocation Loc;
896 uint64_t sz = getTypeSize(type, Loc);
897
898 // Make all integer and enum types at least as large as an int
899 if (sz > 0 && type->isIntegralType())
900 sz = std::max(sz, getTypeSize(IntTy, Loc));
901 // Treat arrays as pointers, since that's how they're passed in.
902 else if (type->isArrayType())
903 sz = getTypeSize(VoidPtrTy, Loc);
904 return sz / getTypeSize(CharTy, Loc);
905}
906
907/// getObjcEncodingForMethodDecl - Return the encoded type for this method
908/// declaration.
909void ASTContext::getObjcEncodingForMethodDecl(ObjcMethodDecl *Decl,
910 std::string& S)
911{
912 // TODO: First encode type qualifer, 'in', 'inout', etc. for the return type.
913 // Encode result type.
914 getObjcEncodingForType(Decl->getResultType(), S);
915 // Compute size of all parameters.
916 // Start with computing size of a pointer in number of bytes.
917 // FIXME: There might(should) be a better way of doing this computation!
918 SourceLocation Loc;
919 int PtrSize = getTypeSize(VoidPtrTy, Loc) / getTypeSize(CharTy, Loc);
920 // The first two arguments (self and _cmd) are pointers; account for
921 // their size.
922 int ParmOffset = 2 * PtrSize;
923 int NumOfParams = Decl->getNumParams();
924 for (int i = 0; i < NumOfParams; i++) {
925 QualType PType = Decl->getParamDecl(i)->getType();
926 int sz = getObjcEncodingTypeSize (PType);
927 assert (sz > 0 && "getObjcEncodingForMethodDecl - Incomplete param type");
928 ParmOffset += sz;
929 }
930 S += llvm::utostr(ParmOffset);
931 S += "@0:";
932 S += llvm::utostr(PtrSize);
933
934 // Argument types.
935 ParmOffset = 2 * PtrSize;
936 for (int i = 0; i < NumOfParams; i++) {
937 QualType PType = Decl->getParamDecl(i)->getType();
938 // TODO: Process argument qualifiers for user supplied arguments; such as,
939 // 'in', 'inout', etc.
940 getObjcEncodingForType(PType, S);
941 S += llvm::utostr(ParmOffset);
942 ParmOffset += getObjcEncodingTypeSize(PType);
943 }
944}
945
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000946void ASTContext::getObjcEncodingForType(QualType T, std::string& S) const
947{
Anders Carlssone8c49532007-10-29 06:33:42 +0000948 // FIXME: This currently doesn't encode:
949 // @ An object (whether statically typed or typed id)
950 // # A class object (Class)
951 // : A method selector (SEL)
952 // {name=type...} A structure
953 // (name=type...) A union
954 // bnum A bit field of num bits
955
956 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000957 char encoding;
958 switch (BT->getKind()) {
959 case BuiltinType::Void:
960 encoding = 'v';
961 break;
962 case BuiltinType::Bool:
963 encoding = 'B';
964 break;
965 case BuiltinType::Char_U:
966 case BuiltinType::UChar:
967 encoding = 'C';
968 break;
969 case BuiltinType::UShort:
970 encoding = 'S';
971 break;
972 case BuiltinType::UInt:
973 encoding = 'I';
974 break;
975 case BuiltinType::ULong:
976 encoding = 'L';
977 break;
978 case BuiltinType::ULongLong:
979 encoding = 'Q';
980 break;
981 case BuiltinType::Char_S:
982 case BuiltinType::SChar:
983 encoding = 'c';
984 break;
985 case BuiltinType::Short:
986 encoding = 's';
987 break;
988 case BuiltinType::Int:
989 encoding = 'i';
990 break;
991 case BuiltinType::Long:
992 encoding = 'l';
993 break;
994 case BuiltinType::LongLong:
995 encoding = 'q';
996 break;
997 case BuiltinType::Float:
998 encoding = 'f';
999 break;
1000 case BuiltinType::Double:
1001 encoding = 'd';
1002 break;
1003 case BuiltinType::LongDouble:
1004 encoding = 'd';
1005 break;
1006 default:
1007 assert(0 && "Unhandled builtin type kind");
1008 }
1009
1010 S += encoding;
Anders Carlssone8c49532007-10-29 06:33:42 +00001011 } else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001012 QualType PointeeTy = PT->getPointeeType();
1013
1014 if (PointeeTy->isCharType()) {
1015 // char pointer types should be encoded as '*' unless it is a
1016 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00001017 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001018 S += '*';
1019 return;
1020 }
1021 }
1022
1023 S += '^';
1024 getObjcEncodingForType(PT->getPointeeType(), S);
Anders Carlssone8c49532007-10-29 06:33:42 +00001025 } else if (const ArrayType *AT = T->getAsArrayType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001026 S += '[';
1027
1028 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1029 S += llvm::utostr(CAT->getSize().getZExtValue());
1030 else
1031 assert(0 && "Unhandled array type!");
1032
1033 getObjcEncodingForType(AT->getElementType(), S);
1034 S += ']';
1035 } else
Anders Carlssone8c49532007-10-29 06:33:42 +00001036 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001037}
1038
Anders Carlssonb2cf3572007-10-11 01:00:40 +00001039void ASTContext::setBuiltinVaListType(QualType T)
1040{
1041 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1042
1043 BuiltinVaListType = T;
1044}
1045
Steve Naroff7e219e42007-10-15 14:41:52 +00001046void ASTContext::setObjcIdType(TypedefDecl *TD)
1047{
1048 assert(ObjcIdType.isNull() && "'id' type already set!");
1049
1050 ObjcIdType = getTypedefType(TD);
1051
1052 // typedef struct objc_object *id;
1053 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1054 assert(ptr && "'id' incorrectly typed");
1055 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1056 assert(rec && "'id' incorrectly typed");
1057 IdStructType = rec;
1058}
1059
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001060void ASTContext::setObjcSelType(TypedefDecl *TD)
1061{
1062 assert(ObjcSelType.isNull() && "'SEL' type already set!");
1063
1064 ObjcSelType = getTypedefType(TD);
1065
1066 // typedef struct objc_selector *SEL;
1067 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1068 assert(ptr && "'SEL' incorrectly typed");
1069 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1070 assert(rec && "'SEL' incorrectly typed");
1071 SelStructType = rec;
1072}
1073
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00001074void ASTContext::setObjcProtoType(TypedefDecl *TD)
1075{
1076 assert(ObjcProtoType.isNull() && "'Protocol' type already set!");
1077
1078 // typedef struct Protocol Protocol;
1079 ObjcProtoType = TD->getUnderlyingType();
1080 // Protocol * type
1081 ObjcProtoType = getPointerType(ObjcProtoType);
1082 ProtoStructType = TD->getUnderlyingType()->getAsStructureType();
1083}
1084
Steve Naroff21988912007-10-15 23:35:17 +00001085void ASTContext::setObjcConstantStringInterface(ObjcInterfaceDecl *Decl) {
1086 assert(ObjcConstantStringType.isNull() &&
1087 "'NSConstantString' type already set!");
1088
1089 ObjcConstantStringType = getObjcInterfaceType(Decl);
1090}
1091
Steve Naroffec0550f2007-10-15 20:41:53 +00001092bool ASTContext::builtinTypesAreCompatible(QualType lhs, QualType rhs) {
1093 const BuiltinType *lBuiltin = lhs->getAsBuiltinType();
1094 const BuiltinType *rBuiltin = rhs->getAsBuiltinType();
1095
1096 return lBuiltin->getKind() == rBuiltin->getKind();
1097}
1098
1099
1100bool ASTContext::objcTypesAreCompatible(QualType lhs, QualType rhs) {
1101 if (lhs->isObjcInterfaceType() && isObjcIdType(rhs))
1102 return true;
1103 else if (isObjcIdType(lhs) && rhs->isObjcInterfaceType())
1104 return true;
1105 return false;
1106}
1107
1108bool ASTContext::interfaceTypesAreCompatible(QualType lhs, QualType rhs) {
1109 return true; // FIXME: IMPLEMENT.
1110}
1111
1112// C99 6.2.7p1: If both are complete types, then the following additional
1113// requirements apply...FIXME (handle compatibility across source files).
1114bool ASTContext::tagTypesAreCompatible(QualType lhs, QualType rhs) {
1115 TagDecl *ldecl = cast<TagType>(lhs.getCanonicalType())->getDecl();
1116 TagDecl *rdecl = cast<TagType>(rhs.getCanonicalType())->getDecl();
1117
1118 if (ldecl->getKind() == Decl::Struct && rdecl->getKind() == Decl::Struct) {
1119 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1120 return true;
1121 }
1122 if (ldecl->getKind() == Decl::Union && rdecl->getKind() == Decl::Union) {
1123 if (ldecl->getIdentifier() == rdecl->getIdentifier())
1124 return true;
1125 }
1126 return false;
1127}
1128
1129bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) {
1130 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be
1131 // identically qualified and both shall be pointers to compatible types.
1132 if (lhs.getQualifiers() != rhs.getQualifiers())
1133 return false;
1134
1135 QualType ltype = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
1136 QualType rtype = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
1137
1138 return typesAreCompatible(ltype, rtype);
1139}
1140
1141// C++ 5.17p6: When the left opperand of an assignment operator denotes a
1142// reference to T, the operation assigns to the object of type T denoted by the
1143// reference.
1144bool ASTContext::referenceTypesAreCompatible(QualType lhs, QualType rhs) {
1145 QualType ltype = lhs;
1146
1147 if (lhs->isReferenceType())
1148 ltype = cast<ReferenceType>(lhs.getCanonicalType())->getReferenceeType();
1149
1150 QualType rtype = rhs;
1151
1152 if (rhs->isReferenceType())
1153 rtype = cast<ReferenceType>(rhs.getCanonicalType())->getReferenceeType();
1154
1155 return typesAreCompatible(ltype, rtype);
1156}
1157
1158bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) {
1159 const FunctionType *lbase = cast<FunctionType>(lhs.getCanonicalType());
1160 const FunctionType *rbase = cast<FunctionType>(rhs.getCanonicalType());
1161 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1162 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1163
1164 // first check the return types (common between C99 and K&R).
1165 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType()))
1166 return false;
1167
1168 if (lproto && rproto) { // two C99 style function prototypes
1169 unsigned lproto_nargs = lproto->getNumArgs();
1170 unsigned rproto_nargs = rproto->getNumArgs();
1171
1172 if (lproto_nargs != rproto_nargs)
1173 return false;
1174
1175 // both prototypes have the same number of arguments.
1176 if ((lproto->isVariadic() && !rproto->isVariadic()) ||
1177 (rproto->isVariadic() && !lproto->isVariadic()))
1178 return false;
1179
1180 // The use of ellipsis agree...now check the argument types.
1181 for (unsigned i = 0; i < lproto_nargs; i++)
1182 if (!typesAreCompatible(lproto->getArgType(i), rproto->getArgType(i)))
1183 return false;
1184 return true;
1185 }
1186 if (!lproto && !rproto) // two K&R style function decls, nothing to do.
1187 return true;
1188
1189 // we have a mixture of K&R style with C99 prototypes
1190 const FunctionTypeProto *proto = lproto ? lproto : rproto;
1191
1192 if (proto->isVariadic())
1193 return false;
1194
1195 // FIXME: Each parameter type T in the prototype must be compatible with the
1196 // type resulting from applying the usual argument conversions to T.
1197 return true;
1198}
1199
1200bool ASTContext::arrayTypesAreCompatible(QualType lhs, QualType rhs) {
1201 QualType ltype = cast<ArrayType>(lhs.getCanonicalType())->getElementType();
1202 QualType rtype = cast<ArrayType>(rhs.getCanonicalType())->getElementType();
1203
1204 if (!typesAreCompatible(ltype, rtype))
1205 return false;
1206
1207 // FIXME: If both types specify constant sizes, then the sizes must also be
1208 // the same. Even if the sizes are the same, GCC produces an error.
1209 return true;
1210}
1211
1212/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1213/// both shall have the identically qualified version of a compatible type.
1214/// C99 6.2.7p1: Two types have compatible types if their types are the
1215/// same. See 6.7.[2,3,5] for additional rules.
1216bool ASTContext::typesAreCompatible(QualType lhs, QualType rhs) {
1217 QualType lcanon = lhs.getCanonicalType();
1218 QualType rcanon = rhs.getCanonicalType();
1219
1220 // If two types are identical, they are are compatible
1221 if (lcanon == rcanon)
1222 return true;
1223
1224 // If the canonical type classes don't match, they can't be compatible
1225 if (lcanon->getTypeClass() != rcanon->getTypeClass()) {
1226 // For Objective-C, it is possible for two types to be compatible
1227 // when their classes don't match (when dealing with "id"). If either type
1228 // is an interface, we defer to objcTypesAreCompatible().
1229 if (lcanon->isObjcInterfaceType() || rcanon->isObjcInterfaceType())
1230 return objcTypesAreCompatible(lcanon, rcanon);
1231 return false;
1232 }
1233 switch (lcanon->getTypeClass()) {
1234 case Type::Pointer:
1235 return pointerTypesAreCompatible(lcanon, rcanon);
1236 case Type::Reference:
1237 return referenceTypesAreCompatible(lcanon, rcanon);
1238 case Type::ConstantArray:
1239 case Type::VariableArray:
1240 return arrayTypesAreCompatible(lcanon, rcanon);
1241 case Type::FunctionNoProto:
1242 case Type::FunctionProto:
1243 return functionTypesAreCompatible(lcanon, rcanon);
1244 case Type::Tagged: // handle structures, unions
1245 return tagTypesAreCompatible(lcanon, rcanon);
1246 case Type::Builtin:
1247 return builtinTypesAreCompatible(lcanon, rcanon);
1248 case Type::ObjcInterface:
1249 return interfaceTypesAreCompatible(lcanon, rcanon);
1250 default:
1251 assert(0 && "unexpected type");
1252 }
1253 return true; // should never get here...
1254}