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