1 //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
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 is the code that handles AST -> LLVM type lowering.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenTypes.h"
15 #include "clang/Basic/TargetInfo.h"
16 #include "clang/AST/AST.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Target/TargetData.h"
21 using namespace clang;
22 using namespace CodeGen;
25 /// RecordOrganizer - This helper class, used by CGRecordLayout, layouts
26 /// structs and unions. It manages transient information used during layout.
27 /// FIXME : Handle field aligments. Handle packed structs.
28 class RecordOrganizer {
30 explicit RecordOrganizer(CodeGenTypes &Types) :
31 CGT(Types), STy(NULL), llvmFieldNo(0), Cursor(0),
34 /// addField - Add new field.
35 void addField(const FieldDecl *FD);
37 /// addLLVMField - Add llvm struct field that corresponds to llvm type Ty.
38 /// Increment field count.
39 void addLLVMField(const llvm::Type *Ty, bool isPaddingField = false);
41 /// addPaddingFields - Current cursor is not suitable place to add next
42 /// field. Add required padding fields.
43 void addPaddingFields(unsigned WaterMark);
45 /// layoutStructFields - Do the actual work and lay out all fields. Create
46 /// corresponding llvm struct type. This should be invoked only after
47 /// all fields are added.
48 void layoutStructFields(const ASTRecordLayout &RL);
50 /// layoutUnionFields - Do the actual work and lay out all fields. Create
51 /// corresponding llvm struct type. This should be invoked only after
52 /// all fields are added.
53 void layoutUnionFields();
55 /// getLLVMType - Return associated llvm struct type. This may be NULL
56 /// if fields are not laid out.
57 llvm::Type *getLLVMType() const {
61 /// placeBitField - Find a place for FD, which is a bit-field.
62 void placeBitField(const FieldDecl *FD);
64 llvm::SmallSet<unsigned, 8> &getPaddingFields() {
74 llvm::SmallVector<const FieldDecl *, 8> FieldDecls;
75 std::vector<const llvm::Type*> LLVMFields;
76 llvm::SmallSet<unsigned, 8> PaddingFields;
80 CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M,
81 const llvm::TargetData &TD)
82 : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD) {
85 CodeGenTypes::~CodeGenTypes() {
86 for(llvm::DenseMap<const TagDecl *, CGRecordLayout *>::iterator
87 I = CGRecordLayouts.begin(), E = CGRecordLayouts.end();
90 CGRecordLayouts.clear();
93 /// ConvertType - Convert the specified type to its LLVM form.
94 const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
95 // See if type is already cached.
96 llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator
97 I = TypeCache.find(T.getCanonicalType().getTypePtr());
98 // If type is found in map and this is not a definition for a opaque
99 // place holder type then use it. Otherwise, convert type T.
100 if (I != TypeCache.end())
101 return I->second.get();
103 const llvm::Type *ResultType = ConvertNewType(T);
104 TypeCache.insert(std::make_pair(T.getCanonicalType().getTypePtr(),
105 llvm::PATypeHolder(ResultType)));
109 /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
110 /// ConvertType in that it is used to convert to the memory representation for
111 /// a type. For example, the scalar representation for _Bool is i1, but the
112 /// memory representation is usually i8 or i32, depending on the target.
113 const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
114 const llvm::Type *R = ConvertType(T);
116 // If this is a non-bool type, don't map it.
117 if (R != llvm::Type::Int1Ty)
120 // Otherwise, return an integer of the target-specified size.
121 unsigned BoolWidth = (unsigned)Context.getTypeSize(T, SourceLocation());
122 return llvm::IntegerType::get(BoolWidth);
126 /// UpdateCompletedType - When we find the full definition for a TagDecl,
127 /// replace the 'opaque' type we previously made for it if applicable.
128 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
129 llvm::DenseMap<const TagDecl*, llvm::PATypeHolder>::iterator TDTI =
130 TagDeclTypes.find(TD);
131 if (TDTI == TagDeclTypes.end()) return;
133 // Remember the opaque LLVM type for this tagdecl.
134 llvm::PATypeHolder OpaqueHolder = TDTI->second;
135 assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) &&
136 "Updating compilation of an already non-opaque type?");
138 // Remove it from TagDeclTypes so that it will be regenerated.
139 TagDeclTypes.erase(TDTI);
141 // Generate the new type.
142 const llvm::Type *NT = ConvertTagDeclType(TD);
144 // Refine the old opaque type to its new definition.
145 cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT);
150 const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) {
151 const clang::Type &Ty = *T.getCanonicalType();
153 switch (Ty.getTypeClass()) {
154 case Type::TypeName: // typedef isn't canonical.
155 case Type::TypeOfExp: // typeof isn't canonical.
156 case Type::TypeOfTyp: // typeof isn't canonical.
157 assert(0 && "Non-canonical type, shouldn't happen");
158 case Type::Builtin: {
159 switch (cast<BuiltinType>(Ty).getKind()) {
160 case BuiltinType::Void:
161 // LLVM void type can only be used as the result of a function call. Just
162 // map to the same as char.
163 return llvm::IntegerType::get(8);
165 case BuiltinType::Bool:
166 // Note that we always return bool as i1 for use as a scalar type.
167 return llvm::Type::Int1Ty;
169 case BuiltinType::Char_S:
170 case BuiltinType::Char_U:
171 case BuiltinType::SChar:
172 case BuiltinType::UChar:
173 case BuiltinType::Short:
174 case BuiltinType::UShort:
175 case BuiltinType::Int:
176 case BuiltinType::UInt:
177 case BuiltinType::Long:
178 case BuiltinType::ULong:
179 case BuiltinType::LongLong:
180 case BuiltinType::ULongLong:
181 return llvm::IntegerType::get(
182 static_cast<unsigned>(Context.getTypeSize(T, SourceLocation())));
184 case BuiltinType::Float: return llvm::Type::FloatTy;
185 case BuiltinType::Double: return llvm::Type::DoubleTy;
186 case BuiltinType::LongDouble:
187 // FIXME: mapping long double onto double.
188 return llvm::Type::DoubleTy;
192 case Type::Complex: {
193 std::vector<const llvm::Type*> Elts;
194 Elts.push_back(ConvertType(cast<ComplexType>(Ty).getElementType()));
195 Elts.push_back(Elts[0]);
196 return llvm::StructType::get(Elts);
198 case Type::Pointer: {
199 const PointerType &P = cast<PointerType>(Ty);
200 QualType ETy = P.getPointeeType();
201 return llvm::PointerType::get(ConvertType(ETy), ETy.getAddressSpace());
203 case Type::Reference: {
204 const ReferenceType &R = cast<ReferenceType>(Ty);
205 return llvm::PointerType::getUnqual(ConvertType(R.getReferenceeType()));
208 case Type::VariableArray: {
209 const VariableArrayType &A = cast<VariableArrayType>(Ty);
210 assert(A.getIndexTypeQualifier() == 0 &&
211 "FIXME: We only handle trivial array types so far!");
212 // VLAs resolve to the innermost element type; this matches
213 // the return of alloca, and there isn't any obviously better choice.
214 return ConvertType(A.getElementType());
216 case Type::IncompleteArray: {
217 const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty);
218 assert(A.getIndexTypeQualifier() == 0 &&
219 "FIXME: We only handle trivial array types so far!");
220 // int X[] -> [0 x int]
221 return llvm::ArrayType::get(ConvertType(A.getElementType()), 0);
223 case Type::ConstantArray: {
224 const ConstantArrayType &A = cast<ConstantArrayType>(Ty);
225 const llvm::Type *EltTy = ConvertType(A.getElementType());
226 return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue());
228 case Type::OCUVector:
230 const VectorType &VT = cast<VectorType>(Ty);
231 return llvm::VectorType::get(ConvertType(VT.getElementType()),
232 VT.getNumElements());
234 case Type::FunctionNoProto:
235 case Type::FunctionProto: {
236 const FunctionType &FP = cast<FunctionType>(Ty);
237 const llvm::Type *ResultType;
239 if (FP.getResultType()->isVoidType())
240 ResultType = llvm::Type::VoidTy; // Result of function uses llvm void.
242 ResultType = ConvertType(FP.getResultType());
244 // FIXME: Convert argument types.
246 std::vector<const llvm::Type*> ArgTys;
248 // Struct return passes the struct byref.
249 if (!ResultType->isFirstClassType() && ResultType != llvm::Type::VoidTy) {
250 ArgTys.push_back(llvm::PointerType::get(ResultType,
251 FP.getResultType().getAddressSpace()));
252 ResultType = llvm::Type::VoidTy;
255 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(&FP)) {
256 DecodeArgumentTypes(*FTP, ArgTys);
257 isVarArg = FTP->isVariadic();
262 return llvm::FunctionType::get(ResultType, ArgTys, isVarArg);
266 return ConvertType(QualType(cast<ASQualType>(Ty).getBaseType(), 0));
268 case Type::ObjCInterface:
269 assert(0 && "FIXME: add missing functionality here");
272 case Type::ObjCQualifiedInterface:
273 assert(0 && "FIXME: add missing functionality here");
276 case Type::ObjCQualifiedId:
277 assert(0 && "FIXME: add missing functionality here");
281 const TagDecl *TD = cast<TagType>(Ty).getDecl();
282 const llvm::Type *Res = ConvertTagDeclType(TD);
284 std::string TypeName(TD->getKindName());
287 // Name the codegen type after the typedef name
288 // if there is no tag type name available
289 if (TD->getIdentifier())
290 TypeName += TD->getName();
291 else if (const TypedefType *TdT = dyn_cast<TypedefType>(T))
292 TypeName += TdT->getDecl()->getName();
296 TheModule.addTypeName(TypeName, Res);
302 return llvm::OpaqueType::get();
305 void CodeGenTypes::DecodeArgumentTypes(const FunctionTypeProto &FTP,
306 std::vector<const llvm::Type*> &ArgTys) {
307 for (unsigned i = 0, e = FTP.getNumArgs(); i != e; ++i) {
308 const llvm::Type *Ty = ConvertType(FTP.getArgType(i));
309 if (Ty->isFirstClassType())
310 ArgTys.push_back(Ty);
312 // byval arguments are always on the stack, which is addr space #0.
313 ArgTys.push_back(llvm::PointerType::getUnqual(Ty));
317 /// ConvertTagDeclType - Lay out a tagged decl type like struct or union or
319 const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) {
320 llvm::DenseMap<const TagDecl*, llvm::PATypeHolder>::iterator TDTI =
321 TagDeclTypes.find(TD);
323 // If we've already compiled this tag type, use the previous definition.
324 if (TDTI != TagDeclTypes.end())
327 // If this is still a forward definition, just define an opaque type to use
328 // for this tagged decl.
329 if (!TD->isDefinition()) {
330 llvm::Type *ResultType = llvm::OpaqueType::get();
331 TagDeclTypes.insert(std::make_pair(TD, ResultType));
335 // Okay, this is a definition of a type. Compile the implementation now.
337 if (TD->getKind() == Decl::Enum) {
338 // Don't bother storing enums in TagDeclTypes.
339 return ConvertType(cast<EnumDecl>(TD)->getIntegerType());
342 // This decl could well be recursive. In this case, insert an opaque
343 // definition of this type, which the recursive uses will get. We will then
344 // refine this opaque version later.
346 // Create new OpaqueType now for later use in case this is a recursive
347 // type. This will later be refined to the actual type.
348 llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get();
349 TagDeclTypes.insert(std::make_pair(TD, ResultHolder));
351 const llvm::Type *ResultType;
352 const RecordDecl *RD = cast<const RecordDecl>(TD);
353 if (TD->getKind() == Decl::Struct || TD->getKind() == Decl::Class) {
355 RecordOrganizer RO(*this);
356 for (unsigned i = 0, e = RD->getNumMembers(); i != e; ++i)
357 RO.addField(RD->getMember(i));
359 RO.layoutStructFields(Context.getASTRecordLayout(RD, SourceLocation()));
361 // Get llvm::StructType.
362 CGRecordLayouts[TD] = new CGRecordLayout(RO.getLLVMType(),
363 RO.getPaddingFields());
364 ResultType = RO.getLLVMType();
366 } else if (TD->getKind() == Decl::Union) {
367 // Just use the largest element of the union, breaking ties with the
368 // highest aligned member.
369 if (RD->getNumMembers() != 0) {
370 RecordOrganizer RO(*this);
371 for (unsigned i = 0, e = RD->getNumMembers(); i != e; ++i)
372 RO.addField(RD->getMember(i));
374 RO.layoutUnionFields();
376 // Get llvm::StructType.
377 CGRecordLayouts[TD] = new CGRecordLayout(RO.getLLVMType(),
378 RO.getPaddingFields());
379 ResultType = RO.getLLVMType();
381 ResultType = llvm::StructType::get(std::vector<const llvm::Type*>());
384 assert(0 && "FIXME: Unknown tag decl kind!");
387 // Refine our Opaque type to ResultType. This can invalidate ResultType, so
388 // make sure to read the result out of the holder.
389 cast<llvm::OpaqueType>(ResultHolder.get())
390 ->refineAbstractTypeTo(ResultType);
392 return ResultHolder.get();
395 /// getLLVMFieldNo - Return llvm::StructType element number
396 /// that corresponds to the field FD.
397 unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) {
398 llvm::DenseMap<const FieldDecl *, unsigned>::iterator
399 I = FieldInfo.find(FD);
400 assert (I != FieldInfo.end() && "Unable to find field info");
404 /// addFieldInfo - Assign field number to field FD.
405 void CodeGenTypes::addFieldInfo(const FieldDecl *FD, unsigned No) {
409 /// getBitFieldInfo - Return the BitFieldInfo that corresponds to the field FD.
410 CodeGenTypes::BitFieldInfo CodeGenTypes::getBitFieldInfo(const FieldDecl *FD) {
411 llvm::DenseMap<const FieldDecl *, BitFieldInfo>::iterator
412 I = BitFields.find(FD);
413 assert (I != BitFields.end() && "Unable to find bitfield info");
417 /// addBitFieldInfo - Assign a start bit and a size to field FD.
418 void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned Begin,
420 BitFields.insert(std::make_pair(FD, BitFieldInfo(Begin, Size)));
423 /// getCGRecordLayout - Return record layout info for the given llvm::Type.
424 const CGRecordLayout *
425 CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const {
426 llvm::DenseMap<const TagDecl*, CGRecordLayout *>::iterator I
427 = CGRecordLayouts.find(TD);
428 assert (I != CGRecordLayouts.end()
429 && "Unable to find record layout information for type");
433 /// addField - Add new field.
434 void RecordOrganizer::addField(const FieldDecl *FD) {
435 assert (!STy && "Record fields are already laid out");
436 FieldDecls.push_back(FD);
439 /// layoutStructFields - Do the actual work and lay out all fields. Create
440 /// corresponding llvm struct type. This should be invoked only after
441 /// all fields are added.
442 /// FIXME : At the moment assume
443 /// - one to one mapping between AST FieldDecls and
444 /// llvm::StructType elements.
445 /// - Ignore bit fields
446 /// - Ignore field aligments
447 /// - Ignore packed structs
448 void RecordOrganizer::layoutStructFields(const ASTRecordLayout &RL) {
449 // FIXME : Use SmallVector
455 for (llvm::SmallVector<const FieldDecl *, 8>::iterator I = FieldDecls.begin(),
456 E = FieldDecls.end(); I != E; ++I) {
457 const FieldDecl *FD = *I;
459 if (FD->isBitField())
462 const llvm::Type *Ty = CGT.ConvertType(FD->getType());
464 CGT.addFieldInfo(FD, llvmFieldNo - 1);
469 unsigned StructAlign = RL.getAlignment();
470 if (llvmSize % StructAlign) {
471 unsigned StructPadding = StructAlign - (llvmSize % StructAlign);
472 addPaddingFields(llvmSize + StructPadding);
475 STy = llvm::StructType::get(LLVMFields);
478 /// addPaddingFields - Current cursor is not suitable place to add next field.
479 /// Add required padding fields.
480 void RecordOrganizer::addPaddingFields(unsigned WaterMark) {
481 assert(WaterMark >= llvmSize && "Invalid padding Field");
482 unsigned RequiredBits = WaterMark - llvmSize;
483 unsigned RequiredBytes = (RequiredBits + 7) / 8;
484 for (unsigned i = 0; i != RequiredBytes; ++i)
485 addLLVMField(llvm::Type::Int8Ty, true);
488 /// addLLVMField - Add llvm struct field that corresponds to llvm type Ty.
489 /// Increment field count.
490 void RecordOrganizer::addLLVMField(const llvm::Type *Ty, bool isPaddingField) {
492 unsigned AlignmentInBits = CGT.getTargetData().getABITypeAlignment(Ty) * 8;
493 if (llvmSize % AlignmentInBits) {
494 // At the moment, insert padding fields even if target specific llvm
495 // type alignment enforces implict padding fields for FD. Later on,
496 // optimize llvm fields by removing implicit padding fields and
497 // combining consequetive padding fields.
498 unsigned Padding = AlignmentInBits - (llvmSize % AlignmentInBits);
499 addPaddingFields(llvmSize + Padding);
502 unsigned TySize = CGT.getTargetData().getABITypeSizeInBits(Ty);
505 PaddingFields.insert(llvmFieldNo);
506 LLVMFields.push_back(Ty);
510 /// layoutUnionFields - Do the actual work and lay out all fields. Create
511 /// corresponding llvm struct type. This should be invoked only after
512 /// all fields are added.
513 void RecordOrganizer::layoutUnionFields() {
515 unsigned PrimaryEltNo = 0;
516 std::pair<uint64_t, unsigned> PrimaryElt =
517 CGT.getContext().getTypeInfo(FieldDecls[0]->getType(), SourceLocation());
518 CGT.addFieldInfo(FieldDecls[0], 0);
520 unsigned Size = FieldDecls.size();
521 for(unsigned i = 1; i != Size; ++i) {
522 const FieldDecl *FD = FieldDecls[i];
523 assert (!FD->isBitField() && "Bit fields are not yet supported");
524 std::pair<uint64_t, unsigned> EltInfo =
525 CGT.getContext().getTypeInfo(FD->getType(), SourceLocation());
527 // Use largest element, breaking ties with the hightest aligned member.
528 if (EltInfo.first > PrimaryElt.first ||
529 (EltInfo.first == PrimaryElt.first &&
530 EltInfo.second > PrimaryElt.second)) {
531 PrimaryElt = EltInfo;
535 // In union, each field gets first slot.
536 CGT.addFieldInfo(FD, 0);
539 std::vector<const llvm::Type*> Fields;
540 const llvm::Type *Ty = CGT.ConvertType(FieldDecls[PrimaryEltNo]->getType());
541 Fields.push_back(Ty);
542 STy = llvm::StructType::get(Fields);
545 /// placeBitField - Find a place for FD, which is a bit-field.
546 /// This function searches for the last aligned field. If the bit-field fits in
547 /// it, it is reused. Otherwise, the bit-field is placed in a new field.
548 void RecordOrganizer::placeBitField(const FieldDecl *FD) {
550 assert (FD->isBitField() && "FD is not a bit-field");
551 Expr *BitWidth = FD->getBitWidth();
552 llvm::APSInt FieldSize(32);
554 BitWidth->isIntegerConstantExpr(FieldSize, CGT.getContext());
555 assert (isBitField && "Invalid BitField size expression");
556 uint64_t BitFieldSize = FieldSize.getZExtValue();
558 const llvm::Type *Ty = CGT.ConvertType(FD->getType());
559 uint64_t TySize = CGT.getTargetData().getABITypeSizeInBits(Ty);
561 unsigned Idx = Cursor / TySize;
562 unsigned BitsLeft = TySize - (Cursor % TySize);
564 if (BitsLeft >= BitFieldSize) {
565 // The bitfield fits in the last aligned field.
566 // This is : struct { char a; int CurrentField:10;};
567 // where 'CurrentField' shares first field with 'a'.
568 CGT.addFieldInfo(FD, Idx);
569 CGT.addBitFieldInfo(FD, TySize - BitsLeft, BitFieldSize);
570 Cursor += BitFieldSize;
572 // Place the bitfield in a new LLVM field.
573 // This is : struct { char a; short CurrentField:10;};
574 // where 'CurrentField' needs a new llvm field.
575 CGT.addFieldInfo(FD, Idx + 1);
576 CGT.addBitFieldInfo(FD, 0, BitFieldSize);
577 Cursor = (Idx + 1) * TySize + BitFieldSize;
579 if (Cursor > llvmSize)
580 addPaddingFields(Cursor);