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/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Target/TargetData.h"
25 #include "CGRecordLayoutBuilder.h"
27 using namespace clang;
28 using namespace CodeGen;
30 CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M,
31 const llvm::TargetData &TD, const ABIInfo &Info)
32 : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD),
36 CodeGenTypes::~CodeGenTypes() {
37 for (llvm::DenseMap<const Type *, CGRecordLayout *>::iterator
38 I = CGRecordLayouts.begin(), E = CGRecordLayouts.end();
42 for (llvm::FoldingSet<CGFunctionInfo>::iterator
43 I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
47 /// ConvertType - Convert the specified type to its LLVM form.
48 const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
49 llvm::PATypeHolder Result = ConvertTypeRecursive(T);
51 // Any pointers that were converted defered evaluation of their pointee type,
52 // creating an opaque type instead. This is in order to avoid problems with
53 // circular types. Loop through all these defered pointees, if any, and
55 while (!PointersToResolve.empty()) {
56 std::pair<QualType, llvm::OpaqueType*> P = PointersToResolve.pop_back_val();
58 // We can handle bare pointers here because we know that the only pointers
59 // to the Opaque type are P.second and from other types. Refining the
60 // opqaue type away will invalidate P.second, but we don't mind :).
61 const llvm::Type *NT = ConvertTypeForMemRecursive(P.first);
62 P.second->refineAbstractTypeTo(NT);
68 const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) {
69 T = Context.getCanonicalType(T);
71 // See if type is already cached.
72 llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator
73 I = TypeCache.find(T.getTypePtr());
74 // If type is found in map and this is not a definition for a opaque
75 // place holder type then use it. Otherwise, convert type T.
76 if (I != TypeCache.end())
77 return I->second.get();
79 const llvm::Type *ResultType = ConvertNewType(T);
80 TypeCache.insert(std::make_pair(T.getTypePtr(),
81 llvm::PATypeHolder(ResultType)));
85 const llvm::Type *CodeGenTypes::ConvertTypeForMemRecursive(QualType T) {
86 const llvm::Type *ResultType = ConvertTypeRecursive(T);
87 if (ResultType->isIntegerTy(1))
88 return llvm::IntegerType::get(getLLVMContext(),
89 (unsigned)Context.getTypeSize(T));
90 // FIXME: Should assert that the llvm type and AST type has the same size.
94 /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
95 /// ConvertType in that it is used to convert to the memory representation for
96 /// a type. For example, the scalar representation for _Bool is i1, but the
97 /// memory representation is usually i8 or i32, depending on the target.
98 const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
99 const llvm::Type *R = ConvertType(T);
101 // If this is a non-bool type, don't map it.
102 if (!R->isIntegerTy(1))
105 // Otherwise, return an integer of the target-specified size.
106 return llvm::IntegerType::get(getLLVMContext(),
107 (unsigned)Context.getTypeSize(T));
111 // Code to verify a given function type is complete, i.e. the return type
112 // and all of the argument types are complete.
113 static const TagType *VerifyFuncTypeComplete(const Type* T) {
114 const FunctionType *FT = cast<FunctionType>(T);
115 if (const TagType* TT = FT->getResultType()->getAs<TagType>())
116 if (!TT->getDecl()->isDefinition())
118 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(T))
119 for (unsigned i = 0; i < FPT->getNumArgs(); i++)
120 if (const TagType* TT = FPT->getArgType(i)->getAs<TagType>())
121 if (!TT->getDecl()->isDefinition())
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 const Type *Key = Context.getTagDeclType(TD).getTypePtr();
130 llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
131 TagDeclTypes.find(Key);
132 if (TDTI == TagDeclTypes.end()) return;
134 // Remember the opaque LLVM type for this tagdecl.
135 llvm::PATypeHolder OpaqueHolder = TDTI->second;
136 assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) &&
137 "Updating compilation of an already non-opaque type?");
139 // Remove it from TagDeclTypes so that it will be regenerated.
140 TagDeclTypes.erase(TDTI);
142 // Generate the new type.
143 const llvm::Type *NT = ConvertTagDeclType(TD);
145 // Refine the old opaque type to its new definition.
146 cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT);
148 // Since we just completed a tag type, check to see if any function types
149 // were completed along with the tag type.
150 // FIXME: This is very inefficient; if we track which function types depend
151 // on which tag types, though, it should be reasonably efficient.
152 llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator i;
153 for (i = FunctionTypes.begin(); i != FunctionTypes.end(); ++i) {
154 if (const TagType* TT = VerifyFuncTypeComplete(i->first)) {
155 // This function type still depends on an incomplete tag type; make sure
156 // that tag type has an associated opaque type.
157 ConvertTagDeclType(TT->getDecl());
159 // This function no longer depends on an incomplete tag type; create the
160 // function type, and refine the opaque type to the new function type.
161 llvm::PATypeHolder OpaqueHolder = i->second;
162 const llvm::Type *NFT = ConvertNewType(QualType(i->first, 0));
163 cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NFT);
164 FunctionTypes.erase(i);
169 static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext,
170 const llvm::fltSemantics &format) {
171 if (&format == &llvm::APFloat::IEEEsingle)
172 return llvm::Type::getFloatTy(VMContext);
173 if (&format == &llvm::APFloat::IEEEdouble)
174 return llvm::Type::getDoubleTy(VMContext);
175 if (&format == &llvm::APFloat::IEEEquad)
176 return llvm::Type::getFP128Ty(VMContext);
177 if (&format == &llvm::APFloat::PPCDoubleDouble)
178 return llvm::Type::getPPC_FP128Ty(VMContext);
179 if (&format == &llvm::APFloat::x87DoubleExtended)
180 return llvm::Type::getX86_FP80Ty(VMContext);
181 assert(0 && "Unknown float format!");
185 const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) {
186 const clang::Type &Ty = *Context.getCanonicalType(T).getTypePtr();
188 switch (Ty.getTypeClass()) {
189 #define TYPE(Class, Base)
190 #define ABSTRACT_TYPE(Class, Base)
191 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
192 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
193 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
194 #include "clang/AST/TypeNodes.def"
195 assert(false && "Non-canonical or dependent types aren't possible.");
198 case Type::Builtin: {
199 switch (cast<BuiltinType>(Ty).getKind()) {
200 case BuiltinType::Void:
201 case BuiltinType::ObjCId:
202 case BuiltinType::ObjCClass:
203 case BuiltinType::ObjCSel:
204 // LLVM void type can only be used as the result of a function call. Just
205 // map to the same as char.
206 return llvm::IntegerType::get(getLLVMContext(), 8);
208 case BuiltinType::Bool:
209 // Note that we always return bool as i1 for use as a scalar type.
210 return llvm::Type::getInt1Ty(getLLVMContext());
212 case BuiltinType::Char_S:
213 case BuiltinType::Char_U:
214 case BuiltinType::SChar:
215 case BuiltinType::UChar:
216 case BuiltinType::Short:
217 case BuiltinType::UShort:
218 case BuiltinType::Int:
219 case BuiltinType::UInt:
220 case BuiltinType::Long:
221 case BuiltinType::ULong:
222 case BuiltinType::LongLong:
223 case BuiltinType::ULongLong:
224 case BuiltinType::WChar:
225 case BuiltinType::Char16:
226 case BuiltinType::Char32:
227 return llvm::IntegerType::get(getLLVMContext(),
228 static_cast<unsigned>(Context.getTypeSize(T)));
230 case BuiltinType::Float:
231 case BuiltinType::Double:
232 case BuiltinType::LongDouble:
233 return getTypeForFormat(getLLVMContext(),
234 Context.getFloatTypeSemantics(T));
236 case BuiltinType::NullPtr: {
237 // Model std::nullptr_t as i8*
238 const llvm::Type *Ty = llvm::IntegerType::get(getLLVMContext(), 8);
239 return llvm::PointerType::getUnqual(Ty);
242 case BuiltinType::UInt128:
243 case BuiltinType::Int128:
244 return llvm::IntegerType::get(getLLVMContext(), 128);
246 case BuiltinType::Overload:
247 case BuiltinType::Dependent:
248 case BuiltinType::UndeducedAuto:
249 assert(0 && "Unexpected builtin type!");
252 assert(0 && "Unknown builtin type!");
255 case Type::Complex: {
256 const llvm::Type *EltTy =
257 ConvertTypeRecursive(cast<ComplexType>(Ty).getElementType());
258 return llvm::StructType::get(TheModule.getContext(), EltTy, EltTy, NULL);
260 case Type::LValueReference:
261 case Type::RValueReference: {
262 const ReferenceType &RTy = cast<ReferenceType>(Ty);
263 QualType ETy = RTy.getPointeeType();
264 llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
265 PointersToResolve.push_back(std::make_pair(ETy, PointeeType));
266 return llvm::PointerType::get(PointeeType, ETy.getAddressSpace());
268 case Type::Pointer: {
269 const PointerType &PTy = cast<PointerType>(Ty);
270 QualType ETy = PTy.getPointeeType();
271 llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
272 PointersToResolve.push_back(std::make_pair(ETy, PointeeType));
273 return llvm::PointerType::get(PointeeType, ETy.getAddressSpace());
276 case Type::VariableArray: {
277 const VariableArrayType &A = cast<VariableArrayType>(Ty);
278 assert(A.getIndexTypeCVRQualifiers() == 0 &&
279 "FIXME: We only handle trivial array types so far!");
280 // VLAs resolve to the innermost element type; this matches
281 // the return of alloca, and there isn't any obviously better choice.
282 return ConvertTypeForMemRecursive(A.getElementType());
284 case Type::IncompleteArray: {
285 const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty);
286 assert(A.getIndexTypeCVRQualifiers() == 0 &&
287 "FIXME: We only handle trivial array types so far!");
288 // int X[] -> [0 x int]
289 return llvm::ArrayType::get(ConvertTypeForMemRecursive(A.getElementType()), 0);
291 case Type::ConstantArray: {
292 const ConstantArrayType &A = cast<ConstantArrayType>(Ty);
293 const llvm::Type *EltTy = ConvertTypeForMemRecursive(A.getElementType());
294 return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue());
296 case Type::ExtVector:
298 const VectorType &VT = cast<VectorType>(Ty);
299 return llvm::VectorType::get(ConvertTypeRecursive(VT.getElementType()),
300 VT.getNumElements());
302 case Type::FunctionNoProto:
303 case Type::FunctionProto: {
304 // First, check whether we can build the full function type.
305 if (const TagType* TT = VerifyFuncTypeComplete(&Ty)) {
306 // This function's type depends on an incomplete tag type; make sure
307 // we have an opaque type corresponding to the tag type.
308 ConvertTagDeclType(TT->getDecl());
309 // Create an opaque type for this function type, save it, and return it.
310 llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
311 FunctionTypes.insert(std::make_pair(&Ty, ResultType));
314 // The function type can be built; call the appropriate routines to
316 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(&Ty))
317 return GetFunctionType(getFunctionInfo(
318 CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT,0))),
321 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(&Ty);
322 return GetFunctionType(getFunctionInfo(
323 CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT,0))),
327 case Type::ObjCInterface: {
328 // Objective-C interfaces are always opaque (outside of the
329 // runtime, which can do whatever it likes); we never refine
331 const llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(&Ty)];
333 T = llvm::OpaqueType::get(getLLVMContext());
337 case Type::ObjCObjectPointer: {
338 // Protocol qualifications do not influence the LLVM type, we just return a
339 // pointer to the underlying interface type. We don't need to worry about
340 // recursive conversion.
341 const llvm::Type *T =
342 ConvertTypeRecursive(cast<ObjCObjectPointerType>(Ty).getPointeeType());
343 return llvm::PointerType::getUnqual(T);
348 const TagDecl *TD = cast<TagType>(Ty).getDecl();
349 const llvm::Type *Res = ConvertTagDeclType(TD);
351 std::string TypeName(TD->getKindName());
354 // Name the codegen type after the typedef name
355 // if there is no tag type name available
356 if (TD->getIdentifier())
357 // FIXME: We should not have to check for a null decl context here.
358 // Right now we do it because the implicit Obj-C decls don't have one.
359 TypeName += TD->getDeclContext() ? TD->getQualifiedNameAsString() :
360 TD->getNameAsString();
361 else if (const TypedefType *TdT = dyn_cast<TypedefType>(T))
362 // FIXME: We should not have to check for a null decl context here.
363 // Right now we do it because the implicit Obj-C decls don't have one.
364 TypeName += TdT->getDecl()->getDeclContext() ?
365 TdT->getDecl()->getQualifiedNameAsString() :
366 TdT->getDecl()->getNameAsString();
370 TheModule.addTypeName(TypeName, Res);
374 case Type::BlockPointer: {
375 const QualType FTy = cast<BlockPointerType>(Ty).getPointeeType();
376 llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
377 PointersToResolve.push_back(std::make_pair(FTy, PointeeType));
378 return llvm::PointerType::get(PointeeType, FTy.getAddressSpace());
381 case Type::MemberPointer: {
382 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
383 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
384 // If we ever want to support other ABIs this needs to be abstracted.
386 QualType ETy = cast<MemberPointerType>(Ty).getPointeeType();
387 const llvm::Type *PtrDiffTy =
388 ConvertTypeRecursive(Context.getPointerDiffType());
389 if (ETy->isFunctionType())
390 return llvm::StructType::get(TheModule.getContext(), PtrDiffTy, PtrDiffTy,
397 return llvm::OpaqueType::get(getLLVMContext());
400 /// ConvertTagDeclType - Lay out a tagged decl type like struct or union or
402 const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) {
404 // TagDecl's are not necessarily unique, instead use the (clang)
405 // type connected to the decl.
407 Context.getTagDeclType(TD).getTypePtr();
408 llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
409 TagDeclTypes.find(Key);
411 // If we've already compiled this tag type, use the previous definition.
412 if (TDTI != TagDeclTypes.end())
415 // If this is still a forward declaration, just define an opaque
416 // type to use for this tagged decl.
417 if (!TD->isDefinition()) {
418 llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
419 TagDeclTypes.insert(std::make_pair(Key, ResultType));
423 // Okay, this is a definition of a type. Compile the implementation now.
425 if (TD->isEnum()) // Don't bother storing enums in TagDeclTypes.
426 return ConvertTypeRecursive(cast<EnumDecl>(TD)->getIntegerType());
428 // This decl could well be recursive. In this case, insert an opaque
429 // definition of this type, which the recursive uses will get. We will then
430 // refine this opaque version later.
432 // Create new OpaqueType now for later use in case this is a recursive
433 // type. This will later be refined to the actual type.
434 llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(getLLVMContext());
435 TagDeclTypes.insert(std::make_pair(Key, ResultHolder));
437 const RecordDecl *RD = cast<const RecordDecl>(TD);
439 // Force conversion of non-virtual base classes recursively.
440 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
441 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
442 e = RD->bases_end(); i != e; ++i) {
443 if (!i->isVirtual()) {
444 const CXXRecordDecl *Base =
445 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
446 ConvertTagDeclType(Base);
452 CGRecordLayout *Layout = CGRecordLayoutBuilder::ComputeLayout(*this, RD);
454 CGRecordLayouts[Key] = Layout;
455 const llvm::Type *ResultType = Layout->getLLVMType();
457 // Refine our Opaque type to ResultType. This can invalidate ResultType, so
458 // make sure to read the result out of the holder.
459 cast<llvm::OpaqueType>(ResultHolder.get())
460 ->refineAbstractTypeTo(ResultType);
462 return ResultHolder.get();
465 /// getLLVMFieldNo - Return llvm::StructType element number
466 /// that corresponds to the field FD.
467 unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) {
468 assert(!FD->isBitField() && "Don't use getLLVMFieldNo on bit fields!");
470 llvm::DenseMap<const FieldDecl*, unsigned>::iterator I = FieldInfo.find(FD);
471 assert (I != FieldInfo.end() && "Unable to find field info");
475 /// addFieldInfo - Assign field number to field FD.
476 void CodeGenTypes::addFieldInfo(const FieldDecl *FD, unsigned No) {
480 /// getBitFieldInfo - Return the BitFieldInfo that corresponds to the field FD.
481 CodeGenTypes::BitFieldInfo CodeGenTypes::getBitFieldInfo(const FieldDecl *FD) {
482 llvm::DenseMap<const FieldDecl *, BitFieldInfo>::iterator
483 I = BitFields.find(FD);
484 assert (I != BitFields.end() && "Unable to find bitfield info");
488 /// addBitFieldInfo - Assign a start bit and a size to field FD.
489 void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned FieldNo,
490 unsigned Start, unsigned Size) {
491 BitFields.insert(std::make_pair(FD, BitFieldInfo(FieldNo, Start, Size)));
494 /// getCGRecordLayout - Return record layout info for the given llvm::Type.
495 const CGRecordLayout &
496 CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const {
497 const Type *Key = Context.getTagDeclType(TD).getTypePtr();
498 llvm::DenseMap<const Type*, CGRecordLayout *>::const_iterator I
499 = CGRecordLayouts.find(Key);
500 assert (I != CGRecordLayouts.end()
501 && "Unable to find record layout information for type");