1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===// 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 contains code dealing with C++ code generation of virtual tables. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CodeGenFunction.h" 16 #include "CGCXXABI.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/RecordLayout.h" 19 #include "clang/Frontend/CodeGenOptions.h" 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/Support/Compiler.h" 23 #include "llvm/Support/Format.h" 24 #include "llvm/Transforms/Utils/Cloning.h" 25 #include <algorithm> 26 #include <cstdio> 27 28 using namespace clang; 29 using namespace CodeGen; 30 31 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM) 32 : CGM(CGM), VTContext(CGM.getContext()) { } 33 34 bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) { 35 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable."); 36 37 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind(); 38 if (TSK == TSK_ExplicitInstantiationDeclaration) 39 return false; 40 41 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD); 42 if (!KeyFunction) 43 return true; 44 45 // Itanium C++ ABI, 5.2.6 Instantiated Templates: 46 // An instantiation of a class template requires: 47 // - In the object where instantiated, the virtual table... 48 if (TSK == TSK_ImplicitInstantiation || 49 TSK == TSK_ExplicitInstantiationDefinition) 50 return true; 51 52 // If we're building with optimization, we always emit VTables since that 53 // allows for virtual function calls to be devirtualized. 54 // (We don't want to do this in -fapple-kext mode however). 55 if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOpts().AppleKext) 56 return true; 57 58 return KeyFunction->hasBody(); 59 } 60 61 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD, 62 const ThunkInfo &Thunk) { 63 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 64 65 // Compute the mangled name. 66 SmallString<256> Name; 67 llvm::raw_svector_ostream Out(Name); 68 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD)) 69 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), 70 Thunk.This, Out); 71 else 72 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out); 73 Out.flush(); 74 75 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD); 76 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true); 77 } 78 79 static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF, 80 llvm::Value *Ptr, 81 int64_t NonVirtualAdjustment, 82 int64_t VirtualAdjustment, 83 bool IsReturnAdjustment) { 84 if (!NonVirtualAdjustment && !VirtualAdjustment) 85 return Ptr; 86 87 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 88 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy); 89 90 if (NonVirtualAdjustment && !IsReturnAdjustment) { 91 // Perform the non-virtual adjustment for a base-to-derived cast. 92 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 93 } 94 95 if (VirtualAdjustment) { 96 llvm::Type *PtrDiffTy = 97 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 98 99 // Perform the virtual adjustment. 100 llvm::Value *VTablePtrPtr = 101 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo()); 102 103 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 104 105 llvm::Value *OffsetPtr = 106 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 107 108 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 109 110 // Load the adjustment offset from the vtable. 111 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr); 112 113 // Adjust our pointer. 114 V = CGF.Builder.CreateInBoundsGEP(V, Offset); 115 } 116 117 if (NonVirtualAdjustment && IsReturnAdjustment) { 118 // Perform the non-virtual adjustment for a derived-to-base cast. 119 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 120 } 121 122 // Cast back to the original type. 123 return CGF.Builder.CreateBitCast(V, Ptr->getType()); 124 } 125 126 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD, 127 const ThunkInfo &Thunk, llvm::Function *Fn) { 128 CGM.setGlobalVisibility(Fn, MD); 129 130 if (!CGM.getCodeGenOpts().HiddenWeakVTables) 131 return; 132 133 // If the thunk has weak/linkonce linkage, but the function must be 134 // emitted in every translation unit that references it, then we can 135 // emit its thunks with hidden visibility, since its thunks must be 136 // emitted when the function is. 137 138 // This follows CodeGenModule::setTypeVisibility; see the comments 139 // there for explanation. 140 141 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage && 142 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) || 143 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 144 return; 145 146 if (MD->getExplicitVisibility()) 147 return; 148 149 switch (MD->getTemplateSpecializationKind()) { 150 case TSK_ExplicitInstantiationDefinition: 151 case TSK_ExplicitInstantiationDeclaration: 152 return; 153 154 case TSK_Undeclared: 155 break; 156 157 case TSK_ExplicitSpecialization: 158 case TSK_ImplicitInstantiation: 159 if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables) 160 return; 161 break; 162 } 163 164 // If there's an explicit definition, and that definition is 165 // out-of-line, then we can't assume that all users will have a 166 // definition to emit. 167 const FunctionDecl *Def = 0; 168 if (MD->hasBody(Def) && Def->isOutOfLine()) 169 return; 170 171 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility); 172 } 173 174 #ifndef NDEBUG 175 static bool similar(const ABIArgInfo &infoL, CanQualType typeL, 176 const ABIArgInfo &infoR, CanQualType typeR) { 177 return (infoL.getKind() == infoR.getKind() && 178 (typeL == typeR || 179 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) || 180 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR)))); 181 } 182 #endif 183 184 static RValue PerformReturnAdjustment(CodeGenFunction &CGF, 185 QualType ResultType, RValue RV, 186 const ThunkInfo &Thunk) { 187 // Emit the return adjustment. 188 bool NullCheckValue = !ResultType->isReferenceType(); 189 190 llvm::BasicBlock *AdjustNull = 0; 191 llvm::BasicBlock *AdjustNotNull = 0; 192 llvm::BasicBlock *AdjustEnd = 0; 193 194 llvm::Value *ReturnValue = RV.getScalarVal(); 195 196 if (NullCheckValue) { 197 AdjustNull = CGF.createBasicBlock("adjust.null"); 198 AdjustNotNull = CGF.createBasicBlock("adjust.notnull"); 199 AdjustEnd = CGF.createBasicBlock("adjust.end"); 200 201 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue); 202 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull); 203 CGF.EmitBlock(AdjustNotNull); 204 } 205 206 ReturnValue = PerformTypeAdjustment(CGF, ReturnValue, 207 Thunk.Return.NonVirtual, 208 Thunk.Return.VBaseOffsetOffset, 209 /*IsReturnAdjustment*/true); 210 211 if (NullCheckValue) { 212 CGF.Builder.CreateBr(AdjustEnd); 213 CGF.EmitBlock(AdjustNull); 214 CGF.Builder.CreateBr(AdjustEnd); 215 CGF.EmitBlock(AdjustEnd); 216 217 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2); 218 PHI->addIncoming(ReturnValue, AdjustNotNull); 219 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()), 220 AdjustNull); 221 ReturnValue = PHI; 222 } 223 224 return RValue::get(ReturnValue); 225 } 226 227 // This function does roughly the same thing as GenerateThunk, but in a 228 // very different way, so that va_start and va_end work correctly. 229 // FIXME: This function assumes "this" is the first non-sret LLVM argument of 230 // a function, and that there is an alloca built in the entry block 231 // for all accesses to "this". 232 // FIXME: This function assumes there is only one "ret" statement per function. 233 // FIXME: Cloning isn't correct in the presence of indirect goto! 234 // FIXME: This implementation of thunks bloats codesize by duplicating the 235 // function definition. There are alternatives: 236 // 1. Add some sort of stub support to LLVM for cases where we can 237 // do a this adjustment, then a sibcall. 238 // 2. We could transform the definition to take a va_list instead of an 239 // actual variable argument list, then have the thunks (including a 240 // no-op thunk for the regular definition) call va_start/va_end. 241 // There's a bit of per-call overhead for this solution, but it's 242 // better for codesize if the definition is long. 243 void CodeGenFunction::GenerateVarArgsThunk( 244 llvm::Function *Fn, 245 const CGFunctionInfo &FnInfo, 246 GlobalDecl GD, const ThunkInfo &Thunk) { 247 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 248 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 249 QualType ResultType = FPT->getResultType(); 250 251 // Get the original function 252 assert(FnInfo.isVariadic()); 253 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo); 254 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 255 llvm::Function *BaseFn = cast<llvm::Function>(Callee); 256 257 // Clone to thunk. 258 llvm::ValueToValueMapTy VMap; 259 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap, 260 /*ModuleLevelChanges=*/false); 261 CGM.getModule().getFunctionList().push_back(NewFn); 262 Fn->replaceAllUsesWith(NewFn); 263 NewFn->takeName(Fn); 264 Fn->eraseFromParent(); 265 Fn = NewFn; 266 267 // "Initialize" CGF (minimally). 268 CurFn = Fn; 269 270 // Get the "this" value 271 llvm::Function::arg_iterator AI = Fn->arg_begin(); 272 if (CGM.ReturnTypeUsesSRet(FnInfo)) 273 ++AI; 274 275 // Find the first store of "this", which will be to the alloca associated 276 // with "this". 277 llvm::Value *ThisPtr = &*AI; 278 llvm::BasicBlock *EntryBB = Fn->begin(); 279 llvm::Instruction *ThisStore = 0; 280 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end(); 281 I != E; I++) { 282 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) { 283 ThisStore = cast<llvm::StoreInst>(I); 284 break; 285 } 286 } 287 assert(ThisStore && "Store of this should be in entry block?"); 288 // Adjust "this", if necessary. 289 Builder.SetInsertPoint(ThisStore); 290 llvm::Value *AdjustedThisPtr = 291 PerformTypeAdjustment(*this, ThisPtr, 292 Thunk.This.NonVirtual, 293 Thunk.This.VCallOffsetOffset, 294 /*IsReturnAdjustment*/false); 295 ThisStore->setOperand(0, AdjustedThisPtr); 296 297 if (!Thunk.Return.isEmpty()) { 298 // Fix up the returned value, if necessary. 299 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) { 300 llvm::Instruction *T = I->getTerminator(); 301 if (isa<llvm::ReturnInst>(T)) { 302 RValue RV = RValue::get(T->getOperand(0)); 303 T->eraseFromParent(); 304 Builder.SetInsertPoint(&*I); 305 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk); 306 Builder.CreateRet(RV.getScalarVal()); 307 break; 308 } 309 } 310 } 311 } 312 313 void CodeGenFunction::GenerateThunk(llvm::Function *Fn, 314 const CGFunctionInfo &FnInfo, 315 GlobalDecl GD, const ThunkInfo &Thunk) { 316 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 317 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 318 QualType ResultType = FPT->getResultType(); 319 QualType ThisType = MD->getThisType(getContext()); 320 321 FunctionArgList FunctionArgs; 322 323 // FIXME: It would be nice if more of this code could be shared with 324 // CodeGenFunction::GenerateCode. 325 326 // Create the implicit 'this' parameter declaration. 327 CurGD = GD; 328 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs); 329 330 // Add the rest of the parameters. 331 for (FunctionDecl::param_const_iterator I = MD->param_begin(), 332 E = MD->param_end(); I != E; ++I) { 333 ParmVarDecl *Param = *I; 334 335 FunctionArgs.push_back(Param); 336 } 337 338 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs, 339 SourceLocation()); 340 341 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 342 CXXThisValue = CXXABIThisValue; 343 344 // Adjust the 'this' pointer if necessary. 345 llvm::Value *AdjustedThisPtr = 346 PerformTypeAdjustment(*this, LoadCXXThis(), 347 Thunk.This.NonVirtual, 348 Thunk.This.VCallOffsetOffset, 349 /*IsReturnAdjustment*/false); 350 351 CallArgList CallArgs; 352 353 // Add our adjusted 'this' pointer. 354 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType); 355 356 // Add the rest of the parameters. 357 for (FunctionDecl::param_const_iterator I = MD->param_begin(), 358 E = MD->param_end(); I != E; ++I) { 359 ParmVarDecl *param = *I; 360 EmitDelegateCallArg(CallArgs, param); 361 } 362 363 // Get our callee. 364 llvm::Type *Ty = 365 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD)); 366 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 367 368 #ifndef NDEBUG 369 const CGFunctionInfo &CallFnInfo = 370 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT, 371 RequiredArgs::forPrototypePlus(FPT, 1)); 372 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() && 373 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() && 374 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention()); 375 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types 376 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(), 377 FnInfo.getReturnInfo(), FnInfo.getReturnType())); 378 assert(CallFnInfo.arg_size() == FnInfo.arg_size()); 379 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i) 380 assert(similar(CallFnInfo.arg_begin()[i].info, 381 CallFnInfo.arg_begin()[i].type, 382 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type)); 383 #endif 384 385 // Determine whether we have a return value slot to use. 386 ReturnValueSlot Slot; 387 if (!ResultType->isVoidType() && 388 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect && 389 hasAggregateLLVMType(CurFnInfo->getReturnType())) 390 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified()); 391 392 // Now emit our call. 393 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD); 394 395 if (!Thunk.Return.isEmpty()) 396 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk); 397 398 if (!ResultType->isVoidType() && Slot.isNull()) 399 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType); 400 401 // Disable the final ARC autorelease. 402 AutoreleaseResult = false; 403 404 FinishFunction(); 405 406 // Set the right linkage. 407 CGM.setFunctionLinkage(MD, Fn); 408 409 // Set the right visibility. 410 setThunkVisibility(CGM, MD, Thunk, Fn); 411 } 412 413 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk, 414 bool UseAvailableExternallyLinkage) 415 { 416 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD); 417 418 // FIXME: re-use FnInfo in this computation. 419 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk); 420 421 // Strip off a bitcast if we got one back. 422 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 423 assert(CE->getOpcode() == llvm::Instruction::BitCast); 424 Entry = CE->getOperand(0); 425 } 426 427 // There's already a declaration with the same name, check if it has the same 428 // type or if we need to replace it. 429 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != 430 CGM.getTypes().GetFunctionTypeForVTable(GD)) { 431 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry); 432 433 // If the types mismatch then we have to rewrite the definition. 434 assert(OldThunkFn->isDeclaration() && 435 "Shouldn't replace non-declaration"); 436 437 // Remove the name from the old thunk function and get a new thunk. 438 OldThunkFn->setName(StringRef()); 439 Entry = CGM.GetAddrOfThunk(GD, Thunk); 440 441 // If needed, replace the old thunk with a bitcast. 442 if (!OldThunkFn->use_empty()) { 443 llvm::Constant *NewPtrForOldDecl = 444 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType()); 445 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl); 446 } 447 448 // Remove the old thunk. 449 OldThunkFn->eraseFromParent(); 450 } 451 452 llvm::Function *ThunkFn = cast<llvm::Function>(Entry); 453 454 if (!ThunkFn->isDeclaration()) { 455 if (UseAvailableExternallyLinkage) { 456 // There is already a thunk emitted for this function, do nothing. 457 return; 458 } 459 460 // If a function has a body, it should have available_externally linkage. 461 assert(ThunkFn->hasAvailableExternallyLinkage() && 462 "Function should have available_externally linkage!"); 463 464 // Change the linkage. 465 CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn); 466 return; 467 } 468 469 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn); 470 471 if (ThunkFn->isVarArg()) { 472 // Varargs thunks are special; we can't just generate a call because 473 // we can't copy the varargs. Our implementation is rather 474 // expensive/sucky at the moment, so don't generate the thunk unless 475 // we have to. 476 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly. 477 if (!UseAvailableExternallyLinkage) 478 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk); 479 } else { 480 // Normal thunk body generation. 481 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk); 482 } 483 484 if (UseAvailableExternallyLinkage) 485 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 486 } 487 488 void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD, 489 const ThunkInfo &Thunk) { 490 // We only want to do this when building with optimizations. 491 if (!CGM.getCodeGenOpts().OptimizationLevel) 492 return; 493 494 // We can't emit thunks for member functions with incomplete types. 495 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 496 if (!CGM.getTypes().isFuncTypeConvertible( 497 cast<FunctionType>(MD->getType().getTypePtr()))) 498 return; 499 500 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true); 501 } 502 503 void CodeGenVTables::EmitThunks(GlobalDecl GD) 504 { 505 const CXXMethodDecl *MD = 506 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl(); 507 508 // We don't need to generate thunks for the base destructor. 509 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 510 return; 511 512 const VTableContext::ThunkInfoVectorTy *ThunkInfoVector = 513 VTContext.getThunkInfo(MD); 514 if (!ThunkInfoVector) 515 return; 516 517 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I) 518 EmitThunk(GD, (*ThunkInfoVector)[I], 519 /*UseAvailableExternallyLinkage=*/false); 520 } 521 522 llvm::Constant * 523 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD, 524 const VTableComponent *Components, 525 unsigned NumComponents, 526 const VTableLayout::VTableThunkTy *VTableThunks, 527 unsigned NumVTableThunks) { 528 SmallVector<llvm::Constant *, 64> Inits; 529 530 llvm::Type *Int8PtrTy = CGM.Int8PtrTy; 531 532 llvm::Type *PtrDiffTy = 533 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 534 535 QualType ClassType = CGM.getContext().getTagDeclType(RD); 536 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType); 537 538 unsigned NextVTableThunkIndex = 0; 539 540 llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0; 541 542 for (unsigned I = 0; I != NumComponents; ++I) { 543 VTableComponent Component = Components[I]; 544 545 llvm::Constant *Init = 0; 546 547 switch (Component.getKind()) { 548 case VTableComponent::CK_VCallOffset: 549 Init = llvm::ConstantInt::get(PtrDiffTy, 550 Component.getVCallOffset().getQuantity()); 551 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy); 552 break; 553 case VTableComponent::CK_VBaseOffset: 554 Init = llvm::ConstantInt::get(PtrDiffTy, 555 Component.getVBaseOffset().getQuantity()); 556 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy); 557 break; 558 case VTableComponent::CK_OffsetToTop: 559 Init = llvm::ConstantInt::get(PtrDiffTy, 560 Component.getOffsetToTop().getQuantity()); 561 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy); 562 break; 563 case VTableComponent::CK_RTTI: 564 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy); 565 break; 566 case VTableComponent::CK_FunctionPointer: 567 case VTableComponent::CK_CompleteDtorPointer: 568 case VTableComponent::CK_DeletingDtorPointer: { 569 GlobalDecl GD; 570 571 // Get the right global decl. 572 switch (Component.getKind()) { 573 default: 574 llvm_unreachable("Unexpected vtable component kind"); 575 case VTableComponent::CK_FunctionPointer: 576 GD = Component.getFunctionDecl(); 577 break; 578 case VTableComponent::CK_CompleteDtorPointer: 579 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete); 580 break; 581 case VTableComponent::CK_DeletingDtorPointer: 582 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting); 583 break; 584 } 585 586 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) { 587 // We have a pure virtual member function. 588 if (!PureVirtualFn) { 589 llvm::FunctionType *Ty = 590 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 591 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName(); 592 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName); 593 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn, 594 CGM.Int8PtrTy); 595 } 596 Init = PureVirtualFn; 597 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) { 598 if (!DeletedVirtualFn) { 599 llvm::FunctionType *Ty = 600 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 601 StringRef DeletedCallName = 602 CGM.getCXXABI().GetDeletedVirtualCallName(); 603 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName); 604 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn, 605 CGM.Int8PtrTy); 606 } 607 Init = DeletedVirtualFn; 608 } else { 609 // Check if we should use a thunk. 610 if (NextVTableThunkIndex < NumVTableThunks && 611 VTableThunks[NextVTableThunkIndex].first == I) { 612 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second; 613 614 MaybeEmitThunkAvailableExternally(GD, Thunk); 615 Init = CGM.GetAddrOfThunk(GD, Thunk); 616 617 NextVTableThunkIndex++; 618 } else { 619 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD); 620 621 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 622 } 623 624 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy); 625 } 626 break; 627 } 628 629 case VTableComponent::CK_UnusedFunctionPointer: 630 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy); 631 break; 632 }; 633 634 Inits.push_back(Init); 635 } 636 637 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents); 638 return llvm::ConstantArray::get(ArrayType, Inits); 639 } 640 641 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) { 642 llvm::GlobalVariable *&VTable = VTables[RD]; 643 if (VTable) 644 return VTable; 645 646 // We may need to generate a definition for this vtable. 647 if (ShouldEmitVTableInThisTU(RD)) 648 CGM.DeferredVTables.push_back(RD); 649 650 SmallString<256> OutName; 651 llvm::raw_svector_ostream Out(OutName); 652 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out); 653 Out.flush(); 654 StringRef Name = OutName.str(); 655 656 llvm::ArrayType *ArrayType = 657 llvm::ArrayType::get(CGM.Int8PtrTy, 658 VTContext.getVTableLayout(RD).getNumVTableComponents()); 659 660 VTable = 661 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, 662 llvm::GlobalValue::ExternalLinkage); 663 VTable->setUnnamedAddr(true); 664 return VTable; 665 } 666 667 void 668 CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable, 669 llvm::GlobalVariable::LinkageTypes Linkage, 670 const CXXRecordDecl *RD) { 671 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); 672 673 // Create and set the initializer. 674 llvm::Constant *Init = 675 CreateVTableInitializer(RD, 676 VTLayout.vtable_component_begin(), 677 VTLayout.getNumVTableComponents(), 678 VTLayout.vtable_thunk_begin(), 679 VTLayout.getNumVTableThunks()); 680 VTable->setInitializer(Init); 681 682 // Set the correct linkage. 683 VTable->setLinkage(Linkage); 684 685 // Set the right visibility. 686 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable); 687 } 688 689 llvm::GlobalVariable * 690 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD, 691 const BaseSubobject &Base, 692 bool BaseIsVirtual, 693 llvm::GlobalVariable::LinkageTypes Linkage, 694 VTableAddressPointsMapTy& AddressPoints) { 695 OwningPtr<VTableLayout> VTLayout( 696 VTContext.createConstructionVTableLayout(Base.getBase(), 697 Base.getBaseOffset(), 698 BaseIsVirtual, RD)); 699 700 // Add the address points. 701 AddressPoints = VTLayout->getAddressPoints(); 702 703 // Get the mangled construction vtable name. 704 SmallString<256> OutName; 705 llvm::raw_svector_ostream Out(OutName); 706 CGM.getCXXABI().getMangleContext(). 707 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(), 708 Out); 709 Out.flush(); 710 StringRef Name = OutName.str(); 711 712 llvm::ArrayType *ArrayType = 713 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents()); 714 715 // Create the variable that will hold the construction vtable. 716 llvm::GlobalVariable *VTable = 717 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage); 718 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable); 719 720 // V-tables are always unnamed_addr. 721 VTable->setUnnamedAddr(true); 722 723 // Create and set the initializer. 724 llvm::Constant *Init = 725 CreateVTableInitializer(Base.getBase(), 726 VTLayout->vtable_component_begin(), 727 VTLayout->getNumVTableComponents(), 728 VTLayout->vtable_thunk_begin(), 729 VTLayout->getNumVTableThunks()); 730 VTable->setInitializer(Init); 731 732 return VTable; 733 } 734 735 void 736 CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage, 737 const CXXRecordDecl *RD) { 738 llvm::GlobalVariable *VTable = GetAddrOfVTable(RD); 739 if (VTable->hasInitializer()) 740 return; 741 742 EmitVTableDefinition(VTable, Linkage, RD); 743 744 if (RD->getNumVBases()) { 745 llvm::GlobalVariable *VTT = GetAddrOfVTT(RD); 746 EmitVTTDefinition(VTT, Linkage, RD); 747 } 748 749 // If this is the magic class __cxxabiv1::__fundamental_type_info, 750 // we will emit the typeinfo for the fundamental types. This is the 751 // same behaviour as GCC. 752 const DeclContext *DC = RD->getDeclContext(); 753 if (RD->getIdentifier() && 754 RD->getIdentifier()->isStr("__fundamental_type_info") && 755 isa<NamespaceDecl>(DC) && 756 cast<NamespaceDecl>(DC)->getIdentifier() && 757 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 758 DC->getParent()->isTranslationUnit()) 759 CGM.EmitFundamentalRTTIDescriptors(); 760 } 761