1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Bitcode/Serialize.h"
21 #include "llvm/Bitcode/Deserialize.h"
23 using namespace clang;
26 FloatRank, DoubleRank, LongDoubleRank
29 ASTContext::~ASTContext() {
30 // Deallocate all the types.
31 while (!Types.empty()) {
32 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(Types.back())) {
33 // Destroy the object, but don't call delete. These are malloc'd.
34 FT->~FunctionTypeProto();
43 void ASTContext::PrintStats() const {
44 fprintf(stderr, "*** AST Context Stats:\n");
45 fprintf(stderr, " %d types total.\n", (int)Types.size());
46 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
47 unsigned NumVector = 0, NumComplex = 0;
48 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
50 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
51 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
52 unsigned NumObjCQualifiedIds = 0;
54 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
56 if (isa<BuiltinType>(T))
58 else if (isa<PointerType>(T))
60 else if (isa<ReferenceType>(T))
62 else if (isa<ComplexType>(T))
64 else if (isa<ArrayType>(T))
66 else if (isa<VectorType>(T))
68 else if (isa<FunctionTypeNoProto>(T))
70 else if (isa<FunctionTypeProto>(T))
72 else if (isa<TypedefType>(T))
74 else if (TagType *TT = dyn_cast<TagType>(T)) {
76 switch (TT->getDecl()->getKind()) {
77 default: assert(0 && "Unknown tagged type!");
78 case Decl::Struct: ++NumTagStruct; break;
79 case Decl::Union: ++NumTagUnion; break;
80 case Decl::Class: ++NumTagClass; break;
81 case Decl::Enum: ++NumTagEnum; break;
83 } else if (isa<ObjCInterfaceType>(T))
85 else if (isa<ObjCQualifiedInterfaceType>(T))
86 ++NumObjCQualifiedInterfaces;
87 else if (isa<ObjCQualifiedIdType>(T))
88 ++NumObjCQualifiedIds;
90 QualType(T, 0).dump();
91 assert(0 && "Unknown type!");
95 fprintf(stderr, " %d builtin types\n", NumBuiltin);
96 fprintf(stderr, " %d pointer types\n", NumPointer);
97 fprintf(stderr, " %d reference types\n", NumReference);
98 fprintf(stderr, " %d complex types\n", NumComplex);
99 fprintf(stderr, " %d array types\n", NumArray);
100 fprintf(stderr, " %d vector types\n", NumVector);
101 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
102 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
103 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
104 fprintf(stderr, " %d tagged types\n", NumTagged);
105 fprintf(stderr, " %d struct types\n", NumTagStruct);
106 fprintf(stderr, " %d union types\n", NumTagUnion);
107 fprintf(stderr, " %d class types\n", NumTagClass);
108 fprintf(stderr, " %d enum types\n", NumTagEnum);
109 fprintf(stderr, " %d interface types\n", NumObjCInterfaces);
110 fprintf(stderr, " %d protocol qualified interface types\n",
111 NumObjCQualifiedInterfaces);
112 fprintf(stderr, " %d protocol qualified id types\n",
113 NumObjCQualifiedIds);
114 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
115 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
116 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
117 NumFunctionP*sizeof(FunctionTypeProto)+
118 NumFunctionNP*sizeof(FunctionTypeNoProto)+
119 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)));
123 void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
124 Types.push_back((R = QualType(new BuiltinType(K),0)).getTypePtr());
127 void ASTContext::InitBuiltinTypes() {
128 assert(VoidTy.isNull() && "Context reinitialized?");
131 InitBuiltinType(VoidTy, BuiltinType::Void);
134 InitBuiltinType(BoolTy, BuiltinType::Bool);
136 if (Target.isCharSigned())
137 InitBuiltinType(CharTy, BuiltinType::Char_S);
139 InitBuiltinType(CharTy, BuiltinType::Char_U);
141 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
142 InitBuiltinType(ShortTy, BuiltinType::Short);
143 InitBuiltinType(IntTy, BuiltinType::Int);
144 InitBuiltinType(LongTy, BuiltinType::Long);
145 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
148 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
149 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
150 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
151 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
152 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
155 InitBuiltinType(FloatTy, BuiltinType::Float);
156 InitBuiltinType(DoubleTy, BuiltinType::Double);
157 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
160 FloatComplexTy = getComplexType(FloatTy);
161 DoubleComplexTy = getComplexType(DoubleTy);
162 LongDoubleComplexTy = getComplexType(LongDoubleTy);
164 BuiltinVaListType = QualType();
165 ObjCIdType = QualType();
167 ObjCClassType = QualType();
170 ObjCConstantStringType = QualType();
173 VoidPtrTy = getPointerType(VoidTy);
176 //===----------------------------------------------------------------------===//
177 // Type Sizing and Analysis
178 //===----------------------------------------------------------------------===//
180 /// getTypeSize - Return the size of the specified type, in bits. This method
181 /// does not work on incomplete types.
182 std::pair<uint64_t, unsigned>
183 ASTContext::getTypeInfo(QualType T) {
184 T = T.getCanonicalType();
187 switch (T->getTypeClass()) {
188 case Type::TypeName: assert(0 && "Not a canonical type!");
189 case Type::FunctionNoProto:
190 case Type::FunctionProto:
192 assert(0 && "Incomplete types have no size!");
193 case Type::VariableArray:
194 assert(0 && "VLAs not implemented yet!");
195 case Type::ConstantArray: {
196 ConstantArrayType *CAT = cast<ConstantArrayType>(T);
198 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
199 Width = EltInfo.first*CAT->getSize().getZExtValue();
200 Align = EltInfo.second;
203 case Type::OCUVector:
205 std::pair<uint64_t, unsigned> EltInfo =
206 getTypeInfo(cast<VectorType>(T)->getElementType());
207 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
208 // FIXME: Vector alignment is not the alignment of its elements.
209 Align = EltInfo.second;
214 // FIXME: need to use TargetInfo to derive the target specific sizes. This
215 // implementation will suffice for play with vector support.
216 switch (cast<BuiltinType>(T)->getKind()) {
217 default: assert(0 && "Unknown builtin type!");
218 case BuiltinType::Void:
219 assert(0 && "Incomplete types have no size!");
220 case BuiltinType::Bool:
221 Width = Target.getBoolWidth();
222 Align = Target.getBoolAlign();
224 case BuiltinType::Char_S:
225 case BuiltinType::Char_U:
226 case BuiltinType::UChar:
227 case BuiltinType::SChar:
228 Width = Target.getCharWidth();
229 Align = Target.getCharAlign();
231 case BuiltinType::UShort:
232 case BuiltinType::Short:
233 Width = Target.getShortWidth();
234 Align = Target.getShortAlign();
236 case BuiltinType::UInt:
237 case BuiltinType::Int:
238 Width = Target.getIntWidth();
239 Align = Target.getIntAlign();
241 case BuiltinType::ULong:
242 case BuiltinType::Long:
243 Width = Target.getLongWidth();
244 Align = Target.getLongAlign();
246 case BuiltinType::ULongLong:
247 case BuiltinType::LongLong:
248 Width = Target.getLongLongWidth();
249 Align = Target.getLongLongAlign();
251 case BuiltinType::Float:
252 Width = Target.getFloatWidth();
253 Align = Target.getFloatAlign();
255 case BuiltinType::Double:
256 Width = Target.getDoubleWidth();
257 Align = Target.getDoubleAlign();
259 case BuiltinType::LongDouble:
260 Width = Target.getLongDoubleWidth();
261 Align = Target.getLongDoubleAlign();
266 // FIXME: Pointers into different addr spaces could have different sizes and
267 // alignment requirements: getPointerInfo should take an AddrSpace.
268 return getTypeInfo(QualType(cast<ASQualType>(T)->getBaseType(), 0));
269 case Type::ObjCQualifiedId:
270 Width = Target.getPointerWidth(0);
271 Align = Target.getPointerAlign(0);
273 case Type::Pointer: {
274 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
275 Width = Target.getPointerWidth(AS);
276 Align = Target.getPointerAlign(AS);
279 case Type::Reference:
280 // "When applied to a reference or a reference type, the result is the size
281 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
282 // FIXME: This is wrong for struct layout: a reference in a struct has
284 return getTypeInfo(cast<ReferenceType>(T)->getReferenceeType());
286 case Type::Complex: {
287 // Complex types have the same alignment as their elements, but twice the
289 std::pair<uint64_t, unsigned> EltInfo =
290 getTypeInfo(cast<ComplexType>(T)->getElementType());
291 Width = EltInfo.first*2;
292 Align = EltInfo.second;
296 TagType *TT = cast<TagType>(T);
297 if (RecordType *RT = dyn_cast<RecordType>(TT)) {
298 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
299 Width = Layout.getSize();
300 Align = Layout.getAlignment();
301 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(TT->getDecl())) {
302 return getTypeInfo(ED->getIntegerType());
304 assert(0 && "Unimplemented type sizes!");
309 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
310 return std::make_pair(Width, Align);
313 /// getASTRecordLayout - Get or compute information about the layout of the
314 /// specified record (struct/union/class), which indicates its size and field
315 /// position information.
316 const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
317 assert(D->isDefinition() && "Cannot get layout of forward declarations!");
319 // Look up this layout, if already laid out, return what we have.
320 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
321 if (Entry) return *Entry;
323 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
324 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
325 ASTRecordLayout *NewEntry = new ASTRecordLayout();
328 uint64_t *FieldOffsets = new uint64_t[D->getNumMembers()];
329 uint64_t RecordSize = 0;
330 unsigned RecordAlign = 8; // Default alignment = 1 byte = 8 bits.
332 if (D->getKind() != Decl::Union) {
333 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
334 RecordAlign = std::max(RecordAlign, AA->getAlignment());
336 bool StructIsPacked = D->getAttr<PackedAttr>();
338 // Layout each field, for now, just sequentially, respecting alignment. In
339 // the future, this will need to be tweakable by targets.
340 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
341 const FieldDecl *FD = D->getMember(i);
342 bool FieldIsPacked = StructIsPacked || FD->getAttr<PackedAttr>();
346 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
349 BitWidthExpr->isIntegerConstantExpr(I, *this);
350 assert (BitWidthIsICE && "Invalid BitField size expression");
351 FieldSize = I.getZExtValue();
353 std::pair<uint64_t, unsigned> TypeInfo = getTypeInfo(FD->getType());
354 uint64_t TypeSize = TypeInfo.first;
356 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
357 FieldAlign = AA->getAlignment();
358 else if (FieldIsPacked)
361 // FIXME: This is X86 specific, use 32-bit alignment for long long.
362 if (FD->getType()->isIntegerType() && TypeInfo.second > 32)
365 FieldAlign = TypeInfo.second;
368 // Check if we need to add padding to give the field the correct
370 if (RecordSize % FieldAlign + FieldSize > TypeSize)
371 RecordSize = (RecordSize+FieldAlign-1) & ~(FieldAlign-1);
374 if (FD->getType()->isIncompleteType()) {
375 // This must be a flexible array member; we can't directly
376 // query getTypeInfo about these, so we figure it out here.
377 // Flexible array members don't have any size, but they
378 // have to be aligned appropriately for their element type.
380 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
381 FieldAlign = AA->getAlignment();
382 else if (FieldIsPacked)
385 const ArrayType* ATy = FD->getType()->getAsArrayType();
386 FieldAlign = getTypeAlign(ATy->getElementType());
390 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType());
391 FieldSize = FieldInfo.first;
393 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
394 FieldAlign = AA->getAlignment();
395 else if (FieldIsPacked)
398 FieldAlign = FieldInfo.second;
401 // Round up the current record size to the field's alignment boundary.
402 RecordSize = (RecordSize+FieldAlign-1) & ~(FieldAlign-1);
405 // Place this field at the current location.
406 FieldOffsets[i] = RecordSize;
408 // Reserve space for this field.
409 RecordSize += FieldSize;
411 // Remember max struct/class alignment.
412 RecordAlign = std::max(RecordAlign, FieldAlign);
415 // Finally, round the size of the total struct up to the alignment of the
417 RecordSize = (RecordSize+RecordAlign-1) & ~(RecordAlign-1);
419 // Union layout just puts each member at the start of the record.
420 for (unsigned i = 0, e = D->getNumMembers(); i != e; ++i) {
421 const FieldDecl *FD = D->getMember(i);
422 std::pair<uint64_t, unsigned> FieldInfo = getTypeInfo(FD->getType());
423 uint64_t FieldSize = FieldInfo.first;
424 unsigned FieldAlign = FieldInfo.second;
426 // FIXME: This is X86 specific, use 32-bit alignment for long long.
427 if (FD->getType()->isIntegerType() && FieldAlign > 32)
430 // Round up the current record size to the field's alignment boundary.
431 RecordSize = std::max(RecordSize, FieldSize);
433 // Place this field at the start of the record.
436 // Remember max struct/class alignment.
437 RecordAlign = std::max(RecordAlign, FieldAlign);
441 NewEntry->SetLayout(RecordSize, RecordAlign, FieldOffsets);
445 //===----------------------------------------------------------------------===//
446 // Type creation/memoization methods
447 //===----------------------------------------------------------------------===//
449 QualType ASTContext::getASQualType(QualType T, unsigned AddressSpace) {
450 if (T.getCanonicalType().getAddressSpace() == AddressSpace)
453 // Type's cannot have multiple ASQuals, therefore we know we only have to deal
454 // with CVR qualifiers from here on out.
455 assert(T.getCanonicalType().getAddressSpace() == 0 &&
456 "Type is already address space qualified");
458 // Check if we've already instantiated an address space qual'd type of this
460 llvm::FoldingSetNodeID ID;
461 ASQualType::Profile(ID, T.getTypePtr(), AddressSpace);
463 if (ASQualType *ASQy = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos))
464 return QualType(ASQy, 0);
466 // If the base type isn't canonical, this won't be a canonical type either,
467 // so fill in the canonical type field.
469 if (!T->isCanonical()) {
470 Canonical = getASQualType(T.getCanonicalType(), AddressSpace);
472 // Get the new insert position for the node we care about.
473 ASQualType *NewIP = ASQualTypes.FindNodeOrInsertPos(ID, InsertPos);
474 assert(NewIP == 0 && "Shouldn't be in the map!");
476 ASQualType *New = new ASQualType(T.getTypePtr(), Canonical, AddressSpace);
477 ASQualTypes.InsertNode(New, InsertPos);
478 Types.push_back(New);
479 return QualType(New, T.getCVRQualifiers());
483 /// getComplexType - Return the uniqued reference to the type for a complex
484 /// number with the specified element type.
485 QualType ASTContext::getComplexType(QualType T) {
486 // Unique pointers, to guarantee there is only one pointer of a particular
488 llvm::FoldingSetNodeID ID;
489 ComplexType::Profile(ID, T);
492 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
493 return QualType(CT, 0);
495 // If the pointee type isn't canonical, this won't be a canonical type either,
496 // so fill in the canonical type field.
498 if (!T->isCanonical()) {
499 Canonical = getComplexType(T.getCanonicalType());
501 // Get the new insert position for the node we care about.
502 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
503 assert(NewIP == 0 && "Shouldn't be in the map!");
505 ComplexType *New = new ComplexType(T, Canonical);
506 Types.push_back(New);
507 ComplexTypes.InsertNode(New, InsertPos);
508 return QualType(New, 0);
512 /// getPointerType - Return the uniqued reference to the type for a pointer to
513 /// the specified type.
514 QualType ASTContext::getPointerType(QualType T) {
515 // Unique pointers, to guarantee there is only one pointer of a particular
517 llvm::FoldingSetNodeID ID;
518 PointerType::Profile(ID, T);
521 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
522 return QualType(PT, 0);
524 // If the pointee type isn't canonical, this won't be a canonical type either,
525 // so fill in the canonical type field.
527 if (!T->isCanonical()) {
528 Canonical = getPointerType(T.getCanonicalType());
530 // Get the new insert position for the node we care about.
531 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
532 assert(NewIP == 0 && "Shouldn't be in the map!");
534 PointerType *New = new PointerType(T, Canonical);
535 Types.push_back(New);
536 PointerTypes.InsertNode(New, InsertPos);
537 return QualType(New, 0);
540 /// getReferenceType - Return the uniqued reference to the type for a reference
541 /// to the specified type.
542 QualType ASTContext::getReferenceType(QualType T) {
543 // Unique pointers, to guarantee there is only one pointer of a particular
545 llvm::FoldingSetNodeID ID;
546 ReferenceType::Profile(ID, T);
549 if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
550 return QualType(RT, 0);
552 // If the referencee type isn't canonical, this won't be a canonical type
553 // either, so fill in the canonical type field.
555 if (!T->isCanonical()) {
556 Canonical = getReferenceType(T.getCanonicalType());
558 // Get the new insert position for the node we care about.
559 ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
560 assert(NewIP == 0 && "Shouldn't be in the map!");
563 ReferenceType *New = new ReferenceType(T, Canonical);
564 Types.push_back(New);
565 ReferenceTypes.InsertNode(New, InsertPos);
566 return QualType(New, 0);
569 /// getConstantArrayType - Return the unique reference to the type for an
570 /// array of the specified element type.
571 QualType ASTContext::getConstantArrayType(QualType EltTy,
572 const llvm::APInt &ArySize,
573 ArrayType::ArraySizeModifier ASM,
574 unsigned EltTypeQuals) {
575 llvm::FoldingSetNodeID ID;
576 ConstantArrayType::Profile(ID, EltTy, ArySize);
579 if (ConstantArrayType *ATP =
580 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
581 return QualType(ATP, 0);
583 // If the element type isn't canonical, this won't be a canonical type either,
584 // so fill in the canonical type field.
586 if (!EltTy->isCanonical()) {
587 Canonical = getConstantArrayType(EltTy.getCanonicalType(), ArySize,
589 // Get the new insert position for the node we care about.
590 ConstantArrayType *NewIP =
591 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
593 assert(NewIP == 0 && "Shouldn't be in the map!");
596 ConstantArrayType *New = new ConstantArrayType(EltTy, Canonical, ArySize,
598 ConstantArrayTypes.InsertNode(New, InsertPos);
599 Types.push_back(New);
600 return QualType(New, 0);
603 /// getVariableArrayType - Returns a non-unique reference to the type for a
604 /// variable array of the specified element type.
605 QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
606 ArrayType::ArraySizeModifier ASM,
607 unsigned EltTypeQuals) {
608 // Since we don't unique expressions, it isn't possible to unique VLA's
609 // that have an expression provided for their size.
611 VariableArrayType *New = new VariableArrayType(EltTy, QualType(), NumElts,
614 VariableArrayTypes.push_back(New);
615 Types.push_back(New);
616 return QualType(New, 0);
619 QualType ASTContext::getIncompleteArrayType(QualType EltTy,
620 ArrayType::ArraySizeModifier ASM,
621 unsigned EltTypeQuals) {
622 llvm::FoldingSetNodeID ID;
623 IncompleteArrayType::Profile(ID, EltTy);
626 if (IncompleteArrayType *ATP =
627 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
628 return QualType(ATP, 0);
630 // If the element type isn't canonical, this won't be a canonical type
631 // either, so fill in the canonical type field.
634 if (!EltTy->isCanonical()) {
635 Canonical = getIncompleteArrayType(EltTy.getCanonicalType(),
638 // Get the new insert position for the node we care about.
639 IncompleteArrayType *NewIP =
640 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
642 assert(NewIP == 0 && "Shouldn't be in the map!");
645 IncompleteArrayType *New = new IncompleteArrayType(EltTy, Canonical,
648 IncompleteArrayTypes.InsertNode(New, InsertPos);
649 Types.push_back(New);
650 return QualType(New, 0);
653 /// getVectorType - Return the unique reference to a vector type of
654 /// the specified element type and size. VectorType must be a built-in type.
655 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
656 BuiltinType *baseType;
658 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
659 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
661 // Check if we've already instantiated a vector of this type.
662 llvm::FoldingSetNodeID ID;
663 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
665 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
666 return QualType(VTP, 0);
668 // If the element type isn't canonical, this won't be a canonical type either,
669 // so fill in the canonical type field.
671 if (!vecType->isCanonical()) {
672 Canonical = getVectorType(vecType.getCanonicalType(), NumElts);
674 // Get the new insert position for the node we care about.
675 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
676 assert(NewIP == 0 && "Shouldn't be in the map!");
678 VectorType *New = new VectorType(vecType, NumElts, Canonical);
679 VectorTypes.InsertNode(New, InsertPos);
680 Types.push_back(New);
681 return QualType(New, 0);
684 /// getOCUVectorType - Return the unique reference to an OCU vector type of
685 /// the specified element type and size. VectorType must be a built-in type.
686 QualType ASTContext::getOCUVectorType(QualType vecType, unsigned NumElts) {
687 BuiltinType *baseType;
689 baseType = dyn_cast<BuiltinType>(vecType.getCanonicalType().getTypePtr());
690 assert(baseType != 0 && "getOCUVectorType(): Expecting a built-in type");
692 // Check if we've already instantiated a vector of this type.
693 llvm::FoldingSetNodeID ID;
694 VectorType::Profile(ID, vecType, NumElts, Type::OCUVector);
696 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
697 return QualType(VTP, 0);
699 // If the element type isn't canonical, this won't be a canonical type either,
700 // so fill in the canonical type field.
702 if (!vecType->isCanonical()) {
703 Canonical = getOCUVectorType(vecType.getCanonicalType(), NumElts);
705 // Get the new insert position for the node we care about.
706 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
707 assert(NewIP == 0 && "Shouldn't be in the map!");
709 OCUVectorType *New = new OCUVectorType(vecType, NumElts, Canonical);
710 VectorTypes.InsertNode(New, InsertPos);
711 Types.push_back(New);
712 return QualType(New, 0);
715 /// getFunctionTypeNoProto - Return a K&R style C function type like 'int()'.
717 QualType ASTContext::getFunctionTypeNoProto(QualType ResultTy) {
718 // Unique functions, to guarantee there is only one function of a particular
720 llvm::FoldingSetNodeID ID;
721 FunctionTypeNoProto::Profile(ID, ResultTy);
724 if (FunctionTypeNoProto *FT =
725 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos))
726 return QualType(FT, 0);
729 if (!ResultTy->isCanonical()) {
730 Canonical = getFunctionTypeNoProto(ResultTy.getCanonicalType());
732 // Get the new insert position for the node we care about.
733 FunctionTypeNoProto *NewIP =
734 FunctionTypeNoProtos.FindNodeOrInsertPos(ID, InsertPos);
735 assert(NewIP == 0 && "Shouldn't be in the map!");
738 FunctionTypeNoProto *New = new FunctionTypeNoProto(ResultTy, Canonical);
739 Types.push_back(New);
740 FunctionTypeNoProtos.InsertNode(New, InsertPos);
741 return QualType(New, 0);
744 /// getFunctionType - Return a normal function type with a typed argument
745 /// list. isVariadic indicates whether the argument list includes '...'.
746 QualType ASTContext::getFunctionType(QualType ResultTy, QualType *ArgArray,
747 unsigned NumArgs, bool isVariadic) {
748 // Unique functions, to guarantee there is only one function of a particular
750 llvm::FoldingSetNodeID ID;
751 FunctionTypeProto::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic);
754 if (FunctionTypeProto *FTP =
755 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos))
756 return QualType(FTP, 0);
758 // Determine whether the type being created is already canonical or not.
759 bool isCanonical = ResultTy->isCanonical();
760 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
761 if (!ArgArray[i]->isCanonical())
764 // If this type isn't canonical, get the canonical version of it.
767 llvm::SmallVector<QualType, 16> CanonicalArgs;
768 CanonicalArgs.reserve(NumArgs);
769 for (unsigned i = 0; i != NumArgs; ++i)
770 CanonicalArgs.push_back(ArgArray[i].getCanonicalType());
772 Canonical = getFunctionType(ResultTy.getCanonicalType(),
773 &CanonicalArgs[0], NumArgs,
776 // Get the new insert position for the node we care about.
777 FunctionTypeProto *NewIP =
778 FunctionTypeProtos.FindNodeOrInsertPos(ID, InsertPos);
779 assert(NewIP == 0 && "Shouldn't be in the map!");
782 // FunctionTypeProto objects are not allocated with new because they have a
783 // variable size array (for parameter types) at the end of them.
784 FunctionTypeProto *FTP =
785 (FunctionTypeProto*)malloc(sizeof(FunctionTypeProto) +
786 NumArgs*sizeof(QualType));
787 new (FTP) FunctionTypeProto(ResultTy, ArgArray, NumArgs, isVariadic,
789 Types.push_back(FTP);
790 FunctionTypeProtos.InsertNode(FTP, InsertPos);
791 return QualType(FTP, 0);
794 /// getTypedefType - Return the unique reference to the type for the
795 /// specified typename decl.
796 QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
797 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
799 QualType Canonical = Decl->getUnderlyingType().getCanonicalType();
800 Decl->TypeForDecl = new TypedefType(Type::TypeName, Decl, Canonical);
801 Types.push_back(Decl->TypeForDecl);
802 return QualType(Decl->TypeForDecl, 0);
805 /// getObjCInterfaceType - Return the unique reference to the type for the
806 /// specified ObjC interface decl.
807 QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
808 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
810 Decl->TypeForDecl = new ObjCInterfaceType(Type::ObjCInterface, Decl);
811 Types.push_back(Decl->TypeForDecl);
812 return QualType(Decl->TypeForDecl, 0);
815 /// getObjCQualifiedInterfaceType - Return a
816 /// ObjCQualifiedInterfaceType type for the given interface decl and
817 /// the conforming protocol list.
818 QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
819 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
820 llvm::FoldingSetNodeID ID;
821 ObjCQualifiedInterfaceType::Profile(ID, Protocols, NumProtocols);
824 if (ObjCQualifiedInterfaceType *QT =
825 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
826 return QualType(QT, 0);
829 ObjCQualifiedInterfaceType *QType =
830 new ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
831 Types.push_back(QType);
832 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
833 return QualType(QType, 0);
836 /// getObjCQualifiedIdType - Return a
837 /// getObjCQualifiedIdType type for the 'id' decl and
838 /// the conforming protocol list.
839 QualType ASTContext::getObjCQualifiedIdType(QualType idType,
840 ObjCProtocolDecl **Protocols,
841 unsigned NumProtocols) {
842 llvm::FoldingSetNodeID ID;
843 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
846 if (ObjCQualifiedIdType *QT =
847 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
848 return QualType(QT, 0);
852 if (!idType->isCanonical()) {
853 Canonical = getObjCQualifiedIdType(idType.getCanonicalType(),
854 Protocols, NumProtocols);
855 ObjCQualifiedIdType *NewQT =
856 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos);
857 assert(NewQT == 0 && "Shouldn't be in the map!");
860 ObjCQualifiedIdType *QType =
861 new ObjCQualifiedIdType(Canonical, Protocols, NumProtocols);
862 Types.push_back(QType);
863 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
864 return QualType(QType, 0);
867 /// getTypeOfExpr - Unlike many "get<Type>" functions, we can't unique
868 /// TypeOfExpr AST's (since expression's are never shared). For example,
869 /// multiple declarations that refer to "typeof(x)" all contain different
870 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
871 /// on canonical type's (which are always unique).
872 QualType ASTContext::getTypeOfExpr(Expr *tofExpr) {
873 QualType Canonical = tofExpr->getType().getCanonicalType();
874 TypeOfExpr *toe = new TypeOfExpr(tofExpr, Canonical);
875 Types.push_back(toe);
876 return QualType(toe, 0);
879 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
880 /// TypeOfType AST's. The only motivation to unique these nodes would be
881 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
882 /// an issue. This doesn't effect the type checker, since it operates
883 /// on canonical type's (which are always unique).
884 QualType ASTContext::getTypeOfType(QualType tofType) {
885 QualType Canonical = tofType.getCanonicalType();
886 TypeOfType *tot = new TypeOfType(tofType, Canonical);
887 Types.push_back(tot);
888 return QualType(tot, 0);
891 /// getTagDeclType - Return the unique reference to the type for the
892 /// specified TagDecl (struct/union/class/enum) decl.
893 QualType ASTContext::getTagDeclType(TagDecl *Decl) {
896 // The decl stores the type cache.
897 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
899 TagType* T = new TagType(Decl, QualType());
901 Decl->TypeForDecl = T;
903 return QualType(T, 0);
906 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
907 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
908 /// needs to agree with the definition in <stddef.h>.
909 QualType ASTContext::getSizeType() const {
910 // On Darwin, size_t is defined as a "long unsigned int".
911 // FIXME: should derive from "Target".
912 return UnsignedLongTy;
915 /// getWcharType - Return the unique type for "wchar_t" (C99 7.17), the
916 /// width of characters in wide strings, The value is target dependent and
917 /// needs to agree with the definition in <stddef.h>.
918 QualType ASTContext::getWcharType() const {
919 // On Darwin, wchar_t is defined as a "int".
920 // FIXME: should derive from "Target".
924 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
925 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
926 QualType ASTContext::getPointerDiffType() const {
927 // On Darwin, ptrdiff_t is defined as a "int". This seems like a bug...
928 // FIXME: should derive from "Target".
932 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
933 /// routine will assert if passed a built-in type that isn't an integer or enum.
934 static int getIntegerRank(QualType t) {
935 if (const TagType *TT = dyn_cast<TagType>(t.getCanonicalType())) {
936 assert(TT->getDecl()->getKind() == Decl::Enum && "not an int or enum");
940 const BuiltinType *BT = t.getCanonicalType()->getAsBuiltinType();
941 switch (BT->getKind()) {
943 assert(0 && "getIntegerRank(): not a built-in integer");
944 case BuiltinType::Bool:
946 case BuiltinType::Char_S:
947 case BuiltinType::Char_U:
948 case BuiltinType::SChar:
949 case BuiltinType::UChar:
951 case BuiltinType::Short:
952 case BuiltinType::UShort:
954 case BuiltinType::Int:
955 case BuiltinType::UInt:
957 case BuiltinType::Long:
958 case BuiltinType::ULong:
960 case BuiltinType::LongLong:
961 case BuiltinType::ULongLong:
966 /// getFloatingRank - Return a relative rank for floating point types.
967 /// This routine will assert if passed a built-in type that isn't a float.
968 static int getFloatingRank(QualType T) {
969 T = T.getCanonicalType();
970 if (const ComplexType *CT = T->getAsComplexType())
971 return getFloatingRank(CT->getElementType());
973 switch (T->getAsBuiltinType()->getKind()) {
974 default: assert(0 && "getFloatingRank(): not a floating type");
975 case BuiltinType::Float: return FloatRank;
976 case BuiltinType::Double: return DoubleRank;
977 case BuiltinType::LongDouble: return LongDoubleRank;
981 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
982 /// point or a complex type (based on typeDomain/typeSize).
983 /// 'typeDomain' is a real floating point or complex type.
984 /// 'typeSize' is a real floating point or complex type.
985 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(
986 QualType typeSize, QualType typeDomain) const {
987 if (typeDomain->isComplexType()) {
988 switch (getFloatingRank(typeSize)) {
989 default: assert(0 && "getFloatingRank(): illegal value for rank");
990 case FloatRank: return FloatComplexTy;
991 case DoubleRank: return DoubleComplexTy;
992 case LongDoubleRank: return LongDoubleComplexTy;
995 if (typeDomain->isRealFloatingType()) {
996 switch (getFloatingRank(typeSize)) {
997 default: assert(0 && "getFloatingRank(): illegal value for rank");
998 case FloatRank: return FloatTy;
999 case DoubleRank: return DoubleTy;
1000 case LongDoubleRank: return LongDoubleTy;
1003 assert(0 && "getFloatingTypeOfSizeWithinDomain(): illegal domain");
1004 //an invalid return value, but the assert
1005 //will ensure that this code is never reached.
1009 /// compareFloatingType - Handles 3 different combos:
1010 /// float/float, float/complex, complex/complex.
1011 /// If lt > rt, return 1. If lt == rt, return 0. If lt < rt, return -1.
1012 int ASTContext::compareFloatingType(QualType lt, QualType rt) {
1013 if (getFloatingRank(lt) == getFloatingRank(rt))
1015 if (getFloatingRank(lt) > getFloatingRank(rt))
1020 // maxIntegerType - Returns the highest ranked integer type. Handles 3 case:
1021 // unsigned/unsigned, signed/signed, signed/unsigned. C99 6.3.1.8p1.
1022 QualType ASTContext::maxIntegerType(QualType lhs, QualType rhs) {
1023 if (lhs == rhs) return lhs;
1025 bool t1Unsigned = lhs->isUnsignedIntegerType();
1026 bool t2Unsigned = rhs->isUnsignedIntegerType();
1028 if ((t1Unsigned && t2Unsigned) || (!t1Unsigned && !t2Unsigned))
1029 return getIntegerRank(lhs) >= getIntegerRank(rhs) ? lhs : rhs;
1031 // We have two integer types with differing signs
1032 QualType unsignedType = t1Unsigned ? lhs : rhs;
1033 QualType signedType = t1Unsigned ? rhs : lhs;
1035 if (getIntegerRank(unsignedType) >= getIntegerRank(signedType))
1036 return unsignedType;
1038 // FIXME: Need to check if the signed type can represent all values of the
1039 // unsigned type. If it can, then the result is the signed type.
1040 // If it can't, then the result is the unsigned version of the signed type.
1041 // Should probably add a helper that returns a signed integer type from
1042 // an unsigned (and vice versa). C99 6.3.1.8.
1047 // getCFConstantStringType - Return the type used for constant CFStrings.
1048 QualType ASTContext::getCFConstantStringType() {
1049 if (!CFConstantStringTypeDecl) {
1050 CFConstantStringTypeDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1051 &Idents.get("NSConstantString"),
1053 QualType FieldTypes[4];
1056 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
1058 FieldTypes[1] = IntTy;
1060 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
1062 FieldTypes[3] = LongTy;
1064 FieldDecl *FieldDecls[4];
1066 for (unsigned i = 0; i < 4; ++i)
1067 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1069 CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
1072 return getTagDeclType(CFConstantStringTypeDecl);
1075 // This returns true if a type has been typedefed to BOOL:
1076 // typedef <type> BOOL;
1077 static bool isTypeTypedefedAsBOOL(QualType T) {
1078 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1079 return !strcmp(TT->getDecl()->getName(), "BOOL");
1084 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
1086 int ASTContext::getObjCEncodingTypeSize(QualType type) {
1087 uint64_t sz = getTypeSize(type);
1089 // Make all integer and enum types at least as large as an int
1090 if (sz > 0 && type->isIntegralType())
1091 sz = std::max(sz, getTypeSize(IntTy));
1092 // Treat arrays as pointers, since that's how they're passed in.
1093 else if (type->isArrayType())
1094 sz = getTypeSize(VoidPtrTy);
1095 return sz / getTypeSize(CharTy);
1098 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
1100 void ASTContext::getObjCEncodingForMethodDecl(ObjCMethodDecl *Decl,
1103 // Encode type qualifer, 'in', 'inout', etc. for the return type.
1104 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
1105 // Encode result type.
1106 getObjCEncodingForType(Decl->getResultType(), S, EncodingRecordTypes);
1107 // Compute size of all parameters.
1108 // Start with computing size of a pointer in number of bytes.
1109 // FIXME: There might(should) be a better way of doing this computation!
1111 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
1112 // The first two arguments (self and _cmd) are pointers; account for
1114 int ParmOffset = 2 * PtrSize;
1115 int NumOfParams = Decl->getNumParams();
1116 for (int i = 0; i < NumOfParams; i++) {
1117 QualType PType = Decl->getParamDecl(i)->getType();
1118 int sz = getObjCEncodingTypeSize (PType);
1119 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
1122 S += llvm::utostr(ParmOffset);
1124 S += llvm::utostr(PtrSize);
1127 ParmOffset = 2 * PtrSize;
1128 for (int i = 0; i < NumOfParams; i++) {
1129 QualType PType = Decl->getParamDecl(i)->getType();
1130 // Process argument qualifiers for user supplied arguments; such as,
1131 // 'in', 'inout', etc.
1132 getObjCEncodingForTypeQualifier(
1133 Decl->getParamDecl(i)->getObjCDeclQualifier(), S);
1134 getObjCEncodingForType(PType, S, EncodingRecordTypes);
1135 S += llvm::utostr(ParmOffset);
1136 ParmOffset += getObjCEncodingTypeSize(PType);
1140 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
1141 llvm::SmallVector<const RecordType *, 8> &ERType) const
1143 // FIXME: This currently doesn't encode:
1144 // @ An object (whether statically typed or typed id)
1145 // # A class object (Class)
1146 // : A method selector (SEL)
1147 // {name=type...} A structure
1148 // (name=type...) A union
1149 // bnum A bit field of num bits
1151 if (const BuiltinType *BT = T->getAsBuiltinType()) {
1153 switch (BT->getKind()) {
1154 case BuiltinType::Void:
1157 case BuiltinType::Bool:
1160 case BuiltinType::Char_U:
1161 case BuiltinType::UChar:
1164 case BuiltinType::UShort:
1167 case BuiltinType::UInt:
1170 case BuiltinType::ULong:
1173 case BuiltinType::ULongLong:
1176 case BuiltinType::Char_S:
1177 case BuiltinType::SChar:
1180 case BuiltinType::Short:
1183 case BuiltinType::Int:
1186 case BuiltinType::Long:
1189 case BuiltinType::LongLong:
1192 case BuiltinType::Float:
1195 case BuiltinType::Double:
1198 case BuiltinType::LongDouble:
1202 assert(0 && "Unhandled builtin type kind");
1207 else if (T->isObjCQualifiedIdType()) {
1208 // Treat id<P...> same as 'id' for encoding purposes.
1209 return getObjCEncodingForType(getObjCIdType(), S, ERType);
1212 else if (const PointerType *PT = T->getAsPointerType()) {
1213 QualType PointeeTy = PT->getPointeeType();
1214 if (isObjCIdType(PointeeTy) || PointeeTy->isObjCInterfaceType()) {
1217 } else if (isObjCClassType(PointeeTy)) {
1220 } else if (isObjCSelType(PointeeTy)) {
1225 if (PointeeTy->isCharType()) {
1226 // char pointer types should be encoded as '*' unless it is a
1227 // type that has been typedef'd to 'BOOL'.
1228 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
1235 getObjCEncodingForType(PT->getPointeeType(), S, ERType);
1236 } else if (const ArrayType *AT = T->getAsArrayType()) {
1239 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1240 S += llvm::utostr(CAT->getSize().getZExtValue());
1242 assert(0 && "Unhandled array type!");
1244 getObjCEncodingForType(AT->getElementType(), S, ERType);
1246 } else if (T->getAsFunctionType()) {
1248 } else if (const RecordType *RTy = T->getAsRecordType()) {
1249 RecordDecl *RDecl= RTy->getDecl();
1251 S += RDecl->getName();
1253 for (unsigned i = 0, e = ERType.size(); i != e; ++i)
1254 if (ERType[i] == RTy) {
1259 ERType.push_back(RTy);
1261 for (int i = 0; i < RDecl->getNumMembers(); i++) {
1262 FieldDecl *field = RDecl->getMember(i);
1263 getObjCEncodingForType(field->getType(), S, ERType);
1265 assert(ERType.back() == RTy && "Record Type stack mismatch.");
1269 } else if (T->isEnumeralType()) {
1272 assert(0 && "@encode for type not implemented!");
1275 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1276 std::string& S) const {
1277 if (QT & Decl::OBJC_TQ_In)
1279 if (QT & Decl::OBJC_TQ_Inout)
1281 if (QT & Decl::OBJC_TQ_Out)
1283 if (QT & Decl::OBJC_TQ_Bycopy)
1285 if (QT & Decl::OBJC_TQ_Byref)
1287 if (QT & Decl::OBJC_TQ_Oneway)
1291 void ASTContext::setBuiltinVaListType(QualType T)
1293 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
1295 BuiltinVaListType = T;
1298 void ASTContext::setObjCIdType(TypedefDecl *TD)
1300 assert(ObjCIdType.isNull() && "'id' type already set!");
1302 ObjCIdType = getTypedefType(TD);
1304 // typedef struct objc_object *id;
1305 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1306 assert(ptr && "'id' incorrectly typed");
1307 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1308 assert(rec && "'id' incorrectly typed");
1312 void ASTContext::setObjCSelType(TypedefDecl *TD)
1314 assert(ObjCSelType.isNull() && "'SEL' type already set!");
1316 ObjCSelType = getTypedefType(TD);
1318 // typedef struct objc_selector *SEL;
1319 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1320 assert(ptr && "'SEL' incorrectly typed");
1321 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1322 assert(rec && "'SEL' incorrectly typed");
1323 SelStructType = rec;
1326 void ASTContext::setObjCProtoType(QualType QT)
1328 assert(ObjCProtoType.isNull() && "'Protocol' type already set!");
1332 void ASTContext::setObjCClassType(TypedefDecl *TD)
1334 assert(ObjCClassType.isNull() && "'Class' type already set!");
1336 ObjCClassType = getTypedefType(TD);
1338 // typedef struct objc_class *Class;
1339 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
1340 assert(ptr && "'Class' incorrectly typed");
1341 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
1342 assert(rec && "'Class' incorrectly typed");
1343 ClassStructType = rec;
1346 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
1347 assert(ObjCConstantStringType.isNull() &&
1348 "'NSConstantString' type already set!");
1350 ObjCConstantStringType = getObjCInterfaceType(Decl);
1353 bool ASTContext::builtinTypesAreCompatible(QualType lhs, QualType rhs) {
1354 const BuiltinType *lBuiltin = lhs->getAsBuiltinType();
1355 const BuiltinType *rBuiltin = rhs->getAsBuiltinType();
1357 return lBuiltin->getKind() == rBuiltin->getKind();
1360 /// objcTypesAreCompatible - This routine is called when two types
1361 /// are of different class; one is interface type or is
1362 /// a qualified interface type and the other type is of a different class.
1363 /// Example, II or II<P>.
1364 bool ASTContext::objcTypesAreCompatible(QualType lhs, QualType rhs) {
1365 if (lhs->isObjCInterfaceType() && isObjCIdType(rhs))
1367 else if (isObjCIdType(lhs) && rhs->isObjCInterfaceType())
1369 if (ObjCInterfaceType *lhsIT =
1370 dyn_cast<ObjCInterfaceType>(lhs.getCanonicalType().getTypePtr())) {
1371 ObjCQualifiedInterfaceType *rhsQI =
1372 dyn_cast<ObjCQualifiedInterfaceType>(rhs.getCanonicalType().getTypePtr());
1373 return rhsQI && (lhsIT->getDecl() == rhsQI->getDecl());
1375 else if (ObjCInterfaceType *rhsIT =
1376 dyn_cast<ObjCInterfaceType>(rhs.getCanonicalType().getTypePtr())) {
1377 ObjCQualifiedInterfaceType *lhsQI =
1378 dyn_cast<ObjCQualifiedInterfaceType>(lhs.getCanonicalType().getTypePtr());
1379 return lhsQI && (rhsIT->getDecl() == lhsQI->getDecl());
1384 /// Check that 'lhs' and 'rhs' are compatible interface types. Both types
1385 /// must be canonical types.
1386 bool ASTContext::interfaceTypesAreCompatible(QualType lhs, QualType rhs) {
1387 assert (lhs->isCanonical() &&
1388 "interfaceTypesAreCompatible strip typedefs of lhs");
1389 assert (rhs->isCanonical() &&
1390 "interfaceTypesAreCompatible strip typedefs of rhs");
1393 ObjCInterfaceType *lhsIT = cast<ObjCInterfaceType>(lhs.getTypePtr());
1394 ObjCInterfaceType *rhsIT = cast<ObjCInterfaceType>(rhs.getTypePtr());
1395 ObjCInterfaceDecl *rhsIDecl = rhsIT->getDecl();
1396 ObjCInterfaceDecl *lhsIDecl = lhsIT->getDecl();
1397 // rhs is derived from lhs it is OK; else it is not OK.
1398 while (rhsIDecl != NULL) {
1399 if (rhsIDecl == lhsIDecl)
1401 rhsIDecl = rhsIDecl->getSuperClass();
1406 bool ASTContext::QualifiedInterfaceTypesAreCompatible(QualType lhs,
1408 ObjCQualifiedInterfaceType *lhsQI =
1409 dyn_cast<ObjCQualifiedInterfaceType>(lhs.getCanonicalType().getTypePtr());
1410 assert(lhsQI && "QualifiedInterfaceTypesAreCompatible - bad lhs type");
1411 ObjCQualifiedInterfaceType *rhsQI =
1412 dyn_cast<ObjCQualifiedInterfaceType>(rhs.getCanonicalType().getTypePtr());
1413 assert(rhsQI && "QualifiedInterfaceTypesAreCompatible - bad rhs type");
1414 if (!interfaceTypesAreCompatible(
1415 getObjCInterfaceType(lhsQI->getDecl()).getCanonicalType(),
1416 getObjCInterfaceType(rhsQI->getDecl()).getCanonicalType()))
1418 /* All protocols in lhs must have a presense in rhs. */
1419 for (unsigned i =0; i < lhsQI->getNumProtocols(); i++) {
1421 ObjCProtocolDecl *lhsProto = lhsQI->getProtocols(i);
1422 for (unsigned j = 0; j < rhsQI->getNumProtocols(); j++) {
1423 ObjCProtocolDecl *rhsProto = rhsQI->getProtocols(j);
1424 if (lhsProto == rhsProto) {
1435 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
1436 /// inheritance hierarchy of 'rProto'.
1437 static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1438 ObjCProtocolDecl *rProto) {
1439 if (lProto == rProto)
1441 ObjCProtocolDecl** RefPDecl = rProto->getReferencedProtocols();
1442 for (unsigned i = 0; i < rProto->getNumReferencedProtocols(); i++)
1443 if (ProtocolCompatibleWithProtocol(lProto, RefPDecl[i]))
1448 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1449 /// has been implemented in IDecl class, its super class or categories (if
1450 /// lookupCategory is true).
1451 static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1452 ObjCInterfaceDecl *IDecl,
1453 bool lookupCategory) {
1455 // 1st, look up the class.
1456 ObjCProtocolDecl **protoList = IDecl->getReferencedProtocols();
1457 for (unsigned i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1458 if (ProtocolCompatibleWithProtocol(lProto, protoList[i]))
1462 // 2nd, look up the category.
1464 for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
1465 CDecl = CDecl->getNextClassCategory()) {
1466 protoList = CDecl->getReferencedProtocols();
1467 for (unsigned i = 0; i < CDecl->getNumReferencedProtocols(); i++) {
1468 if (ProtocolCompatibleWithProtocol(lProto, protoList[i]))
1473 // 3rd, look up the super class(s)
1474 if (IDecl->getSuperClass())
1476 ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory);
1481 /// ObjCQualifiedIdTypesAreCompatible - Compares two types, at least
1482 /// one of which is a protocol qualified 'id' type. When 'compare'
1483 /// is true it is for comparison; when false, for assignment/initialization.
1484 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs,
1487 // match id<P..> with an 'id' type in all cases.
1488 if (const PointerType *PT = lhs->getAsPointerType()) {
1489 QualType PointeeTy = PT->getPointeeType();
1490 if (isObjCIdType(PointeeTy) || PointeeTy->isVoidType())
1494 else if (const PointerType *PT = rhs->getAsPointerType()) {
1495 QualType PointeeTy = PT->getPointeeType();
1496 if (isObjCIdType(PointeeTy) || PointeeTy->isVoidType())
1501 ObjCQualifiedInterfaceType *lhsQI = 0;
1502 ObjCQualifiedInterfaceType *rhsQI = 0;
1503 ObjCInterfaceDecl *lhsID = 0;
1504 ObjCInterfaceDecl *rhsID = 0;
1505 ObjCQualifiedIdType *lhsQID = dyn_cast<ObjCQualifiedIdType>(lhs);
1506 ObjCQualifiedIdType *rhsQID = dyn_cast<ObjCQualifiedIdType>(rhs);
1509 if (!rhsQID && rhs->getTypeClass() == Type::Pointer) {
1511 cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
1513 dyn_cast<ObjCQualifiedInterfaceType>(
1514 rtype.getCanonicalType().getTypePtr());
1516 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(
1517 rtype.getCanonicalType().getTypePtr());
1519 rhsID = IT->getDecl();
1522 if (!rhsQI && !rhsQID && !rhsID)
1525 unsigned numRhsProtocols = 0;
1526 ObjCProtocolDecl **rhsProtoList = 0;
1528 numRhsProtocols = rhsQI->getNumProtocols();
1529 rhsProtoList = rhsQI->getReferencedProtocols();
1532 numRhsProtocols = rhsQID->getNumProtocols();
1533 rhsProtoList = rhsQID->getReferencedProtocols();
1536 for (unsigned i =0; i < lhsQID->getNumProtocols(); i++) {
1537 ObjCProtocolDecl *lhsProto = lhsQID->getProtocols(i);
1540 // when comparing an id<P> on lhs with a static type on rhs,
1541 // see if static class implements all of id's protocols, directly or
1542 // through its super class and categories.
1544 if (ClassImplementsProtocol(lhsProto, rhsID, true))
1547 else for (unsigned j = 0; j < numRhsProtocols; j++) {
1548 ObjCProtocolDecl *rhsProto = rhsProtoList[j];
1549 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
1550 compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto)) {
1560 if (!lhsQID && lhs->getTypeClass() == Type::Pointer) {
1562 cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
1564 dyn_cast<ObjCQualifiedInterfaceType>(
1565 ltype.getCanonicalType().getTypePtr());
1567 ObjCInterfaceType *IT = dyn_cast<ObjCInterfaceType>(
1568 ltype.getCanonicalType().getTypePtr());
1570 lhsID = IT->getDecl();
1573 if (!lhsQI && !lhsQID && !lhsID)
1576 unsigned numLhsProtocols = 0;
1577 ObjCProtocolDecl **lhsProtoList = 0;
1579 numLhsProtocols = lhsQI->getNumProtocols();
1580 lhsProtoList = lhsQI->getReferencedProtocols();
1583 numLhsProtocols = lhsQID->getNumProtocols();
1584 lhsProtoList = lhsQID->getReferencedProtocols();
1587 // for static type vs. qualified 'id' type, check that class implements
1588 // one of 'id's protocols.
1590 for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) {
1591 ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j);
1592 if (ClassImplementsProtocol(rhsProto, lhsID, compare)) {
1598 else for (unsigned i =0; i < numLhsProtocols; i++) {
1600 ObjCProtocolDecl *lhsProto = lhsProtoList[i];
1601 for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) {
1602 ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j);
1603 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
1604 compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto)) {
1616 bool ASTContext::vectorTypesAreCompatible(QualType lhs, QualType rhs) {
1617 const VectorType *lVector = lhs->getAsVectorType();
1618 const VectorType *rVector = rhs->getAsVectorType();
1620 if ((lVector->getElementType().getCanonicalType() ==
1621 rVector->getElementType().getCanonicalType()) &&
1622 (lVector->getNumElements() == rVector->getNumElements()))
1627 // C99 6.2.7p1: If both are complete types, then the following additional
1628 // requirements apply...FIXME (handle compatibility across source files).
1629 bool ASTContext::tagTypesAreCompatible(QualType lhs, QualType rhs) {
1630 // "Class" and "id" are compatible built-in structure types.
1631 if (isObjCIdType(lhs) && isObjCClassType(rhs) ||
1632 isObjCClassType(lhs) && isObjCIdType(rhs))
1635 // Within a translation unit a tag type is
1636 // only compatible with itself.
1637 return lhs.getCanonicalType() == rhs.getCanonicalType();
1640 bool ASTContext::pointerTypesAreCompatible(QualType lhs, QualType rhs) {
1641 // C99 6.7.5.1p2: For two pointer types to be compatible, both shall be
1642 // identically qualified and both shall be pointers to compatible types.
1643 if (lhs.getCVRQualifiers() != rhs.getCVRQualifiers() ||
1644 lhs.getAddressSpace() != rhs.getAddressSpace())
1647 QualType ltype = cast<PointerType>(lhs.getCanonicalType())->getPointeeType();
1648 QualType rtype = cast<PointerType>(rhs.getCanonicalType())->getPointeeType();
1650 return typesAreCompatible(ltype, rtype);
1653 // C++ 5.17p6: When the left operand of an assignment operator denotes a
1654 // reference to T, the operation assigns to the object of type T denoted by the
1656 bool ASTContext::referenceTypesAreCompatible(QualType lhs, QualType rhs) {
1657 QualType ltype = lhs;
1659 if (lhs->isReferenceType())
1660 ltype = cast<ReferenceType>(lhs.getCanonicalType())->getReferenceeType();
1662 QualType rtype = rhs;
1664 if (rhs->isReferenceType())
1665 rtype = cast<ReferenceType>(rhs.getCanonicalType())->getReferenceeType();
1667 return typesAreCompatible(ltype, rtype);
1670 bool ASTContext::functionTypesAreCompatible(QualType lhs, QualType rhs) {
1671 const FunctionType *lbase = cast<FunctionType>(lhs.getCanonicalType());
1672 const FunctionType *rbase = cast<FunctionType>(rhs.getCanonicalType());
1673 const FunctionTypeProto *lproto = dyn_cast<FunctionTypeProto>(lbase);
1674 const FunctionTypeProto *rproto = dyn_cast<FunctionTypeProto>(rbase);
1676 // first check the return types (common between C99 and K&R).
1677 if (!typesAreCompatible(lbase->getResultType(), rbase->getResultType()))
1680 if (lproto && rproto) { // two C99 style function prototypes
1681 unsigned lproto_nargs = lproto->getNumArgs();
1682 unsigned rproto_nargs = rproto->getNumArgs();
1684 if (lproto_nargs != rproto_nargs)
1687 // both prototypes have the same number of arguments.
1688 if ((lproto->isVariadic() && !rproto->isVariadic()) ||
1689 (rproto->isVariadic() && !lproto->isVariadic()))
1692 // The use of ellipsis agree...now check the argument types.
1693 for (unsigned i = 0; i < lproto_nargs; i++)
1694 // C99 6.7.5.3p15: ...and each parameter declared with qualified type
1695 // is taken as having the unqualified version of it's declared type.
1696 if (!typesAreCompatible(lproto->getArgType(i).getUnqualifiedType(),
1697 rproto->getArgType(i).getUnqualifiedType()))
1701 if (!lproto && !rproto) // two K&R style function decls, nothing to do.
1704 // we have a mixture of K&R style with C99 prototypes
1705 const FunctionTypeProto *proto = lproto ? lproto : rproto;
1707 if (proto->isVariadic())
1710 // FIXME: Each parameter type T in the prototype must be compatible with the
1711 // type resulting from applying the usual argument conversions to T.
1715 bool ASTContext::arrayTypesAreCompatible(QualType lhs, QualType rhs) {
1716 // Compatible arrays must have compatible element types
1717 QualType ltype = lhs->getAsArrayType()->getElementType();
1718 QualType rtype = rhs->getAsArrayType()->getElementType();
1720 if (!typesAreCompatible(ltype, rtype))
1723 // Compatible arrays must be the same size
1724 if (const ConstantArrayType* LCAT = lhs->getAsConstantArrayType())
1725 if (const ConstantArrayType* RCAT = rhs->getAsConstantArrayType())
1726 return RCAT->getSize() == LCAT->getSize();
1731 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
1732 /// both shall have the identically qualified version of a compatible type.
1733 /// C99 6.2.7p1: Two types have compatible types if their types are the
1734 /// same. See 6.7.[2,3,5] for additional rules.
1735 bool ASTContext::typesAreCompatible(QualType lhs, QualType rhs) {
1736 if (lhs.getCVRQualifiers() != rhs.getCVRQualifiers() ||
1737 lhs.getAddressSpace() != rhs.getAddressSpace())
1740 QualType lcanon = lhs.getCanonicalType();
1741 QualType rcanon = rhs.getCanonicalType();
1743 // If two types are identical, they are are compatible
1744 if (lcanon == rcanon)
1747 // C++ [expr]: If an expression initially has the type "reference to T", the
1748 // type is adjusted to "T" prior to any further analysis, the expression
1749 // designates the object or function denoted by the reference, and the
1750 // expression is an lvalue.
1751 if (ReferenceType *RT = dyn_cast<ReferenceType>(lcanon))
1752 lcanon = RT->getReferenceeType();
1753 if (ReferenceType *RT = dyn_cast<ReferenceType>(rcanon))
1754 rcanon = RT->getReferenceeType();
1756 Type::TypeClass LHSClass = lcanon->getTypeClass();
1757 Type::TypeClass RHSClass = rcanon->getTypeClass();
1759 // We want to consider the two function types to be the same for these
1760 // comparisons, just force one to the other.
1761 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
1762 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
1764 // Same as above for arrays
1765 if (LHSClass == Type::VariableArray) LHSClass = Type::ConstantArray;
1766 if (RHSClass == Type::VariableArray) RHSClass = Type::ConstantArray;
1767 if (LHSClass == Type::IncompleteArray) LHSClass = Type::ConstantArray;
1768 if (RHSClass == Type::IncompleteArray) RHSClass = Type::ConstantArray;
1770 // If the canonical type classes don't match...
1771 if (LHSClass != RHSClass) {
1772 // For Objective-C, it is possible for two types to be compatible
1773 // when their classes don't match (when dealing with "id"). If either type
1774 // is an interface, we defer to objcTypesAreCompatible().
1775 if (lcanon->isObjCInterfaceType() || rcanon->isObjCInterfaceType())
1776 return objcTypesAreCompatible(lcanon, rcanon);
1778 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
1779 // a signed integer type, or an unsigned integer type.
1780 if (lcanon->isEnumeralType() && rcanon->isIntegralType()) {
1781 EnumDecl* EDecl = cast<EnumDecl>(cast<TagType>(lcanon)->getDecl());
1782 return EDecl->getIntegerType() == rcanon;
1784 if (rcanon->isEnumeralType() && lcanon->isIntegralType()) {
1785 EnumDecl* EDecl = cast<EnumDecl>(cast<TagType>(rcanon)->getDecl());
1786 return EDecl->getIntegerType() == lcanon;
1791 // The canonical type classes match.
1793 case Type::FunctionProto: assert(0 && "Canonicalized away above");
1795 return pointerTypesAreCompatible(lcanon, rcanon);
1796 case Type::ConstantArray:
1797 case Type::VariableArray:
1798 case Type::IncompleteArray:
1799 return arrayTypesAreCompatible(lcanon, rcanon);
1800 case Type::FunctionNoProto:
1801 return functionTypesAreCompatible(lcanon, rcanon);
1802 case Type::Tagged: // handle structures, unions
1803 return tagTypesAreCompatible(lcanon, rcanon);
1805 return builtinTypesAreCompatible(lcanon, rcanon);
1806 case Type::ObjCInterface:
1807 return interfaceTypesAreCompatible(lcanon, rcanon);
1809 case Type::OCUVector:
1810 return vectorTypesAreCompatible(lcanon, rcanon);
1811 case Type::ObjCQualifiedInterface:
1812 return QualifiedInterfaceTypesAreCompatible(lcanon, rcanon);
1814 assert(0 && "unexpected type");
1816 return true; // should never get here...
1819 /// Emit - Serialize an ASTContext object to Bitcode.
1820 void ASTContext::Emit(llvm::Serializer& S) const {
1821 S.EmitRef(SourceMgr);
1824 S.EmitRef(Selectors);
1826 // Emit the size of the type vector so that we can reserve that size
1827 // when we reconstitute the ASTContext object.
1828 S.EmitInt(Types.size());
1830 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
1834 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
1837 ASTContext* ASTContext::Create(llvm::Deserializer& D) {
1838 SourceManager &SM = D.ReadRef<SourceManager>();
1839 TargetInfo &t = D.ReadRef<TargetInfo>();
1840 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
1841 SelectorTable &sels = D.ReadRef<SelectorTable>();
1843 unsigned size_reserve = D.ReadInt();
1845 ASTContext* A = new ASTContext(SM,t,idents,sels,size_reserve);
1847 for (unsigned i = 0; i < size_reserve; ++i)
1848 Type::Create(*A,i,D);
1850 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();