1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This contains code dealing with C++ code generation of virtual tables.
11 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/Basic/CodeGenOptions.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/CodeGen/ConstantInitBuilder.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
29 using namespace clang
;
30 using namespace CodeGen
;
32 CodeGenVTables::CodeGenVTables(CodeGenModule
&CGM
)
33 : CGM(CGM
), VTContext(CGM
.getContext().getVTableContext()) {}
35 llvm::Constant
*CodeGenModule::GetAddrOfThunk(StringRef Name
, llvm::Type
*FnTy
,
37 return GetOrCreateLLVMFunction(Name
, FnTy
, GD
, /*ForVTable=*/true,
38 /*DontDefer=*/true, /*IsThunk=*/true);
41 static void setThunkProperties(CodeGenModule
&CGM
, const ThunkInfo
&Thunk
,
42 llvm::Function
*ThunkFn
, bool ForVTable
,
44 CGM
.setFunctionLinkage(GD
, ThunkFn
);
45 CGM
.getCXXABI().setThunkLinkage(ThunkFn
, ForVTable
, GD
,
46 !Thunk
.Return
.isEmpty());
48 // Set the right visibility.
49 CGM
.setGVProperties(ThunkFn
, GD
);
51 if (!CGM
.getCXXABI().exportThunk()) {
52 ThunkFn
->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass
);
53 ThunkFn
->setDSOLocal(true);
56 if (CGM
.supportsCOMDAT() && ThunkFn
->isWeakForLinker())
57 ThunkFn
->setComdat(CGM
.getModule().getOrInsertComdat(ThunkFn
->getName()));
61 static bool similar(const ABIArgInfo
&infoL
, CanQualType typeL
,
62 const ABIArgInfo
&infoR
, CanQualType typeR
) {
63 return (infoL
.getKind() == infoR
.getKind() &&
65 (isa
<PointerType
>(typeL
) && isa
<PointerType
>(typeR
)) ||
66 (isa
<ReferenceType
>(typeL
) && isa
<ReferenceType
>(typeR
))));
70 static RValue
PerformReturnAdjustment(CodeGenFunction
&CGF
,
71 QualType ResultType
, RValue RV
,
72 const ThunkInfo
&Thunk
) {
73 // Emit the return adjustment.
74 bool NullCheckValue
= !ResultType
->isReferenceType();
76 llvm::BasicBlock
*AdjustNull
= nullptr;
77 llvm::BasicBlock
*AdjustNotNull
= nullptr;
78 llvm::BasicBlock
*AdjustEnd
= nullptr;
80 llvm::Value
*ReturnValue
= RV
.getScalarVal();
83 AdjustNull
= CGF
.createBasicBlock("adjust.null");
84 AdjustNotNull
= CGF
.createBasicBlock("adjust.notnull");
85 AdjustEnd
= CGF
.createBasicBlock("adjust.end");
87 llvm::Value
*IsNull
= CGF
.Builder
.CreateIsNull(ReturnValue
);
88 CGF
.Builder
.CreateCondBr(IsNull
, AdjustNull
, AdjustNotNull
);
89 CGF
.EmitBlock(AdjustNotNull
);
92 auto ClassDecl
= ResultType
->getPointeeType()->getAsCXXRecordDecl();
93 auto ClassAlign
= CGF
.CGM
.getClassPointerAlignment(ClassDecl
);
94 ReturnValue
= CGF
.CGM
.getCXXABI().performReturnAdjustment(
96 Address(ReturnValue
, CGF
.ConvertTypeForMem(ResultType
->getPointeeType()),
100 if (NullCheckValue
) {
101 CGF
.Builder
.CreateBr(AdjustEnd
);
102 CGF
.EmitBlock(AdjustNull
);
103 CGF
.Builder
.CreateBr(AdjustEnd
);
104 CGF
.EmitBlock(AdjustEnd
);
106 llvm::PHINode
*PHI
= CGF
.Builder
.CreatePHI(ReturnValue
->getType(), 2);
107 PHI
->addIncoming(ReturnValue
, AdjustNotNull
);
108 PHI
->addIncoming(llvm::Constant::getNullValue(ReturnValue
->getType()),
113 return RValue::get(ReturnValue
);
116 /// This function clones a function's DISubprogram node and enters it into
117 /// a value map with the intent that the map can be utilized by the cloner
118 /// to short-circuit Metadata node mapping.
119 /// Furthermore, the function resolves any DILocalVariable nodes referenced
120 /// by dbg.value intrinsics so they can be properly mapped during cloning.
121 static void resolveTopLevelMetadata(llvm::Function
*Fn
,
122 llvm::ValueToValueMapTy
&VMap
) {
123 // Clone the DISubprogram node and put it into the Value map.
124 auto *DIS
= Fn
->getSubprogram();
127 auto *NewDIS
= DIS
->replaceWithDistinct(DIS
->clone());
128 VMap
.MD()[DIS
].reset(NewDIS
);
130 // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
131 // they are referencing.
132 for (auto &BB
: *Fn
) {
134 if (auto *DII
= dyn_cast
<llvm::DbgVariableIntrinsic
>(&I
)) {
135 auto *DILocal
= DII
->getVariable();
136 if (!DILocal
->isResolved())
143 // This function does roughly the same thing as GenerateThunk, but in a
144 // very different way, so that va_start and va_end work correctly.
145 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
146 // a function, and that there is an alloca built in the entry block
147 // for all accesses to "this".
148 // FIXME: This function assumes there is only one "ret" statement per function.
149 // FIXME: Cloning isn't correct in the presence of indirect goto!
150 // FIXME: This implementation of thunks bloats codesize by duplicating the
151 // function definition. There are alternatives:
152 // 1. Add some sort of stub support to LLVM for cases where we can
153 // do a this adjustment, then a sibcall.
154 // 2. We could transform the definition to take a va_list instead of an
155 // actual variable argument list, then have the thunks (including a
156 // no-op thunk for the regular definition) call va_start/va_end.
157 // There's a bit of per-call overhead for this solution, but it's
158 // better for codesize if the definition is long.
160 CodeGenFunction::GenerateVarArgsThunk(llvm::Function
*Fn
,
161 const CGFunctionInfo
&FnInfo
,
162 GlobalDecl GD
, const ThunkInfo
&Thunk
) {
163 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
164 const FunctionProtoType
*FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
165 QualType ResultType
= FPT
->getReturnType();
167 // Get the original function
168 assert(FnInfo
.isVariadic());
169 llvm::Type
*Ty
= CGM
.getTypes().GetFunctionType(FnInfo
);
170 llvm::Value
*Callee
= CGM
.GetAddrOfFunction(GD
, Ty
, /*ForVTable=*/true);
171 llvm::Function
*BaseFn
= cast
<llvm::Function
>(Callee
);
173 // Cloning can't work if we don't have a definition. The Microsoft ABI may
174 // require thunks when a definition is not available. Emit an error in these
176 if (!MD
->isDefined()) {
177 CGM
.ErrorUnsupported(MD
, "return-adjusting thunk with variadic arguments");
180 assert(!BaseFn
->isDeclaration() && "cannot clone undefined variadic method");
183 llvm::ValueToValueMapTy VMap
;
185 // We are cloning a function while some Metadata nodes are still unresolved.
186 // Ensure that the value mapper does not encounter any of them.
187 resolveTopLevelMetadata(BaseFn
, VMap
);
188 llvm::Function
*NewFn
= llvm::CloneFunction(BaseFn
, VMap
);
189 Fn
->replaceAllUsesWith(NewFn
);
191 Fn
->eraseFromParent();
194 // "Initialize" CGF (minimally).
197 // Get the "this" value
198 llvm::Function::arg_iterator AI
= Fn
->arg_begin();
199 if (CGM
.ReturnTypeUsesSRet(FnInfo
))
202 // Find the first store of "this", which will be to the alloca associated
205 Address(&*AI
, ConvertTypeForMem(MD
->getFunctionObjectParameterType()),
206 CGM
.getClassPointerAlignment(MD
->getParent()));
207 llvm::BasicBlock
*EntryBB
= &Fn
->front();
208 llvm::BasicBlock::iterator ThisStore
=
209 llvm::find_if(*EntryBB
, [&](llvm::Instruction
&I
) {
210 return isa
<llvm::StoreInst
>(I
) &&
211 I
.getOperand(0) == ThisPtr
.getPointer();
213 assert(ThisStore
!= EntryBB
->end() &&
214 "Store of this should be in entry block?");
215 // Adjust "this", if necessary.
216 Builder
.SetInsertPoint(&*ThisStore
);
217 llvm::Value
*AdjustedThisPtr
=
218 CGM
.getCXXABI().performThisAdjustment(*this, ThisPtr
, Thunk
.This
);
219 AdjustedThisPtr
= Builder
.CreateBitCast(AdjustedThisPtr
,
220 ThisStore
->getOperand(0)->getType());
221 ThisStore
->setOperand(0, AdjustedThisPtr
);
223 if (!Thunk
.Return
.isEmpty()) {
224 // Fix up the returned value, if necessary.
225 for (llvm::BasicBlock
&BB
: *Fn
) {
226 llvm::Instruction
*T
= BB
.getTerminator();
227 if (isa
<llvm::ReturnInst
>(T
)) {
228 RValue RV
= RValue::get(T
->getOperand(0));
229 T
->eraseFromParent();
230 Builder
.SetInsertPoint(&BB
);
231 RV
= PerformReturnAdjustment(*this, ResultType
, RV
, Thunk
);
232 Builder
.CreateRet(RV
.getScalarVal());
241 void CodeGenFunction::StartThunk(llvm::Function
*Fn
, GlobalDecl GD
,
242 const CGFunctionInfo
&FnInfo
,
243 bool IsUnprototyped
) {
244 assert(!CurGD
.getDecl() && "CurGD was already set!");
246 CurFuncIsThunk
= true;
248 // Build FunctionArgs.
249 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
250 QualType ThisType
= MD
->getThisType();
253 ResultType
= CGM
.getContext().VoidTy
;
254 else if (CGM
.getCXXABI().HasThisReturn(GD
))
255 ResultType
= ThisType
;
256 else if (CGM
.getCXXABI().hasMostDerivedReturn(GD
))
257 ResultType
= CGM
.getContext().VoidPtrTy
;
259 ResultType
= MD
->getType()->castAs
<FunctionProtoType
>()->getReturnType();
260 FunctionArgList FunctionArgs
;
262 // Create the implicit 'this' parameter declaration.
263 CGM
.getCXXABI().buildThisParam(*this, FunctionArgs
);
265 // Add the rest of the parameters, if we have a prototype to work with.
266 if (!IsUnprototyped
) {
267 FunctionArgs
.append(MD
->param_begin(), MD
->param_end());
269 if (isa
<CXXDestructorDecl
>(MD
))
270 CGM
.getCXXABI().addImplicitStructorParams(*this, ResultType
,
274 // Start defining the function.
275 auto NL
= ApplyDebugLocation::CreateEmpty(*this);
276 StartFunction(GlobalDecl(), ResultType
, Fn
, FnInfo
, FunctionArgs
,
278 // Create a scope with an artificial location for the body of this function.
279 auto AL
= ApplyDebugLocation::CreateArtificial(*this);
281 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
282 CGM
.getCXXABI().EmitInstanceFunctionProlog(*this);
283 CXXThisValue
= CXXABIThisValue
;
288 void CodeGenFunction::FinishThunk() {
289 // Clear these to restore the invariants expected by
290 // StartFunction/FinishFunction.
291 CurCodeDecl
= nullptr;
292 CurFuncDecl
= nullptr;
297 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee
,
298 const ThunkInfo
*Thunk
,
299 bool IsUnprototyped
) {
300 assert(isa
<CXXMethodDecl
>(CurGD
.getDecl()) &&
301 "Please use a new CGF for this thunk");
302 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(CurGD
.getDecl());
304 // Adjust the 'this' pointer if necessary
305 llvm::Value
*AdjustedThisPtr
=
306 Thunk
? CGM
.getCXXABI().performThisAdjustment(
307 *this, LoadCXXThisAddress(), Thunk
->This
)
310 // If perfect forwarding is required a variadic method, a method using
311 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
312 // thunk requires a return adjustment, since that is impossible with musttail.
313 if (CurFnInfo
->usesInAlloca() || CurFnInfo
->isVariadic() || IsUnprototyped
) {
314 if (Thunk
&& !Thunk
->Return
.isEmpty()) {
316 CGM
.ErrorUnsupported(
317 MD
, "return-adjusting thunk with incomplete parameter type");
318 else if (CurFnInfo
->isVariadic())
319 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
320 "thunks for variadic functions");
322 CGM
.ErrorUnsupported(
323 MD
, "non-trivial argument copy for return-adjusting thunk");
325 EmitMustTailThunk(CurGD
, AdjustedThisPtr
, Callee
);
329 // Start building CallArgs.
330 CallArgList CallArgs
;
331 QualType ThisType
= MD
->getThisType();
332 CallArgs
.add(RValue::get(AdjustedThisPtr
), ThisType
);
334 if (isa
<CXXDestructorDecl
>(MD
))
335 CGM
.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD
, CallArgs
);
338 unsigned PrefixArgs
= CallArgs
.size() - 1;
340 // Add the rest of the arguments.
341 for (const ParmVarDecl
*PD
: MD
->parameters())
342 EmitDelegateCallArg(CallArgs
, PD
, SourceLocation());
344 const FunctionProtoType
*FPT
= MD
->getType()->castAs
<FunctionProtoType
>();
347 const CGFunctionInfo
&CallFnInfo
= CGM
.getTypes().arrangeCXXMethodCall(
348 CallArgs
, FPT
, RequiredArgs::forPrototypePlus(FPT
, 1), PrefixArgs
);
349 assert(CallFnInfo
.getRegParm() == CurFnInfo
->getRegParm() &&
350 CallFnInfo
.isNoReturn() == CurFnInfo
->isNoReturn() &&
351 CallFnInfo
.getCallingConvention() == CurFnInfo
->getCallingConvention());
352 assert(isa
<CXXDestructorDecl
>(MD
) || // ignore dtor return types
353 similar(CallFnInfo
.getReturnInfo(), CallFnInfo
.getReturnType(),
354 CurFnInfo
->getReturnInfo(), CurFnInfo
->getReturnType()));
355 assert(CallFnInfo
.arg_size() == CurFnInfo
->arg_size());
356 for (unsigned i
= 0, e
= CurFnInfo
->arg_size(); i
!= e
; ++i
)
357 assert(similar(CallFnInfo
.arg_begin()[i
].info
,
358 CallFnInfo
.arg_begin()[i
].type
,
359 CurFnInfo
->arg_begin()[i
].info
,
360 CurFnInfo
->arg_begin()[i
].type
));
363 // Determine whether we have a return value slot to use.
364 QualType ResultType
= CGM
.getCXXABI().HasThisReturn(CurGD
)
366 : CGM
.getCXXABI().hasMostDerivedReturn(CurGD
)
367 ? CGM
.getContext().VoidPtrTy
368 : FPT
->getReturnType();
369 ReturnValueSlot Slot
;
370 if (!ResultType
->isVoidType() &&
371 (CurFnInfo
->getReturnInfo().getKind() == ABIArgInfo::Indirect
||
372 hasAggregateEvaluationKind(ResultType
)))
373 Slot
= ReturnValueSlot(ReturnValue
, ResultType
.isVolatileQualified(),
374 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
376 // Now emit our call.
377 llvm::CallBase
*CallOrInvoke
;
378 RValue RV
= EmitCall(*CurFnInfo
, CGCallee::forDirect(Callee
, CurGD
), Slot
,
379 CallArgs
, &CallOrInvoke
);
381 // Consider return adjustment if we have ThunkInfo.
382 if (Thunk
&& !Thunk
->Return
.isEmpty())
383 RV
= PerformReturnAdjustment(*this, ResultType
, RV
, *Thunk
);
384 else if (llvm::CallInst
* Call
= dyn_cast
<llvm::CallInst
>(CallOrInvoke
))
385 Call
->setTailCallKind(llvm::CallInst::TCK_Tail
);
388 if (!ResultType
->isVoidType() && Slot
.isNull())
389 CGM
.getCXXABI().EmitReturnFromThunk(*this, RV
, ResultType
);
391 // Disable the final ARC autorelease.
392 AutoreleaseResult
= false;
397 void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD
,
398 llvm::Value
*AdjustedThisPtr
,
399 llvm::FunctionCallee Callee
) {
400 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
401 // to translate AST arguments into LLVM IR arguments. For thunks, we know
402 // that the caller prototype more or less matches the callee prototype with
403 // the exception of 'this'.
404 SmallVector
<llvm::Value
*, 8> Args(llvm::make_pointer_range(CurFn
->args()));
406 // Set the adjusted 'this' pointer.
407 const ABIArgInfo
&ThisAI
= CurFnInfo
->arg_begin()->info
;
408 if (ThisAI
.isDirect()) {
409 const ABIArgInfo
&RetAI
= CurFnInfo
->getReturnInfo();
410 int ThisArgNo
= RetAI
.isIndirect() && !RetAI
.isSRetAfterThis() ? 1 : 0;
411 llvm::Type
*ThisType
= Args
[ThisArgNo
]->getType();
412 if (ThisType
!= AdjustedThisPtr
->getType())
413 AdjustedThisPtr
= Builder
.CreateBitCast(AdjustedThisPtr
, ThisType
);
414 Args
[ThisArgNo
] = AdjustedThisPtr
;
416 assert(ThisAI
.isInAlloca() && "this is passed directly or inalloca");
417 Address ThisAddr
= GetAddrOfLocalVar(CXXABIThisDecl
);
418 llvm::Type
*ThisType
= ThisAddr
.getElementType();
419 if (ThisType
!= AdjustedThisPtr
->getType())
420 AdjustedThisPtr
= Builder
.CreateBitCast(AdjustedThisPtr
, ThisType
);
421 Builder
.CreateStore(AdjustedThisPtr
, ThisAddr
);
424 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
425 // don't actually want to run them.
426 llvm::CallInst
*Call
= Builder
.CreateCall(Callee
, Args
);
427 Call
->setTailCallKind(llvm::CallInst::TCK_MustTail
);
429 // Apply the standard set of call attributes.
430 unsigned CallingConv
;
431 llvm::AttributeList Attrs
;
432 CGM
.ConstructAttributeList(Callee
.getCallee()->getName(), *CurFnInfo
, GD
,
433 Attrs
, CallingConv
, /*AttrOnCallSite=*/true,
435 Call
->setAttributes(Attrs
);
436 Call
->setCallingConv(static_cast<llvm::CallingConv::ID
>(CallingConv
));
438 if (Call
->getType()->isVoidTy())
439 Builder
.CreateRetVoid();
441 Builder
.CreateRet(Call
);
443 // Finish the function to maintain CodeGenFunction invariants.
444 // FIXME: Don't emit unreachable code.
445 EmitBlock(createBasicBlock());
450 void CodeGenFunction::generateThunk(llvm::Function
*Fn
,
451 const CGFunctionInfo
&FnInfo
, GlobalDecl GD
,
452 const ThunkInfo
&Thunk
,
453 bool IsUnprototyped
) {
454 StartThunk(Fn
, GD
, FnInfo
, IsUnprototyped
);
455 // Create a scope with an artificial location for the body of this function.
456 auto AL
= ApplyDebugLocation::CreateArtificial(*this);
458 // Get our callee. Use a placeholder type if this method is unprototyped so
459 // that CodeGenModule doesn't try to set attributes.
462 Ty
= llvm::StructType::get(getLLVMContext());
464 Ty
= CGM
.getTypes().GetFunctionType(FnInfo
);
466 llvm::Constant
*Callee
= CGM
.GetAddrOfFunction(GD
, Ty
, /*ForVTable=*/true);
468 // Fix up the function type for an unprototyped musttail call.
470 Callee
= llvm::ConstantExpr::getBitCast(Callee
, Fn
->getType());
472 // Make the call and return the result.
473 EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn
->getFunctionType(), Callee
),
474 &Thunk
, IsUnprototyped
);
477 static bool shouldEmitVTableThunk(CodeGenModule
&CGM
, const CXXMethodDecl
*MD
,
478 bool IsUnprototyped
, bool ForVTable
) {
479 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
480 // provide thunks for us.
481 if (CGM
.getTarget().getCXXABI().isMicrosoft())
484 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
485 // definitions of the main method. Therefore, emitting thunks with the vtable
486 // is purely an optimization. Emit the thunk if optimizations are enabled and
487 // all of the parameter types are complete.
489 return CGM
.getCodeGenOpts().OptimizationLevel
&& !IsUnprototyped
;
491 // Always emit thunks along with the method definition.
495 llvm::Constant
*CodeGenVTables::maybeEmitThunk(GlobalDecl GD
,
498 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
500 // First, get a declaration. Compute the mangled name. Don't worry about
501 // getting the function prototype right, since we may only need this
502 // declaration to fill in a vtable slot.
503 SmallString
<256> Name
;
504 MangleContext
&MCtx
= CGM
.getCXXABI().getMangleContext();
505 llvm::raw_svector_ostream
Out(Name
);
506 if (const CXXDestructorDecl
*DD
= dyn_cast
<CXXDestructorDecl
>(MD
))
507 MCtx
.mangleCXXDtorThunk(DD
, GD
.getDtorType(), TI
.This
, Out
);
509 MCtx
.mangleThunk(MD
, TI
, Out
);
510 llvm::Type
*ThunkVTableTy
= CGM
.getTypes().GetFunctionTypeForVTable(GD
);
511 llvm::Constant
*Thunk
= CGM
.GetAddrOfThunk(Name
, ThunkVTableTy
, GD
);
513 // If we don't need to emit a definition, return this declaration as is.
514 bool IsUnprototyped
= !CGM
.getTypes().isFuncTypeConvertible(
515 MD
->getType()->castAs
<FunctionType
>());
516 if (!shouldEmitVTableThunk(CGM
, MD
, IsUnprototyped
, ForVTable
))
519 // Arrange a function prototype appropriate for a function definition. In some
520 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
521 const CGFunctionInfo
&FnInfo
=
522 IsUnprototyped
? CGM
.getTypes().arrangeUnprototypedMustTailThunk(MD
)
523 : CGM
.getTypes().arrangeGlobalDeclaration(GD
);
524 llvm::FunctionType
*ThunkFnTy
= CGM
.getTypes().GetFunctionType(FnInfo
);
526 // If the type of the underlying GlobalValue is wrong, we'll have to replace
527 // it. It should be a declaration.
528 llvm::Function
*ThunkFn
= cast
<llvm::Function
>(Thunk
->stripPointerCasts());
529 if (ThunkFn
->getFunctionType() != ThunkFnTy
) {
530 llvm::GlobalValue
*OldThunkFn
= ThunkFn
;
532 assert(OldThunkFn
->isDeclaration() && "Shouldn't replace non-declaration");
534 // Remove the name from the old thunk function and get a new thunk.
535 OldThunkFn
->setName(StringRef());
536 ThunkFn
= llvm::Function::Create(ThunkFnTy
, llvm::Function::ExternalLinkage
,
537 Name
.str(), &CGM
.getModule());
538 CGM
.SetLLVMFunctionAttributes(MD
, FnInfo
, ThunkFn
, /*IsThunk=*/false);
540 // If needed, replace the old thunk with a bitcast.
541 if (!OldThunkFn
->use_empty()) {
542 llvm::Constant
*NewPtrForOldDecl
=
543 llvm::ConstantExpr::getBitCast(ThunkFn
, OldThunkFn
->getType());
544 OldThunkFn
->replaceAllUsesWith(NewPtrForOldDecl
);
547 // Remove the old thunk.
548 OldThunkFn
->eraseFromParent();
551 bool ABIHasKeyFunctions
= CGM
.getTarget().getCXXABI().hasKeyFunctions();
552 bool UseAvailableExternallyLinkage
= ForVTable
&& ABIHasKeyFunctions
;
554 if (!ThunkFn
->isDeclaration()) {
555 if (!ABIHasKeyFunctions
|| UseAvailableExternallyLinkage
) {
556 // There is already a thunk emitted for this function, do nothing.
560 setThunkProperties(CGM
, TI
, ThunkFn
, ForVTable
, GD
);
564 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
565 // that the return type is meaningless. These thunks can be used to call
566 // functions with differing return types, and the caller is required to cast
567 // the prototype appropriately to extract the correct value.
569 ThunkFn
->addFnAttr("thunk");
571 CGM
.SetLLVMFunctionAttributesForDefinition(GD
.getDecl(), ThunkFn
);
573 // Thunks for variadic methods are special because in general variadic
574 // arguments cannot be perfectly forwarded. In the general case, clang
575 // implements such thunks by cloning the original function body. However, for
576 // thunks with no return adjustment on targets that support musttail, we can
577 // use musttail to perfectly forward the variadic arguments.
578 bool ShouldCloneVarArgs
= false;
579 if (!IsUnprototyped
&& ThunkFn
->isVarArg()) {
580 ShouldCloneVarArgs
= true;
581 if (TI
.Return
.isEmpty()) {
582 switch (CGM
.getTriple().getArch()) {
583 case llvm::Triple::x86_64
:
584 case llvm::Triple::x86
:
585 case llvm::Triple::aarch64
:
586 ShouldCloneVarArgs
= false;
594 if (ShouldCloneVarArgs
) {
595 if (UseAvailableExternallyLinkage
)
598 CodeGenFunction(CGM
).GenerateVarArgsThunk(ThunkFn
, FnInfo
, GD
, TI
);
600 // Normal thunk body generation.
601 CodeGenFunction(CGM
).generateThunk(ThunkFn
, FnInfo
, GD
, TI
, IsUnprototyped
);
604 setThunkProperties(CGM
, TI
, ThunkFn
, ForVTable
, GD
);
608 void CodeGenVTables::EmitThunks(GlobalDecl GD
) {
609 const CXXMethodDecl
*MD
=
610 cast
<CXXMethodDecl
>(GD
.getDecl())->getCanonicalDecl();
612 // We don't need to generate thunks for the base destructor.
613 if (isa
<CXXDestructorDecl
>(MD
) && GD
.getDtorType() == Dtor_Base
)
616 const VTableContextBase::ThunkInfoVectorTy
*ThunkInfoVector
=
617 VTContext
->getThunkInfo(GD
);
619 if (!ThunkInfoVector
)
622 for (const ThunkInfo
& Thunk
: *ThunkInfoVector
)
623 maybeEmitThunk(GD
, Thunk
, /*ForVTable=*/false);
626 void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder
&builder
,
627 llvm::Constant
*component
,
628 unsigned vtableAddressPoint
,
629 bool vtableHasLocalLinkage
,
630 bool isCompleteDtor
) const {
631 // No need to get the offset of a nullptr.
632 if (component
->isNullValue())
633 return builder
.add(llvm::ConstantInt::get(CGM
.Int32Ty
, 0));
636 cast
<llvm::GlobalValue
>(component
->stripPointerCastsAndAliases());
637 llvm::Module
&module
= CGM
.getModule();
639 // We don't want to copy the linkage of the vtable exactly because we still
640 // want the stub/proxy to be emitted for properly calculating the offset.
641 // Examples where there would be no symbol emitted are available_externally
642 // and private linkages.
644 // `internal` linkage results in STB_LOCAL Elf binding while still manifesting a
647 // `linkonce_odr` linkage results in a STB_DEFAULT Elf binding but also allows for
648 // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
649 // target that supports this replacement.
650 auto stubLinkage
= vtableHasLocalLinkage
651 ? llvm::GlobalValue::InternalLinkage
652 : llvm::GlobalValue::LinkOnceODRLinkage
;
654 llvm::Constant
*target
;
655 if (auto *func
= dyn_cast
<llvm::Function
>(globalVal
)) {
656 target
= llvm::DSOLocalEquivalent::get(func
);
658 llvm::SmallString
<16> rttiProxyName(globalVal
->getName());
659 rttiProxyName
.append(".rtti_proxy");
661 // The RTTI component may not always be emitted in the same linkage unit as
662 // the vtable. As a general case, we can make a dso_local proxy to the RTTI
663 // that points to the actual RTTI struct somewhere. This will result in a
664 // GOTPCREL relocation when taking the relative offset to the proxy.
665 llvm::GlobalVariable
*proxy
= module
.getNamedGlobal(rttiProxyName
);
667 proxy
= new llvm::GlobalVariable(module
, globalVal
->getType(),
668 /*isConstant=*/true, stubLinkage
,
669 globalVal
, rttiProxyName
);
670 proxy
->setDSOLocal(true);
671 proxy
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
672 if (!proxy
->hasLocalLinkage()) {
673 proxy
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
674 proxy
->setComdat(module
.getOrInsertComdat(rttiProxyName
));
676 // Do not instrument the rtti proxies with hwasan to avoid a duplicate
677 // symbol error. Aliases generated by hwasan will retain the same namebut
678 // the addresses they are set to may have different tags from different
679 // compilation units. We don't run into this without hwasan because the
680 // proxies are in comdat groups, but those aren't propagated to the alias.
681 RemoveHwasanMetadata(proxy
);
686 builder
.addRelativeOffsetToPosition(CGM
.Int32Ty
, target
,
687 /*position=*/vtableAddressPoint
);
690 static bool UseRelativeLayout(const CodeGenModule
&CGM
) {
691 return CGM
.getTarget().getCXXABI().isItaniumFamily() &&
692 CGM
.getItaniumVTableContext().isRelativeLayout();
695 bool CodeGenVTables::useRelativeLayout() const {
696 return UseRelativeLayout(CGM
);
699 llvm::Type
*CodeGenModule::getVTableComponentType() const {
700 if (UseRelativeLayout(*this))
702 return GlobalsInt8PtrTy
;
705 llvm::Type
*CodeGenVTables::getVTableComponentType() const {
706 return CGM
.getVTableComponentType();
709 static void AddPointerLayoutOffset(const CodeGenModule
&CGM
,
710 ConstantArrayBuilder
&builder
,
712 builder
.add(llvm::ConstantExpr::getIntToPtr(
713 llvm::ConstantInt::get(CGM
.PtrDiffTy
, offset
.getQuantity()),
714 CGM
.GlobalsInt8PtrTy
));
717 static void AddRelativeLayoutOffset(const CodeGenModule
&CGM
,
718 ConstantArrayBuilder
&builder
,
720 builder
.add(llvm::ConstantInt::get(CGM
.Int32Ty
, offset
.getQuantity()));
723 void CodeGenVTables::addVTableComponent(ConstantArrayBuilder
&builder
,
724 const VTableLayout
&layout
,
725 unsigned componentIndex
,
726 llvm::Constant
*rtti
,
727 unsigned &nextVTableThunkIndex
,
728 unsigned vtableAddressPoint
,
729 bool vtableHasLocalLinkage
) {
730 auto &component
= layout
.vtable_components()[componentIndex
];
732 auto addOffsetConstant
=
733 useRelativeLayout() ? AddRelativeLayoutOffset
: AddPointerLayoutOffset
;
735 switch (component
.getKind()) {
736 case VTableComponent::CK_VCallOffset
:
737 return addOffsetConstant(CGM
, builder
, component
.getVCallOffset());
739 case VTableComponent::CK_VBaseOffset
:
740 return addOffsetConstant(CGM
, builder
, component
.getVBaseOffset());
742 case VTableComponent::CK_OffsetToTop
:
743 return addOffsetConstant(CGM
, builder
, component
.getOffsetToTop());
745 case VTableComponent::CK_RTTI
:
746 if (useRelativeLayout())
747 return addRelativeComponent(builder
, rtti
, vtableAddressPoint
,
748 vtableHasLocalLinkage
,
749 /*isCompleteDtor=*/false);
751 return builder
.add(rtti
);
753 case VTableComponent::CK_FunctionPointer
:
754 case VTableComponent::CK_CompleteDtorPointer
:
755 case VTableComponent::CK_DeletingDtorPointer
: {
756 GlobalDecl GD
= component
.getGlobalDecl();
758 if (CGM
.getLangOpts().CUDA
) {
759 // Emit NULL for methods we can't codegen on this
760 // side. Otherwise we'd end up with vtable with unresolved
762 const CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(GD
.getDecl());
763 // OK on device side: functions w/ __device__ attribute
764 // OK on host side: anything except __device__-only functions.
766 CGM
.getLangOpts().CUDAIsDevice
767 ? MD
->hasAttr
<CUDADeviceAttr
>()
768 : (MD
->hasAttr
<CUDAHostAttr
>() || !MD
->hasAttr
<CUDADeviceAttr
>());
771 llvm::ConstantExpr::getNullValue(CGM
.GlobalsInt8PtrTy
));
772 // Method is acceptable, continue processing as usual.
775 auto getSpecialVirtualFn
= [&](StringRef name
) -> llvm::Constant
* {
776 // FIXME(PR43094): When merging comdat groups, lld can select a local
777 // symbol as the signature symbol even though it cannot be accessed
778 // outside that symbol's TU. The relative vtables ABI would make
779 // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
780 // depending on link order, the comdat groups could resolve to the one
781 // with the local symbol. As a temporary solution, fill these components
782 // with zero. We shouldn't be calling these in the first place anyway.
783 if (useRelativeLayout())
784 return llvm::ConstantPointerNull::get(CGM
.GlobalsInt8PtrTy
);
786 // For NVPTX devices in OpenMP emit special functon as null pointers,
787 // otherwise linking ends up with unresolved references.
788 if (CGM
.getLangOpts().OpenMP
&& CGM
.getLangOpts().OpenMPIsTargetDevice
&&
789 CGM
.getTriple().isNVPTX())
790 return llvm::ConstantPointerNull::get(CGM
.GlobalsInt8PtrTy
);
791 llvm::FunctionType
*fnTy
=
792 llvm::FunctionType::get(CGM
.VoidTy
, /*isVarArg=*/false);
793 llvm::Constant
*fn
= cast
<llvm::Constant
>(
794 CGM
.CreateRuntimeFunction(fnTy
, name
).getCallee());
795 if (auto f
= dyn_cast
<llvm::Function
>(fn
))
796 f
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
800 llvm::Constant
*fnPtr
;
802 // Pure virtual member functions.
803 if (cast
<CXXMethodDecl
>(GD
.getDecl())->isPure()) {
806 getSpecialVirtualFn(CGM
.getCXXABI().GetPureVirtualCallName());
807 fnPtr
= PureVirtualFn
;
809 // Deleted virtual member functions.
810 } else if (cast
<CXXMethodDecl
>(GD
.getDecl())->isDeleted()) {
811 if (!DeletedVirtualFn
)
813 getSpecialVirtualFn(CGM
.getCXXABI().GetDeletedVirtualCallName());
814 fnPtr
= DeletedVirtualFn
;
817 } else if (nextVTableThunkIndex
< layout
.vtable_thunks().size() &&
818 layout
.vtable_thunks()[nextVTableThunkIndex
].first
==
820 auto &thunkInfo
= layout
.vtable_thunks()[nextVTableThunkIndex
].second
;
822 nextVTableThunkIndex
++;
823 fnPtr
= maybeEmitThunk(GD
, thunkInfo
, /*ForVTable=*/true);
825 // Otherwise we can use the method definition directly.
827 llvm::Type
*fnTy
= CGM
.getTypes().GetFunctionTypeForVTable(GD
);
828 fnPtr
= CGM
.GetAddrOfFunction(GD
, fnTy
, /*ForVTable=*/true);
831 if (useRelativeLayout()) {
832 return addRelativeComponent(
833 builder
, fnPtr
, vtableAddressPoint
, vtableHasLocalLinkage
,
834 component
.getKind() == VTableComponent::CK_CompleteDtorPointer
);
836 // TODO: this icky and only exists due to functions being in the generic
837 // address space, rather than the global one, even though they are
838 // globals; fixing said issue might be intrusive, and will be done
840 unsigned FnAS
= fnPtr
->getType()->getPointerAddressSpace();
841 unsigned GVAS
= CGM
.GlobalsInt8PtrTy
->getPointerAddressSpace();
845 llvm::ConstantExpr::getAddrSpaceCast(fnPtr
, CGM
.GlobalsInt8PtrTy
);
846 return builder
.add(fnPtr
);
850 case VTableComponent::CK_UnusedFunctionPointer
:
851 if (useRelativeLayout())
852 return builder
.add(llvm::ConstantExpr::getNullValue(CGM
.Int32Ty
));
854 return builder
.addNullPointer(CGM
.GlobalsInt8PtrTy
);
857 llvm_unreachable("Unexpected vtable component kind");
860 llvm::Type
*CodeGenVTables::getVTableType(const VTableLayout
&layout
) {
861 SmallVector
<llvm::Type
*, 4> tys
;
862 llvm::Type
*componentType
= getVTableComponentType();
863 for (unsigned i
= 0, e
= layout
.getNumVTables(); i
!= e
; ++i
)
864 tys
.push_back(llvm::ArrayType::get(componentType
, layout
.getVTableSize(i
)));
866 return llvm::StructType::get(CGM
.getLLVMContext(), tys
);
869 void CodeGenVTables::createVTableInitializer(ConstantStructBuilder
&builder
,
870 const VTableLayout
&layout
,
871 llvm::Constant
*rtti
,
872 bool vtableHasLocalLinkage
) {
873 llvm::Type
*componentType
= getVTableComponentType();
875 const auto &addressPoints
= layout
.getAddressPointIndices();
876 unsigned nextVTableThunkIndex
= 0;
877 for (unsigned vtableIndex
= 0, endIndex
= layout
.getNumVTables();
878 vtableIndex
!= endIndex
; ++vtableIndex
) {
879 auto vtableElem
= builder
.beginArray(componentType
);
881 size_t vtableStart
= layout
.getVTableOffset(vtableIndex
);
882 size_t vtableEnd
= vtableStart
+ layout
.getVTableSize(vtableIndex
);
883 for (size_t componentIndex
= vtableStart
; componentIndex
< vtableEnd
;
885 addVTableComponent(vtableElem
, layout
, componentIndex
, rtti
,
886 nextVTableThunkIndex
, addressPoints
[vtableIndex
],
887 vtableHasLocalLinkage
);
889 vtableElem
.finishAndAddTo(builder
);
893 llvm::GlobalVariable
*CodeGenVTables::GenerateConstructionVTable(
894 const CXXRecordDecl
*RD
, const BaseSubobject
&Base
, bool BaseIsVirtual
,
895 llvm::GlobalVariable::LinkageTypes Linkage
,
896 VTableAddressPointsMapTy
&AddressPoints
) {
897 if (CGDebugInfo
*DI
= CGM
.getModuleDebugInfo())
898 DI
->completeClassData(Base
.getBase());
900 std::unique_ptr
<VTableLayout
> VTLayout(
901 getItaniumVTableContext().createConstructionVTableLayout(
902 Base
.getBase(), Base
.getBaseOffset(), BaseIsVirtual
, RD
));
904 // Add the address points.
905 AddressPoints
= VTLayout
->getAddressPoints();
907 // Get the mangled construction vtable name.
908 SmallString
<256> OutName
;
909 llvm::raw_svector_ostream
Out(OutName
);
910 cast
<ItaniumMangleContext
>(CGM
.getCXXABI().getMangleContext())
911 .mangleCXXCtorVTable(RD
, Base
.getBaseOffset().getQuantity(),
912 Base
.getBase(), Out
);
913 SmallString
<256> Name(OutName
);
915 bool UsingRelativeLayout
= getItaniumVTableContext().isRelativeLayout();
916 bool VTableAliasExists
=
917 UsingRelativeLayout
&& CGM
.getModule().getNamedAlias(Name
);
918 if (VTableAliasExists
) {
919 // We previously made the vtable hidden and changed its name.
920 Name
.append(".local");
923 llvm::Type
*VTType
= getVTableType(*VTLayout
);
925 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
926 // guarantee that they actually will be available externally. Instead, when
927 // emitting an available_externally VTT, we provide references to an internal
928 // linkage construction vtable. The ABI only requires complete-object vtables
929 // to be the same for all instances of a type, not construction vtables.
930 if (Linkage
== llvm::GlobalVariable::AvailableExternallyLinkage
)
931 Linkage
= llvm::GlobalVariable::InternalLinkage
;
933 llvm::Align Align
= CGM
.getDataLayout().getABITypeAlign(VTType
);
935 // Create the variable that will hold the construction vtable.
936 llvm::GlobalVariable
*VTable
=
937 CGM
.CreateOrReplaceCXXRuntimeVariable(Name
, VTType
, Linkage
, Align
);
939 // V-tables are always unnamed_addr.
940 VTable
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
942 llvm::Constant
*RTTI
= CGM
.GetAddrOfRTTIDescriptor(
943 CGM
.getContext().getTagDeclType(Base
.getBase()));
945 // Create and set the initializer.
946 ConstantInitBuilder
builder(CGM
);
947 auto components
= builder
.beginStruct();
948 createVTableInitializer(components
, *VTLayout
, RTTI
,
949 VTable
->hasLocalLinkage());
950 components
.finishAndSetAsInitializer(VTable
);
952 // Set properties only after the initializer has been set to ensure that the
953 // GV is treated as definition and not declaration.
954 assert(!VTable
->isDeclaration() && "Shouldn't set properties on declaration");
955 CGM
.setGVProperties(VTable
, RD
);
957 CGM
.EmitVTableTypeMetadata(RD
, VTable
, *VTLayout
.get());
959 if (UsingRelativeLayout
) {
960 RemoveHwasanMetadata(VTable
);
961 if (!VTable
->isDSOLocal())
962 GenerateRelativeVTableAlias(VTable
, OutName
);
968 // Ensure this vtable is not instrumented by hwasan. That is, a global alias is
969 // not generated for it. This is mainly used by the relative-vtables ABI where
970 // vtables instead contain 32-bit offsets between the vtable and function
971 // pointers. Hwasan is disabled for these vtables for now because the tag in a
972 // vtable pointer may fail the overflow check when resolving 32-bit PLT
973 // relocations. A future alternative for this would be finding which usages of
974 // the vtable can continue to use the untagged hwasan value without any loss of
976 void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue
*GV
) const {
977 if (CGM
.getLangOpts().Sanitize
.has(SanitizerKind::HWAddress
)) {
978 llvm::GlobalValue::SanitizerMetadata Meta
;
979 if (GV
->hasSanitizerMetadata())
980 Meta
= GV
->getSanitizerMetadata();
981 Meta
.NoHWAddress
= true;
982 GV
->setSanitizerMetadata(Meta
);
986 // If the VTable is not dso_local, then we will not be able to indicate that
987 // the VTable does not need a relocation and move into rodata. A frequent
988 // time this can occur is for classes that should be made public from a DSO
989 // (like in libc++). For cases like these, we can make the vtable hidden or
990 // private and create a public alias with the same visibility and linkage as
991 // the original vtable type.
992 void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable
*VTable
,
993 llvm::StringRef AliasNameRef
) {
994 assert(getItaniumVTableContext().isRelativeLayout() &&
995 "Can only use this if the relative vtable ABI is used");
996 assert(!VTable
->isDSOLocal() && "This should be called only if the vtable is "
997 "not guaranteed to be dso_local");
999 // If the vtable is available_externally, we shouldn't (or need to) generate
1000 // an alias for it in the first place since the vtable won't actually by
1001 // emitted in this compilation unit.
1002 if (VTable
->hasAvailableExternallyLinkage())
1005 // Create a new string in the event the alias is already the name of the
1006 // vtable. Using the reference directly could lead to use of an inititialized
1007 // value in the module's StringMap.
1008 llvm::SmallString
<256> AliasName(AliasNameRef
);
1009 VTable
->setName(AliasName
+ ".local");
1011 auto Linkage
= VTable
->getLinkage();
1012 assert(llvm::GlobalAlias::isValidLinkage(Linkage
) &&
1013 "Invalid vtable alias linkage");
1015 llvm::GlobalAlias
*VTableAlias
= CGM
.getModule().getNamedAlias(AliasName
);
1017 VTableAlias
= llvm::GlobalAlias::create(VTable
->getValueType(),
1018 VTable
->getAddressSpace(), Linkage
,
1019 AliasName
, &CGM
.getModule());
1021 assert(VTableAlias
->getValueType() == VTable
->getValueType());
1022 assert(VTableAlias
->getLinkage() == Linkage
);
1024 VTableAlias
->setVisibility(VTable
->getVisibility());
1025 VTableAlias
->setUnnamedAddr(VTable
->getUnnamedAddr());
1027 // Both of these imply dso_local for the vtable.
1028 if (!VTable
->hasComdat()) {
1029 // If this is in a comdat, then we shouldn't make the linkage private due to
1030 // an issue in lld where private symbols can be used as the key symbol when
1031 // choosing the prevelant group. This leads to "relocation refers to a
1032 // symbol in a discarded section".
1033 VTable
->setLinkage(llvm::GlobalValue::PrivateLinkage
);
1035 // We should at least make this hidden since we don't want to expose it.
1036 VTable
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1039 VTableAlias
->setAliasee(VTable
);
1042 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule
&CGM
,
1043 const CXXRecordDecl
*RD
) {
1044 return CGM
.getCodeGenOpts().OptimizationLevel
> 0 &&
1045 CGM
.getCXXABI().canSpeculativelyEmitVTable(RD
);
1048 /// Compute the required linkage of the vtable for the given class.
1050 /// Note that we only call this at the end of the translation unit.
1051 llvm::GlobalVariable::LinkageTypes
1052 CodeGenModule::getVTableLinkage(const CXXRecordDecl
*RD
) {
1053 if (!RD
->isExternallyVisible())
1054 return llvm::GlobalVariable::InternalLinkage
;
1056 // We're at the end of the translation unit, so the current key
1057 // function is fully correct.
1058 const CXXMethodDecl
*keyFunction
= Context
.getCurrentKeyFunction(RD
);
1059 if (keyFunction
&& !RD
->hasAttr
<DLLImportAttr
>()) {
1060 // If this class has a key function, use that to determine the
1061 // linkage of the vtable.
1062 const FunctionDecl
*def
= nullptr;
1063 if (keyFunction
->hasBody(def
))
1064 keyFunction
= cast
<CXXMethodDecl
>(def
);
1066 switch (keyFunction
->getTemplateSpecializationKind()) {
1067 case TSK_Undeclared
:
1068 case TSK_ExplicitSpecialization
:
1070 (def
|| CodeGenOpts
.OptimizationLevel
> 0 ||
1071 CodeGenOpts
.getDebugInfo() != llvm::codegenoptions::NoDebugInfo
) &&
1072 "Shouldn't query vtable linkage without key function, "
1073 "optimizations, or debug info");
1074 if (!def
&& CodeGenOpts
.OptimizationLevel
> 0)
1075 return llvm::GlobalVariable::AvailableExternallyLinkage
;
1077 if (keyFunction
->isInlined())
1078 return !Context
.getLangOpts().AppleKext
1079 ? llvm::GlobalVariable::LinkOnceODRLinkage
1080 : llvm::Function::InternalLinkage
;
1082 return llvm::GlobalVariable::ExternalLinkage
;
1084 case TSK_ImplicitInstantiation
:
1085 return !Context
.getLangOpts().AppleKext
?
1086 llvm::GlobalVariable::LinkOnceODRLinkage
:
1087 llvm::Function::InternalLinkage
;
1089 case TSK_ExplicitInstantiationDefinition
:
1090 return !Context
.getLangOpts().AppleKext
?
1091 llvm::GlobalVariable::WeakODRLinkage
:
1092 llvm::Function::InternalLinkage
;
1094 case TSK_ExplicitInstantiationDeclaration
:
1095 llvm_unreachable("Should not have been asked to emit this");
1099 // -fapple-kext mode does not support weak linkage, so we must use
1100 // internal linkage.
1101 if (Context
.getLangOpts().AppleKext
)
1102 return llvm::Function::InternalLinkage
;
1104 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage
=
1105 llvm::GlobalValue::LinkOnceODRLinkage
;
1106 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage
=
1107 llvm::GlobalValue::WeakODRLinkage
;
1108 if (RD
->hasAttr
<DLLExportAttr
>()) {
1109 // Cannot discard exported vtables.
1110 DiscardableODRLinkage
= NonDiscardableODRLinkage
;
1111 } else if (RD
->hasAttr
<DLLImportAttr
>()) {
1112 // Imported vtables are available externally.
1113 DiscardableODRLinkage
= llvm::GlobalVariable::AvailableExternallyLinkage
;
1114 NonDiscardableODRLinkage
= llvm::GlobalVariable::AvailableExternallyLinkage
;
1117 switch (RD
->getTemplateSpecializationKind()) {
1118 case TSK_Undeclared
:
1119 case TSK_ExplicitSpecialization
:
1120 case TSK_ImplicitInstantiation
:
1121 return DiscardableODRLinkage
;
1123 case TSK_ExplicitInstantiationDeclaration
:
1124 // Explicit instantiations in MSVC do not provide vtables, so we must emit
1126 if (getTarget().getCXXABI().isMicrosoft())
1127 return DiscardableODRLinkage
;
1128 return shouldEmitAvailableExternallyVTable(*this, RD
)
1129 ? llvm::GlobalVariable::AvailableExternallyLinkage
1130 : llvm::GlobalVariable::ExternalLinkage
;
1132 case TSK_ExplicitInstantiationDefinition
:
1133 return NonDiscardableODRLinkage
;
1136 llvm_unreachable("Invalid TemplateSpecializationKind!");
1139 /// This is a callback from Sema to tell us that a particular vtable is
1140 /// required to be emitted in this translation unit.
1142 /// This is only called for vtables that _must_ be emitted (mainly due to key
1143 /// functions). For weak vtables, CodeGen tracks when they are needed and
1144 /// emits them as-needed.
1145 void CodeGenModule::EmitVTable(CXXRecordDecl
*theClass
) {
1146 VTables
.GenerateClassData(theClass
);
1150 CodeGenVTables::GenerateClassData(const CXXRecordDecl
*RD
) {
1151 if (CGDebugInfo
*DI
= CGM
.getModuleDebugInfo())
1152 DI
->completeClassData(RD
);
1154 if (RD
->getNumVBases())
1155 CGM
.getCXXABI().emitVirtualInheritanceTables(RD
);
1157 CGM
.getCXXABI().emitVTableDefinitions(*this, RD
);
1160 /// At this point in the translation unit, does it appear that can we
1161 /// rely on the vtable being defined elsewhere in the program?
1163 /// The response is really only definitive when called at the end of
1164 /// the translation unit.
1166 /// The only semantic restriction here is that the object file should
1167 /// not contain a vtable definition when that vtable is defined
1168 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
1169 /// vtables when unnecessary.
1170 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl
*RD
) {
1171 assert(RD
->isDynamicClass() && "Non-dynamic classes have no VTable.");
1173 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1174 // emit them even if there is an explicit template instantiation.
1175 if (CGM
.getTarget().getCXXABI().isMicrosoft())
1178 // If we have an explicit instantiation declaration (and not a
1179 // definition), the vtable is defined elsewhere.
1180 TemplateSpecializationKind TSK
= RD
->getTemplateSpecializationKind();
1181 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
1184 // Otherwise, if the class is an instantiated template, the
1185 // vtable must be defined here.
1186 if (TSK
== TSK_ImplicitInstantiation
||
1187 TSK
== TSK_ExplicitInstantiationDefinition
)
1190 // Otherwise, if the class doesn't have a key function (possibly
1191 // anymore), the vtable must be defined here.
1192 const CXXMethodDecl
*keyFunction
= CGM
.getContext().getCurrentKeyFunction(RD
);
1196 const FunctionDecl
*Def
;
1197 // Otherwise, if we don't have a definition of the key function, the
1198 // vtable must be defined somewhere else.
1199 if (!keyFunction
->hasBody(Def
))
1202 assert(Def
&& "The body of the key function is not assigned to Def?");
1203 // If the non-inline key function comes from another module unit, the vtable
1204 // must be defined there.
1205 return Def
->isInAnotherModuleUnit() && !Def
->isInlineSpecified();
1208 /// Given that we're currently at the end of the translation unit, and
1209 /// we've emitted a reference to the vtable for this class, should
1210 /// we define that vtable?
1211 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule
&CGM
,
1212 const CXXRecordDecl
*RD
) {
1213 // If vtable is internal then it has to be done.
1214 if (!CGM
.getVTables().isVTableExternal(RD
))
1217 // If it's external then maybe we will need it as available_externally.
1218 return shouldEmitAvailableExternallyVTable(CGM
, RD
);
1221 /// Given that at some point we emitted a reference to one or more
1222 /// vtables, and that we are now at the end of the translation unit,
1223 /// decide whether we should emit them.
1224 void CodeGenModule::EmitDeferredVTables() {
1226 // Remember the size of DeferredVTables, because we're going to assume
1227 // that this entire operation doesn't modify it.
1228 size_t savedSize
= DeferredVTables
.size();
1231 for (const CXXRecordDecl
*RD
: DeferredVTables
)
1232 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD
))
1233 VTables
.GenerateClassData(RD
);
1234 else if (shouldOpportunisticallyEmitVTables())
1235 OpportunisticVTables
.push_back(RD
);
1237 assert(savedSize
== DeferredVTables
.size() &&
1238 "deferred extra vtables during vtable emission?");
1239 DeferredVTables
.clear();
1242 bool CodeGenModule::AlwaysHasLTOVisibilityPublic(const CXXRecordDecl
*RD
) {
1243 if (RD
->hasAttr
<LTOVisibilityPublicAttr
>() || RD
->hasAttr
<UuidAttr
>() ||
1244 RD
->hasAttr
<DLLExportAttr
>() || RD
->hasAttr
<DLLImportAttr
>())
1247 if (!getCodeGenOpts().LTOVisibilityPublicStd
)
1250 const DeclContext
*DC
= RD
;
1252 auto *D
= cast
<Decl
>(DC
);
1253 DC
= DC
->getParent();
1254 if (isa
<TranslationUnitDecl
>(DC
->getRedeclContext())) {
1255 if (auto *ND
= dyn_cast
<NamespaceDecl
>(D
))
1256 if (const IdentifierInfo
*II
= ND
->getIdentifier())
1257 if (II
->isStr("std") || II
->isStr("stdext"))
1266 bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl
*RD
) {
1267 LinkageInfo LV
= RD
->getLinkageAndVisibility();
1268 if (!isExternallyVisible(LV
.getLinkage()))
1271 if (!getTriple().isOSBinFormatCOFF() &&
1272 LV
.getVisibility() != HiddenVisibility
)
1275 return !AlwaysHasLTOVisibilityPublic(RD
);
1278 llvm::GlobalObject::VCallVisibility
CodeGenModule::GetVCallVisibilityLevel(
1279 const CXXRecordDecl
*RD
, llvm::DenseSet
<const CXXRecordDecl
*> &Visited
) {
1280 // If we have already visited this RD (which means this is a recursive call
1281 // since the initial call should have an empty Visited set), return the max
1282 // visibility. The recursive calls below compute the min between the result
1283 // of the recursive call and the current TypeVis, so returning the max here
1284 // ensures that it will have no effect on the current TypeVis.
1285 if (!Visited
.insert(RD
).second
)
1286 return llvm::GlobalObject::VCallVisibilityTranslationUnit
;
1288 LinkageInfo LV
= RD
->getLinkageAndVisibility();
1289 llvm::GlobalObject::VCallVisibility TypeVis
;
1290 if (!isExternallyVisible(LV
.getLinkage()))
1291 TypeVis
= llvm::GlobalObject::VCallVisibilityTranslationUnit
;
1292 else if (HasHiddenLTOVisibility(RD
))
1293 TypeVis
= llvm::GlobalObject::VCallVisibilityLinkageUnit
;
1295 TypeVis
= llvm::GlobalObject::VCallVisibilityPublic
;
1297 for (const auto &B
: RD
->bases())
1298 if (B
.getType()->getAsCXXRecordDecl()->isDynamicClass())
1301 GetVCallVisibilityLevel(B
.getType()->getAsCXXRecordDecl(), Visited
));
1303 for (const auto &B
: RD
->vbases())
1304 if (B
.getType()->getAsCXXRecordDecl()->isDynamicClass())
1307 GetVCallVisibilityLevel(B
.getType()->getAsCXXRecordDecl(), Visited
));
1312 void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl
*RD
,
1313 llvm::GlobalVariable
*VTable
,
1314 const VTableLayout
&VTLayout
) {
1315 if (!getCodeGenOpts().LTOUnit
)
1318 CharUnits ComponentWidth
= GetTargetTypeStoreSize(getVTableComponentType());
1320 struct AddressPoint
{
1321 const CXXRecordDecl
*Base
;
1323 std::string TypeName
;
1324 bool operator<(const AddressPoint
&RHS
) const {
1325 int D
= TypeName
.compare(RHS
.TypeName
);
1326 return D
< 0 || (D
== 0 && Offset
< RHS
.Offset
);
1329 std::vector
<AddressPoint
> AddressPoints
;
1330 for (auto &&AP
: VTLayout
.getAddressPoints()) {
1331 AddressPoint N
{AP
.first
.getBase(),
1332 VTLayout
.getVTableOffset(AP
.second
.VTableIndex
) +
1333 AP
.second
.AddressPointIndex
,
1335 llvm::raw_string_ostream
Stream(N
.TypeName
);
1336 getCXXABI().getMangleContext().mangleCanonicalTypeName(
1337 QualType(N
.Base
->getTypeForDecl(), 0), Stream
);
1338 AddressPoints
.push_back(std::move(N
));
1341 // Sort the address points for determinism.
1342 llvm::sort(AddressPoints
);
1344 ArrayRef
<VTableComponent
> Comps
= VTLayout
.vtable_components();
1345 for (auto AP
: AddressPoints
) {
1346 // Create type metadata for the address point.
1347 AddVTableTypeMetadata(VTable
, ComponentWidth
* AP
.Offset
, AP
.Base
);
1349 // The class associated with each address point could also potentially be
1350 // used for indirect calls via a member function pointer, so we need to
1351 // annotate the address of each function pointer with the appropriate member
1352 // function pointer type.
1353 for (unsigned I
= 0; I
!= Comps
.size(); ++I
) {
1354 if (Comps
[I
].getKind() != VTableComponent::CK_FunctionPointer
)
1356 llvm::Metadata
*MD
= CreateMetadataIdentifierForVirtualMemPtrType(
1357 Context
.getMemberPointerType(
1358 Comps
[I
].getFunctionDecl()->getType(),
1359 Context
.getRecordType(AP
.Base
).getTypePtr()));
1360 VTable
->addTypeMetadata((ComponentWidth
* I
).getQuantity(), MD
);
1364 if (getCodeGenOpts().VirtualFunctionElimination
||
1365 getCodeGenOpts().WholeProgramVTables
) {
1366 llvm::DenseSet
<const CXXRecordDecl
*> Visited
;
1367 llvm::GlobalObject::VCallVisibility TypeVis
=
1368 GetVCallVisibilityLevel(RD
, Visited
);
1369 if (TypeVis
!= llvm::GlobalObject::VCallVisibilityPublic
)
1370 VTable
->setVCallVisibilityMetadata(TypeVis
);