CodeGenTypes.cpp revision 198893
183322Speter//===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===// 283322Speter// 383322Speter// The LLVM Compiler Infrastructure 483322Speter// 587629Smikeh// This file is distributed under the University of Illinois Open Source 684829Sdes// License. See LICENSE.TXT for details. 783322Speter// 8109607Sjake//===----------------------------------------------------------------------===// 9109607Sjake// 10109607Sjake// This is the code that handles AST -> LLVM type lowering. 11109607Sjake// 12109607Sjake//===----------------------------------------------------------------------===// 13109607Sjake 1483322Speter#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" 23 24#include "CGCall.h" 25#include "CGRecordLayoutBuilder.h" 26 27using namespace clang; 28using namespace CodeGen; 29 30CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M, 31 const llvm::TargetData &TD) 32 : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD), 33 TheABIInfo(0) { 34} 35 36CodeGenTypes::~CodeGenTypes() { 37 for (llvm::DenseMap<const Type *, CGRecordLayout *>::iterator 38 I = CGRecordLayouts.begin(), E = CGRecordLayouts.end(); 39 I != E; ++I) 40 delete I->second; 41 CGRecordLayouts.clear(); 42} 43 44/// ConvertType - Convert the specified type to its LLVM form. 45const llvm::Type *CodeGenTypes::ConvertType(QualType T) { 46 llvm::PATypeHolder Result = ConvertTypeRecursive(T); 47 48 // Any pointers that were converted defered evaluation of their pointee type, 49 // creating an opaque type instead. This is in order to avoid problems with 50 // circular types. Loop through all these defered pointees, if any, and 51 // resolve them now. 52 while (!PointersToResolve.empty()) { 53 std::pair<QualType, llvm::OpaqueType*> P = 54 PointersToResolve.back(); 55 PointersToResolve.pop_back(); 56 // We can handle bare pointers here because we know that the only pointers 57 // to the Opaque type are P.second and from other types. Refining the 58 // opqaue type away will invalidate P.second, but we don't mind :). 59 const llvm::Type *NT = ConvertTypeForMemRecursive(P.first); 60 P.second->refineAbstractTypeTo(NT); 61 } 62 63 return Result; 64} 65 66const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) { 67 T = Context.getCanonicalType(T); 68 69 // See if type is already cached. 70 llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator 71 I = TypeCache.find(T.getTypePtr()); 72 // If type is found in map and this is not a definition for a opaque 73 // place holder type then use it. Otherwise, convert type T. 74 if (I != TypeCache.end()) 75 return I->second.get(); 76 77 const llvm::Type *ResultType = ConvertNewType(T); 78 TypeCache.insert(std::make_pair(T.getTypePtr(), 79 llvm::PATypeHolder(ResultType))); 80 return ResultType; 81} 82 83const llvm::Type *CodeGenTypes::ConvertTypeForMemRecursive(QualType T) { 84 const llvm::Type *ResultType = ConvertTypeRecursive(T); 85 if (ResultType == llvm::Type::getInt1Ty(getLLVMContext())) 86 return llvm::IntegerType::get(getLLVMContext(), 87 (unsigned)Context.getTypeSize(T)); 88 return ResultType; 89} 90 91/// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from 92/// ConvertType in that it is used to convert to the memory representation for 93/// a type. For example, the scalar representation for _Bool is i1, but the 94/// memory representation is usually i8 or i32, depending on the target. 95const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) { 96 const llvm::Type *R = ConvertType(T); 97 98 // If this is a non-bool type, don't map it. 99 if (R != llvm::Type::getInt1Ty(getLLVMContext())) 100 return R; 101 102 // Otherwise, return an integer of the target-specified size. 103 return llvm::IntegerType::get(getLLVMContext(), 104 (unsigned)Context.getTypeSize(T)); 105 106} 107 108// Code to verify a given function type is complete, i.e. the return type 109// and all of the argument types are complete. 110static const TagType *VerifyFuncTypeComplete(const Type* T) { 111 const FunctionType *FT = cast<FunctionType>(T); 112 if (const TagType* TT = FT->getResultType()->getAs<TagType>()) 113 if (!TT->getDecl()->isDefinition()) 114 return TT; 115 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(T)) 116 for (unsigned i = 0; i < FPT->getNumArgs(); i++) 117 if (const TagType* TT = FPT->getArgType(i)->getAs<TagType>()) 118 if (!TT->getDecl()->isDefinition()) 119 return TT; 120 return 0; 121} 122 123/// UpdateCompletedType - When we find the full definition for a TagDecl, 124/// replace the 'opaque' type we previously made for it if applicable. 125void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { 126 const Type *Key = Context.getTagDeclType(TD).getTypePtr(); 127 llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI = 128 TagDeclTypes.find(Key); 129 if (TDTI == TagDeclTypes.end()) return; 130 131 // Remember the opaque LLVM type for this tagdecl. 132 llvm::PATypeHolder OpaqueHolder = TDTI->second; 133 assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) && 134 "Updating compilation of an already non-opaque type?"); 135 136 // Remove it from TagDeclTypes so that it will be regenerated. 137 TagDeclTypes.erase(TDTI); 138 139 // Generate the new type. 140 const llvm::Type *NT = ConvertTagDeclType(TD); 141 142 // Refine the old opaque type to its new definition. 143 cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT); 144 145 // Since we just completed a tag type, check to see if any function types 146 // were completed along with the tag type. 147 // FIXME: This is very inefficient; if we track which function types depend 148 // on which tag types, though, it should be reasonably efficient. 149 llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator i; 150 for (i = FunctionTypes.begin(); i != FunctionTypes.end(); ++i) { 151 if (const TagType* TT = VerifyFuncTypeComplete(i->first)) { 152 // This function type still depends on an incomplete tag type; make sure 153 // that tag type has an associated opaque type. 154 ConvertTagDeclType(TT->getDecl()); 155 } else { 156 // This function no longer depends on an incomplete tag type; create the 157 // function type, and refine the opaque type to the new function type. 158 llvm::PATypeHolder OpaqueHolder = i->second; 159 const llvm::Type *NFT = ConvertNewType(QualType(i->first, 0)); 160 cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NFT); 161 FunctionTypes.erase(i); 162 } 163 } 164} 165 166static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext, 167 const llvm::fltSemantics &format) { 168 if (&format == &llvm::APFloat::IEEEsingle) 169 return llvm::Type::getFloatTy(VMContext); 170 if (&format == &llvm::APFloat::IEEEdouble) 171 return llvm::Type::getDoubleTy(VMContext); 172 if (&format == &llvm::APFloat::IEEEquad) 173 return llvm::Type::getFP128Ty(VMContext); 174 if (&format == &llvm::APFloat::PPCDoubleDouble) 175 return llvm::Type::getPPC_FP128Ty(VMContext); 176 if (&format == &llvm::APFloat::x87DoubleExtended) 177 return llvm::Type::getX86_FP80Ty(VMContext); 178 assert(0 && "Unknown float format!"); 179 return 0; 180} 181 182const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) { 183 const clang::Type &Ty = *Context.getCanonicalType(T).getTypePtr(); 184 185 switch (Ty.getTypeClass()) { 186#define TYPE(Class, Base) 187#define ABSTRACT_TYPE(Class, Base) 188#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 189#define DEPENDENT_TYPE(Class, Base) case Type::Class: 190#include "clang/AST/TypeNodes.def" 191 assert(false && "Non-canonical or dependent types aren't possible."); 192 break; 193 194 case Type::Builtin: { 195 switch (cast<BuiltinType>(Ty).getKind()) { 196 default: assert(0 && "Unknown builtin type!"); 197 case BuiltinType::Void: 198 case BuiltinType::ObjCId: 199 case BuiltinType::ObjCClass: 200 // LLVM void type can only be used as the result of a function call. Just 201 // map to the same as char. 202 return llvm::IntegerType::get(getLLVMContext(), 8); 203 204 case BuiltinType::Bool: 205 // Note that we always return bool as i1 for use as a scalar type. 206 return llvm::Type::getInt1Ty(getLLVMContext()); 207 208 case BuiltinType::Char_S: 209 case BuiltinType::Char_U: 210 case BuiltinType::SChar: 211 case BuiltinType::UChar: 212 case BuiltinType::Short: 213 case BuiltinType::UShort: 214 case BuiltinType::Int: 215 case BuiltinType::UInt: 216 case BuiltinType::Long: 217 case BuiltinType::ULong: 218 case BuiltinType::LongLong: 219 case BuiltinType::ULongLong: 220 case BuiltinType::WChar: 221 case BuiltinType::Char16: 222 case BuiltinType::Char32: 223 return llvm::IntegerType::get(getLLVMContext(), 224 static_cast<unsigned>(Context.getTypeSize(T))); 225 226 case BuiltinType::Float: 227 case BuiltinType::Double: 228 case BuiltinType::LongDouble: 229 return getTypeForFormat(getLLVMContext(), 230 Context.getFloatTypeSemantics(T)); 231 232 case BuiltinType::NullPtr: { 233 // Model std::nullptr_t as i8* 234 const llvm::Type *Ty = llvm::IntegerType::get(getLLVMContext(), 8); 235 return llvm::PointerType::getUnqual(Ty); 236 } 237 238 case BuiltinType::UInt128: 239 case BuiltinType::Int128: 240 return llvm::IntegerType::get(getLLVMContext(), 128); 241 } 242 break; 243 } 244 case Type::FixedWidthInt: 245 return llvm::IntegerType::get(getLLVMContext(), 246 cast<FixedWidthIntType>(T)->getWidth()); 247 case Type::Complex: { 248 const llvm::Type *EltTy = 249 ConvertTypeRecursive(cast<ComplexType>(Ty).getElementType()); 250 return llvm::StructType::get(TheModule.getContext(), EltTy, EltTy, NULL); 251 } 252 case Type::LValueReference: 253 case Type::RValueReference: { 254 const ReferenceType &RTy = cast<ReferenceType>(Ty); 255 QualType ETy = RTy.getPointeeType(); 256 llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext()); 257 PointersToResolve.push_back(std::make_pair(ETy, PointeeType)); 258 return llvm::PointerType::get(PointeeType, ETy.getAddressSpace()); 259 } 260 case Type::Pointer: { 261 const PointerType &PTy = cast<PointerType>(Ty); 262 QualType ETy = PTy.getPointeeType(); 263 llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext()); 264 PointersToResolve.push_back(std::make_pair(ETy, PointeeType)); 265 return llvm::PointerType::get(PointeeType, ETy.getAddressSpace()); 266 } 267 268 case Type::VariableArray: { 269 const VariableArrayType &A = cast<VariableArrayType>(Ty); 270 assert(A.getIndexTypeCVRQualifiers() == 0 && 271 "FIXME: We only handle trivial array types so far!"); 272 // VLAs resolve to the innermost element type; this matches 273 // the return of alloca, and there isn't any obviously better choice. 274 return ConvertTypeForMemRecursive(A.getElementType()); 275 } 276 case Type::IncompleteArray: { 277 const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty); 278 assert(A.getIndexTypeCVRQualifiers() == 0 && 279 "FIXME: We only handle trivial array types so far!"); 280 // int X[] -> [0 x int] 281 return llvm::ArrayType::get(ConvertTypeForMemRecursive(A.getElementType()), 0); 282 } 283 case Type::ConstantArray: { 284 const ConstantArrayType &A = cast<ConstantArrayType>(Ty); 285 const llvm::Type *EltTy = ConvertTypeForMemRecursive(A.getElementType()); 286 return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue()); 287 } 288 case Type::ExtVector: 289 case Type::Vector: { 290 const VectorType &VT = cast<VectorType>(Ty); 291 return llvm::VectorType::get(ConvertTypeRecursive(VT.getElementType()), 292 VT.getNumElements()); 293 } 294 case Type::FunctionNoProto: 295 case Type::FunctionProto: { 296 // First, check whether we can build the full function type. 297 if (const TagType* TT = VerifyFuncTypeComplete(&Ty)) { 298 // This function's type depends on an incomplete tag type; make sure 299 // we have an opaque type corresponding to the tag type. 300 ConvertTagDeclType(TT->getDecl()); 301 // Create an opaque type for this function type, save it, and return it. 302 llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext()); 303 FunctionTypes.insert(std::make_pair(&Ty, ResultType)); 304 return ResultType; 305 } 306 // The function type can be built; call the appropriate routines to 307 // build it. 308 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(&Ty)) 309 return GetFunctionType(getFunctionInfo(FPT), FPT->isVariadic()); 310 311 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(&Ty); 312 return GetFunctionType(getFunctionInfo(FNPT), true); 313 } 314 315 case Type::ObjCInterface: { 316 // Objective-C interfaces are always opaque (outside of the 317 // runtime, which can do whatever it likes); we never refine 318 // these. 319 const llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(&Ty)]; 320 if (!T) 321 T = llvm::OpaqueType::get(getLLVMContext()); 322 return T; 323 } 324 325 case Type::ObjCObjectPointer: { 326 // Protocol qualifications do not influence the LLVM type, we just return a 327 // pointer to the underlying interface type. We don't need to worry about 328 // recursive conversion. 329 const llvm::Type *T = 330 ConvertTypeRecursive(cast<ObjCObjectPointerType>(Ty).getPointeeType()); 331 return llvm::PointerType::getUnqual(T); 332 } 333 334 case Type::Record: 335 case Type::Enum: { 336 const TagDecl *TD = cast<TagType>(Ty).getDecl(); 337 const llvm::Type *Res = ConvertTagDeclType(TD); 338 339 std::string TypeName(TD->getKindName()); 340 TypeName += '.'; 341 342 // Name the codegen type after the typedef name 343 // if there is no tag type name available 344 if (TD->getIdentifier()) 345 // FIXME: We should not have to check for a null decl context here. 346 // Right now we do it because the implicit Obj-C decls don't have one. 347 TypeName += TD->getDeclContext() ? TD->getQualifiedNameAsString() : 348 TD->getNameAsString(); 349 else if (const TypedefType *TdT = dyn_cast<TypedefType>(T)) 350 // FIXME: We should not have to check for a null decl context here. 351 // Right now we do it because the implicit Obj-C decls don't have one. 352 TypeName += TdT->getDecl()->getDeclContext() ? 353 TdT->getDecl()->getQualifiedNameAsString() : 354 TdT->getDecl()->getNameAsString(); 355 else 356 TypeName += "anon"; 357 358 TheModule.addTypeName(TypeName, Res); 359 return Res; 360 } 361 362 case Type::BlockPointer: { 363 const QualType FTy = cast<BlockPointerType>(Ty).getPointeeType(); 364 llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext()); 365 PointersToResolve.push_back(std::make_pair(FTy, PointeeType)); 366 return llvm::PointerType::get(PointeeType, FTy.getAddressSpace()); 367 } 368 369 case Type::MemberPointer: { 370 // FIXME: This is ABI dependent. We use the Itanium C++ ABI. 371 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers 372 // If we ever want to support other ABIs this needs to be abstracted. 373 374 QualType ETy = cast<MemberPointerType>(Ty).getPointeeType(); 375 if (ETy->isFunctionType()) { 376 return llvm::StructType::get(TheModule.getContext(), 377 ConvertType(Context.getPointerDiffType()), 378 ConvertType(Context.getPointerDiffType()), 379 NULL); 380 } else 381 return ConvertType(Context.getPointerDiffType()); 382 } 383 384 case Type::TemplateSpecialization: 385 assert(false && "Dependent types can't get here"); 386 } 387 388 // FIXME: implement. 389 return llvm::OpaqueType::get(getLLVMContext()); 390} 391 392/// ConvertTagDeclType - Lay out a tagged decl type like struct or union or 393/// enum. 394const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) { 395 396 // FIXME. This may have to move to a better place. 397 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 398 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 399 e = RD->bases_end(); i != e; ++i) { 400 if (!i->isVirtual()) { 401 const CXXRecordDecl *Base = 402 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 403 ConvertTagDeclType(Base); 404 } 405 } 406 } 407 408 // TagDecl's are not necessarily unique, instead use the (clang) 409 // type connected to the decl. 410 const Type *Key = 411 Context.getTagDeclType(TD).getTypePtr(); 412 llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI = 413 TagDeclTypes.find(Key); 414 415 // If we've already compiled this tag type, use the previous definition. 416 if (TDTI != TagDeclTypes.end()) 417 return TDTI->second; 418 419 // If this is still a forward definition, just define an opaque type to use 420 // for this tagged decl. 421 if (!TD->isDefinition()) { 422 llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext()); 423 TagDeclTypes.insert(std::make_pair(Key, ResultType)); 424 return ResultType; 425 } 426 427 // Okay, this is a definition of a type. Compile the implementation now. 428 429 if (TD->isEnum()) { 430 // Don't bother storing enums in TagDeclTypes. 431 return ConvertTypeRecursive(cast<EnumDecl>(TD)->getIntegerType()); 432 } 433 434 // This decl could well be recursive. In this case, insert an opaque 435 // definition of this type, which the recursive uses will get. We will then 436 // refine this opaque version later. 437 438 // Create new OpaqueType now for later use in case this is a recursive 439 // type. This will later be refined to the actual type. 440 llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(getLLVMContext()); 441 TagDeclTypes.insert(std::make_pair(Key, ResultHolder)); 442 443 const llvm::Type *ResultType; 444 const RecordDecl *RD = cast<const RecordDecl>(TD); 445 446 // Layout fields. 447 CGRecordLayout *Layout = 448 CGRecordLayoutBuilder::ComputeLayout(*this, RD); 449 450 CGRecordLayouts[Key] = Layout; 451 ResultType = Layout->getLLVMType(); 452 453 // Refine our Opaque type to ResultType. This can invalidate ResultType, so 454 // make sure to read the result out of the holder. 455 cast<llvm::OpaqueType>(ResultHolder.get()) 456 ->refineAbstractTypeTo(ResultType); 457 458 return ResultHolder.get(); 459} 460 461/// getLLVMFieldNo - Return llvm::StructType element number 462/// that corresponds to the field FD. 463unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) { 464 assert(!FD->isBitField() && "Don't use getLLVMFieldNo on bit fields!"); 465 466 llvm::DenseMap<const FieldDecl*, unsigned>::iterator I = FieldInfo.find(FD); 467 assert (I != FieldInfo.end() && "Unable to find field info"); 468 return I->second; 469} 470 471/// addFieldInfo - Assign field number to field FD. 472void CodeGenTypes::addFieldInfo(const FieldDecl *FD, unsigned No) { 473 FieldInfo[FD] = No; 474} 475 476/// getBitFieldInfo - Return the BitFieldInfo that corresponds to the field FD. 477CodeGenTypes::BitFieldInfo CodeGenTypes::getBitFieldInfo(const FieldDecl *FD) { 478 llvm::DenseMap<const FieldDecl *, BitFieldInfo>::iterator 479 I = BitFields.find(FD); 480 assert (I != BitFields.end() && "Unable to find bitfield info"); 481 return I->second; 482} 483 484/// addBitFieldInfo - Assign a start bit and a size to field FD. 485void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned FieldNo, 486 unsigned Start, unsigned Size) { 487 BitFields.insert(std::make_pair(FD, BitFieldInfo(FieldNo, Start, Size))); 488} 489 490/// getCGRecordLayout - Return record layout info for the given llvm::Type. 491const CGRecordLayout & 492CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const { 493 const Type *Key = 494 Context.getTagDeclType(TD).getTypePtr(); 495 llvm::DenseMap<const Type*, CGRecordLayout *>::iterator I 496 = CGRecordLayouts.find(Key); 497 assert (I != CGRecordLayouts.end() 498 && "Unable to find record layout information for type"); 499 return *I->second; 500} 501