1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
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 contains code dealing with C++ code generation of virtual tables.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
15 #include "CodeGenFunction.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"
28 using namespace clang;
29 using namespace CodeGen;
31 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32 : CGM(CGM), VTContext(CGM.getContext()) { }
34 bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
35 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
37 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
38 if (TSK == TSK_ExplicitInstantiationDeclaration)
41 const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
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)
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)
58 return KeyFunction->hasBody();
61 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
62 const ThunkInfo &Thunk) {
63 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
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(),
72 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
75 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
76 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
79 static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
81 int64_t NonVirtualAdjustment,
82 int64_t VirtualAdjustment,
83 bool IsReturnAdjustment) {
84 if (!NonVirtualAdjustment && !VirtualAdjustment)
87 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
88 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
90 if (NonVirtualAdjustment && !IsReturnAdjustment) {
91 // Perform the non-virtual adjustment for a base-to-derived cast.
92 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
95 if (VirtualAdjustment) {
96 llvm::Type *PtrDiffTy =
97 CGF.ConvertType(CGF.getContext().getPointerDiffType());
99 // Perform the virtual adjustment.
100 llvm::Value *VTablePtrPtr =
101 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
103 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
105 llvm::Value *OffsetPtr =
106 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
108 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
110 // Load the adjustment offset from the vtable.
111 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
113 // Adjust our pointer.
114 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
117 if (NonVirtualAdjustment && IsReturnAdjustment) {
118 // Perform the non-virtual adjustment for a derived-to-base cast.
119 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
122 // Cast back to the original type.
123 return CGF.Builder.CreateBitCast(V, Ptr->getType());
126 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
127 const ThunkInfo &Thunk, llvm::Function *Fn) {
128 CGM.setGlobalVisibility(Fn, MD);
130 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
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.
138 // This follows CodeGenModule::setTypeVisibility; see the comments
139 // there for explanation.
141 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
142 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
143 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
146 if (MD->getExplicitVisibility())
149 switch (MD->getTemplateSpecializationKind()) {
150 case TSK_ExplicitInstantiationDefinition:
151 case TSK_ExplicitInstantiationDeclaration:
157 case TSK_ExplicitSpecialization:
158 case TSK_ImplicitInstantiation:
163 // If there's an explicit definition, and that definition is
164 // out-of-line, then we can't assume that all users will have a
165 // definition to emit.
166 const FunctionDecl *Def = 0;
167 if (MD->hasBody(Def) && Def->isOutOfLine())
170 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
174 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
175 const ABIArgInfo &infoR, CanQualType typeR) {
176 return (infoL.getKind() == infoR.getKind() &&
178 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
179 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
183 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
184 QualType ResultType, RValue RV,
185 const ThunkInfo &Thunk) {
186 // Emit the return adjustment.
187 bool NullCheckValue = !ResultType->isReferenceType();
189 llvm::BasicBlock *AdjustNull = 0;
190 llvm::BasicBlock *AdjustNotNull = 0;
191 llvm::BasicBlock *AdjustEnd = 0;
193 llvm::Value *ReturnValue = RV.getScalarVal();
195 if (NullCheckValue) {
196 AdjustNull = CGF.createBasicBlock("adjust.null");
197 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
198 AdjustEnd = CGF.createBasicBlock("adjust.end");
200 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
201 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
202 CGF.EmitBlock(AdjustNotNull);
205 ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
206 Thunk.Return.NonVirtual,
207 Thunk.Return.VBaseOffsetOffset,
208 /*IsReturnAdjustment*/true);
210 if (NullCheckValue) {
211 CGF.Builder.CreateBr(AdjustEnd);
212 CGF.EmitBlock(AdjustNull);
213 CGF.Builder.CreateBr(AdjustEnd);
214 CGF.EmitBlock(AdjustEnd);
216 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
217 PHI->addIncoming(ReturnValue, AdjustNotNull);
218 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
223 return RValue::get(ReturnValue);
226 // This function does roughly the same thing as GenerateThunk, but in a
227 // very different way, so that va_start and va_end work correctly.
228 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
229 // a function, and that there is an alloca built in the entry block
230 // for all accesses to "this".
231 // FIXME: This function assumes there is only one "ret" statement per function.
232 // FIXME: Cloning isn't correct in the presence of indirect goto!
233 // FIXME: This implementation of thunks bloats codesize by duplicating the
234 // function definition. There are alternatives:
235 // 1. Add some sort of stub support to LLVM for cases where we can
236 // do a this adjustment, then a sibcall.
237 // 2. We could transform the definition to take a va_list instead of an
238 // actual variable argument list, then have the thunks (including a
239 // no-op thunk for the regular definition) call va_start/va_end.
240 // There's a bit of per-call overhead for this solution, but it's
241 // better for codesize if the definition is long.
242 void CodeGenFunction::GenerateVarArgsThunk(
244 const CGFunctionInfo &FnInfo,
245 GlobalDecl GD, const ThunkInfo &Thunk) {
246 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
247 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
248 QualType ResultType = FPT->getResultType();
250 // Get the original function
251 assert(FnInfo.isVariadic());
252 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
253 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
254 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
257 llvm::ValueToValueMapTy VMap;
258 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
259 /*ModuleLevelChanges=*/false);
260 CGM.getModule().getFunctionList().push_back(NewFn);
261 Fn->replaceAllUsesWith(NewFn);
263 Fn->eraseFromParent();
266 // "Initialize" CGF (minimally).
269 // Get the "this" value
270 llvm::Function::arg_iterator AI = Fn->arg_begin();
271 if (CGM.ReturnTypeUsesSRet(FnInfo))
274 // Find the first store of "this", which will be to the alloca associated
276 llvm::Value *ThisPtr = &*AI;
277 llvm::BasicBlock *EntryBB = Fn->begin();
278 llvm::Instruction *ThisStore = 0;
279 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
281 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
282 ThisStore = cast<llvm::StoreInst>(I);
286 assert(ThisStore && "Store of this should be in entry block?");
287 // Adjust "this", if necessary.
288 Builder.SetInsertPoint(ThisStore);
289 llvm::Value *AdjustedThisPtr =
290 PerformTypeAdjustment(*this, ThisPtr,
291 Thunk.This.NonVirtual,
292 Thunk.This.VCallOffsetOffset,
293 /*IsReturnAdjustment*/false);
294 ThisStore->setOperand(0, AdjustedThisPtr);
296 if (!Thunk.Return.isEmpty()) {
297 // Fix up the returned value, if necessary.
298 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
299 llvm::Instruction *T = I->getTerminator();
300 if (isa<llvm::ReturnInst>(T)) {
301 RValue RV = RValue::get(T->getOperand(0));
302 T->eraseFromParent();
303 Builder.SetInsertPoint(&*I);
304 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
305 Builder.CreateRet(RV.getScalarVal());
312 void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
313 const CGFunctionInfo &FnInfo,
314 GlobalDecl GD, const ThunkInfo &Thunk) {
315 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
316 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
317 QualType ResultType = FPT->getResultType();
318 QualType ThisType = MD->getThisType(getContext());
320 FunctionArgList FunctionArgs;
322 // FIXME: It would be nice if more of this code could be shared with
323 // CodeGenFunction::GenerateCode.
325 // Create the implicit 'this' parameter declaration.
327 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
329 // Add the rest of the parameters.
330 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
331 E = MD->param_end(); I != E; ++I) {
332 ParmVarDecl *Param = *I;
334 FunctionArgs.push_back(Param);
337 // Initialize debug info if needed.
338 maybeInitializeDebugInfo();
340 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
343 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
344 CXXThisValue = CXXABIThisValue;
346 // Adjust the 'this' pointer if necessary.
347 llvm::Value *AdjustedThisPtr =
348 PerformTypeAdjustment(*this, LoadCXXThis(),
349 Thunk.This.NonVirtual,
350 Thunk.This.VCallOffsetOffset,
351 /*IsReturnAdjustment*/false);
353 CallArgList CallArgs;
355 // Add our adjusted 'this' pointer.
356 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
358 // Add the rest of the parameters.
359 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
360 E = MD->param_end(); I != E; ++I) {
361 ParmVarDecl *param = *I;
362 EmitDelegateCallArg(CallArgs, param);
367 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
368 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
371 const CGFunctionInfo &CallFnInfo =
372 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
373 RequiredArgs::forPrototypePlus(FPT, 1));
374 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
375 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
376 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
377 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
378 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
379 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
380 assert(CallFnInfo.arg_size() == FnInfo.arg_size());
381 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
382 assert(similar(CallFnInfo.arg_begin()[i].info,
383 CallFnInfo.arg_begin()[i].type,
384 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
387 // Determine whether we have a return value slot to use.
388 ReturnValueSlot Slot;
389 if (!ResultType->isVoidType() &&
390 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
391 hasAggregateLLVMType(CurFnInfo->getReturnType()))
392 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
394 // Now emit our call.
395 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
397 if (!Thunk.Return.isEmpty())
398 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
400 if (!ResultType->isVoidType() && Slot.isNull())
401 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
403 // Disable the final ARC autorelease.
404 AutoreleaseResult = false;
408 // Set the right linkage.
409 CGM.setFunctionLinkage(MD, Fn);
411 // Set the right visibility.
412 setThunkVisibility(CGM, MD, Thunk, Fn);
415 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
416 bool UseAvailableExternallyLinkage)
418 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
420 // FIXME: re-use FnInfo in this computation.
421 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
423 // Strip off a bitcast if we got one back.
424 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
425 assert(CE->getOpcode() == llvm::Instruction::BitCast);
426 Entry = CE->getOperand(0);
429 // There's already a declaration with the same name, check if it has the same
430 // type or if we need to replace it.
431 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
432 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
433 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
435 // If the types mismatch then we have to rewrite the definition.
436 assert(OldThunkFn->isDeclaration() &&
437 "Shouldn't replace non-declaration");
439 // Remove the name from the old thunk function and get a new thunk.
440 OldThunkFn->setName(StringRef());
441 Entry = CGM.GetAddrOfThunk(GD, Thunk);
443 // If needed, replace the old thunk with a bitcast.
444 if (!OldThunkFn->use_empty()) {
445 llvm::Constant *NewPtrForOldDecl =
446 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
447 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
450 // Remove the old thunk.
451 OldThunkFn->eraseFromParent();
454 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
456 if (!ThunkFn->isDeclaration()) {
457 if (UseAvailableExternallyLinkage) {
458 // There is already a thunk emitted for this function, do nothing.
462 // If a function has a body, it should have available_externally linkage.
463 assert(ThunkFn->hasAvailableExternallyLinkage() &&
464 "Function should have available_externally linkage!");
466 // Change the linkage.
467 CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
471 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
473 if (ThunkFn->isVarArg()) {
474 // Varargs thunks are special; we can't just generate a call because
475 // we can't copy the varargs. Our implementation is rather
476 // expensive/sucky at the moment, so don't generate the thunk unless
478 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
479 if (!UseAvailableExternallyLinkage)
480 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
482 // Normal thunk body generation.
483 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
486 if (UseAvailableExternallyLinkage)
487 ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
490 void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
491 const ThunkInfo &Thunk) {
492 // We only want to do this when building with optimizations.
493 if (!CGM.getCodeGenOpts().OptimizationLevel)
496 // We can't emit thunks for member functions with incomplete types.
497 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
498 if (!CGM.getTypes().isFuncTypeConvertible(
499 cast<FunctionType>(MD->getType().getTypePtr())))
502 EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
505 void CodeGenVTables::EmitThunks(GlobalDecl GD)
507 const CXXMethodDecl *MD =
508 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
510 // We don't need to generate thunks for the base destructor.
511 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
514 const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
515 VTContext.getThunkInfo(MD);
516 if (!ThunkInfoVector)
519 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
520 EmitThunk(GD, (*ThunkInfoVector)[I],
521 /*UseAvailableExternallyLinkage=*/false);
525 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
526 const VTableComponent *Components,
527 unsigned NumComponents,
528 const VTableLayout::VTableThunkTy *VTableThunks,
529 unsigned NumVTableThunks) {
530 SmallVector<llvm::Constant *, 64> Inits;
532 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
534 llvm::Type *PtrDiffTy =
535 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
537 QualType ClassType = CGM.getContext().getTagDeclType(RD);
538 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
540 unsigned NextVTableThunkIndex = 0;
542 llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0;
544 for (unsigned I = 0; I != NumComponents; ++I) {
545 VTableComponent Component = Components[I];
547 llvm::Constant *Init = 0;
549 switch (Component.getKind()) {
550 case VTableComponent::CK_VCallOffset:
551 Init = llvm::ConstantInt::get(PtrDiffTy,
552 Component.getVCallOffset().getQuantity());
553 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
555 case VTableComponent::CK_VBaseOffset:
556 Init = llvm::ConstantInt::get(PtrDiffTy,
557 Component.getVBaseOffset().getQuantity());
558 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
560 case VTableComponent::CK_OffsetToTop:
561 Init = llvm::ConstantInt::get(PtrDiffTy,
562 Component.getOffsetToTop().getQuantity());
563 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
565 case VTableComponent::CK_RTTI:
566 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
568 case VTableComponent::CK_FunctionPointer:
569 case VTableComponent::CK_CompleteDtorPointer:
570 case VTableComponent::CK_DeletingDtorPointer: {
573 // Get the right global decl.
574 switch (Component.getKind()) {
576 llvm_unreachable("Unexpected vtable component kind");
577 case VTableComponent::CK_FunctionPointer:
578 GD = Component.getFunctionDecl();
580 case VTableComponent::CK_CompleteDtorPointer:
581 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
583 case VTableComponent::CK_DeletingDtorPointer:
584 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
588 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
589 // We have a pure virtual member function.
590 if (!PureVirtualFn) {
591 llvm::FunctionType *Ty =
592 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
593 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
594 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
595 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
598 Init = PureVirtualFn;
599 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
600 if (!DeletedVirtualFn) {
601 llvm::FunctionType *Ty =
602 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
603 StringRef DeletedCallName =
604 CGM.getCXXABI().GetDeletedVirtualCallName();
605 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
606 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
609 Init = DeletedVirtualFn;
611 // Check if we should use a thunk.
612 if (NextVTableThunkIndex < NumVTableThunks &&
613 VTableThunks[NextVTableThunkIndex].first == I) {
614 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
616 MaybeEmitThunkAvailableExternally(GD, Thunk);
617 Init = CGM.GetAddrOfThunk(GD, Thunk);
619 NextVTableThunkIndex++;
621 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
623 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
626 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
631 case VTableComponent::CK_UnusedFunctionPointer:
632 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
636 Inits.push_back(Init);
639 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
640 return llvm::ConstantArray::get(ArrayType, Inits);
643 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
644 llvm::GlobalVariable *&VTable = VTables[RD];
648 // We may need to generate a definition for this vtable.
649 if (ShouldEmitVTableInThisTU(RD))
650 CGM.DeferredVTables.push_back(RD);
652 SmallString<256> OutName;
653 llvm::raw_svector_ostream Out(OutName);
654 CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
656 StringRef Name = OutName.str();
658 llvm::ArrayType *ArrayType =
659 llvm::ArrayType::get(CGM.Int8PtrTy,
660 VTContext.getVTableLayout(RD).getNumVTableComponents());
663 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
664 llvm::GlobalValue::ExternalLinkage);
665 VTable->setUnnamedAddr(true);
670 CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
671 llvm::GlobalVariable::LinkageTypes Linkage,
672 const CXXRecordDecl *RD) {
673 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
675 // Create and set the initializer.
676 llvm::Constant *Init =
677 CreateVTableInitializer(RD,
678 VTLayout.vtable_component_begin(),
679 VTLayout.getNumVTableComponents(),
680 VTLayout.vtable_thunk_begin(),
681 VTLayout.getNumVTableThunks());
682 VTable->setInitializer(Init);
684 // Set the correct linkage.
685 VTable->setLinkage(Linkage);
687 // Set the right visibility.
688 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
691 llvm::GlobalVariable *
692 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
693 const BaseSubobject &Base,
695 llvm::GlobalVariable::LinkageTypes Linkage,
696 VTableAddressPointsMapTy& AddressPoints) {
697 OwningPtr<VTableLayout> VTLayout(
698 VTContext.createConstructionVTableLayout(Base.getBase(),
699 Base.getBaseOffset(),
702 // Add the address points.
703 AddressPoints = VTLayout->getAddressPoints();
705 // Get the mangled construction vtable name.
706 SmallString<256> OutName;
707 llvm::raw_svector_ostream Out(OutName);
708 CGM.getCXXABI().getMangleContext().
709 mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
712 StringRef Name = OutName.str();
714 llvm::ArrayType *ArrayType =
715 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
717 // Create the variable that will hold the construction vtable.
718 llvm::GlobalVariable *VTable =
719 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
720 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
722 // V-tables are always unnamed_addr.
723 VTable->setUnnamedAddr(true);
725 // Create and set the initializer.
726 llvm::Constant *Init =
727 CreateVTableInitializer(Base.getBase(),
728 VTLayout->vtable_component_begin(),
729 VTLayout->getNumVTableComponents(),
730 VTLayout->vtable_thunk_begin(),
731 VTLayout->getNumVTableThunks());
732 VTable->setInitializer(Init);
738 CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
739 const CXXRecordDecl *RD) {
740 llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
741 if (VTable->hasInitializer())
744 EmitVTableDefinition(VTable, Linkage, RD);
746 if (RD->getNumVBases()) {
747 llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
748 EmitVTTDefinition(VTT, Linkage, RD);
751 // If this is the magic class __cxxabiv1::__fundamental_type_info,
752 // we will emit the typeinfo for the fundamental types. This is the
753 // same behaviour as GCC.
754 const DeclContext *DC = RD->getDeclContext();
755 if (RD->getIdentifier() &&
756 RD->getIdentifier()->isStr("__fundamental_type_info") &&
757 isa<NamespaceDecl>(DC) &&
758 cast<NamespaceDecl>(DC)->getIdentifier() &&
759 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
760 DC->getParent()->isTranslationUnit())
761 CGM.EmitFundamentalRTTIDescriptors();