1//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of virtual tables.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/Basic/CodeGenOptions.h"
21#include "clang/CodeGen/CGFunctionInfo.h"
22#include "clang/CodeGen/ConstantInitBuilder.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/Transforms/Utils/Cloning.h"
25#include <algorithm>
26#include <cstdio>
27#include <utility>
28
29using namespace clang;
30using namespace CodeGen;
31
32CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
34
35llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
36 GlobalDecl GD) {
37 return GetOrCreateLLVMFunction(MangledName: Name, Ty: FnTy, D: GD, /*ForVTable=*/true,
38 /*DontDefer=*/true, /*IsThunk=*/true);
39}
40
41llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
42 llvm::GlobalVariable *VTable =
43 CGM.getCXXABI().getAddrOfVTable(RD, VPtrOffset: CharUnits());
44 return VTable;
45}
46
47static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
48 llvm::Function *ThunkFn, bool ForVTable,
49 GlobalDecl GD) {
50 CGM.setFunctionLinkage(GD, F: ThunkFn);
51 CGM.getCXXABI().setThunkLinkage(Thunk: ThunkFn, ForVTable, GD,
52 ReturnAdjustment: !Thunk.Return.isEmpty());
53
54 // Set the right visibility.
55 CGM.setGVProperties(GV: ThunkFn, GD);
56
57 if (!CGM.getCXXABI().exportThunk()) {
58 ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
59 ThunkFn->setDSOLocal(true);
60 }
61
62 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
63 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(Name: ThunkFn->getName()));
64}
65
66#ifndef NDEBUG
67static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
68 const ABIArgInfo &infoR, CanQualType typeR) {
69 return (infoL.getKind() == infoR.getKind() &&
70 (typeL == typeR ||
71 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
72 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
73}
74#endif
75
76static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
77 QualType ResultType, RValue RV,
78 const ThunkInfo &Thunk) {
79 // Emit the return adjustment.
80 bool NullCheckValue = !ResultType->isReferenceType();
81
82 llvm::BasicBlock *AdjustNull = nullptr;
83 llvm::BasicBlock *AdjustNotNull = nullptr;
84 llvm::BasicBlock *AdjustEnd = nullptr;
85
86 llvm::Value *ReturnValue = RV.getScalarVal();
87
88 if (NullCheckValue) {
89 AdjustNull = CGF.createBasicBlock(name: "adjust.null");
90 AdjustNotNull = CGF.createBasicBlock(name: "adjust.notnull");
91 AdjustEnd = CGF.createBasicBlock(name: "adjust.end");
92
93 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Arg: ReturnValue);
94 CGF.Builder.CreateCondBr(Cond: IsNull, True: AdjustNull, False: AdjustNotNull);
95 CGF.EmitBlock(BB: AdjustNotNull);
96 }
97
98 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
99 auto ClassAlign = CGF.CGM.getClassPointerAlignment(CD: ClassDecl);
100 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(
101 CGF,
102 Ret: Address(ReturnValue, CGF.ConvertTypeForMem(T: ResultType->getPointeeType()),
103 ClassAlign),
104 UnadjustedClass: ClassDecl, RA: Thunk.Return);
105
106 if (NullCheckValue) {
107 CGF.Builder.CreateBr(Dest: AdjustEnd);
108 CGF.EmitBlock(BB: AdjustNull);
109 CGF.Builder.CreateBr(Dest: AdjustEnd);
110 CGF.EmitBlock(BB: AdjustEnd);
111
112 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Ty: ReturnValue->getType(), NumReservedValues: 2);
113 PHI->addIncoming(V: ReturnValue, BB: AdjustNotNull);
114 PHI->addIncoming(V: llvm::Constant::getNullValue(Ty: ReturnValue->getType()),
115 BB: AdjustNull);
116 ReturnValue = PHI;
117 }
118
119 return RValue::get(V: ReturnValue);
120}
121
122/// This function clones a function's DISubprogram node and enters it into
123/// a value map with the intent that the map can be utilized by the cloner
124/// to short-circuit Metadata node mapping.
125/// Furthermore, the function resolves any DILocalVariable nodes referenced
126/// by dbg.value intrinsics so they can be properly mapped during cloning.
127static void resolveTopLevelMetadata(llvm::Function *Fn,
128 llvm::ValueToValueMapTy &VMap) {
129 // Clone the DISubprogram node and put it into the Value map.
130 auto *DIS = Fn->getSubprogram();
131 if (!DIS)
132 return;
133 auto *NewDIS = llvm::MDNode::replaceWithDistinct(N: DIS->clone());
134 // As DISubprogram remapping is avoided, clear retained nodes list of
135 // cloned DISubprogram from retained nodes local to original DISubprogram.
136 // FIXME: Thunk function signature is produced wrong in DWARF, as retained
137 // nodes are not remapped.
138 NewDIS->replaceRetainedNodes(N: llvm::MDTuple::get(Context&: Fn->getContext(), MDs: {}));
139 VMap.MD()[DIS].reset(MD: NewDIS);
140
141 // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
142 // they are referencing.
143 //
144 // DIDerivedTypes referring to incomplete Clang types, or
145 // LLVM enumeration types representing complete enums with no definition
146 // may be still unresolved. As they can't be cloned, keep references
147 // to the types from the base subprogram.
148 // FIXME: As a result, variables of cloned subprogram may refer to local types
149 // from base subprogram. In such case, type locality information is damaged.
150 // Find a way to enable cloning of all local types.
151 auto PrepareVariableMapping = [&VMap](llvm::DILocalVariable *DILocal) {
152 if (DILocal->isResolved())
153 return;
154
155 if (llvm::DIType *Ty = DILocal->getType(); Ty && !Ty->isResolved())
156 VMap.MD()[Ty].reset(MD: Ty);
157
158 DILocal->resolve();
159 };
160
161 for (auto &BB : *Fn) {
162 for (auto &I : BB) {
163 for (llvm::DbgVariableRecord &DVR :
164 llvm::filterDbgVars(R: I.getDbgRecordRange()))
165 PrepareVariableMapping(DVR.getVariable());
166 }
167 }
168}
169
170// This function does roughly the same thing as GenerateThunk, but in a
171// very different way, so that va_start and va_end work correctly.
172// FIXME: This function assumes "this" is the first non-sret LLVM argument of
173// a function, and that there is an alloca built in the entry block
174// for all accesses to "this".
175// FIXME: This function assumes there is only one "ret" statement per function.
176// FIXME: Cloning isn't correct in the presence of indirect goto!
177// FIXME: This implementation of thunks bloats codesize by duplicating the
178// function definition. There are alternatives:
179// 1. Add some sort of stub support to LLVM for cases where we can
180// do a this adjustment, then a sibcall.
181// 2. We could transform the definition to take a va_list instead of an
182// actual variable argument list, then have the thunks (including a
183// no-op thunk for the regular definition) call va_start/va_end.
184// There's a bit of per-call overhead for this solution, but it's
185// better for codesize if the definition is long.
186llvm::Function *
187CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
188 const CGFunctionInfo &FnInfo,
189 GlobalDecl GD, const ThunkInfo &Thunk) {
190 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
191 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
192 QualType ResultType = FPT->getReturnType();
193
194 // Get the original function
195 assert(FnInfo.isVariadic());
196 llvm::Type *Ty = CGM.getTypes().GetFunctionType(Info: FnInfo);
197 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
198 llvm::Function *BaseFn = cast<llvm::Function>(Val: Callee);
199
200 // Cloning can't work if we don't have a definition. The Microsoft ABI may
201 // require thunks when a definition is not available. Emit an error in these
202 // cases.
203 if (!MD->isDefined()) {
204 CGM.ErrorUnsupported(D: MD, Type: "return-adjusting thunk with variadic arguments");
205 return Fn;
206 }
207 assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
208
209 // Clone to thunk.
210 llvm::ValueToValueMapTy VMap;
211
212 // We are cloning a function while some Metadata nodes are still unresolved.
213 // Ensure that the value mapper does not encounter any of them.
214 resolveTopLevelMetadata(Fn: BaseFn, VMap);
215 llvm::Function *NewFn = llvm::CloneFunction(F: BaseFn, VMap);
216
217 // The clone inherited the callee's attributes. Keep its function attributes,
218 // which describe the cloned body, but take the return and parameter
219 // attributes from the thunk declaration.
220 llvm::AttributeList ThunkAttrs = Fn->getAttributes();
221 SmallVector<llvm::AttributeSet, 8> ParamAttrs;
222 for (unsigned I = 0, N = NewFn->arg_size(); I != N; ++I)
223 ParamAttrs.push_back(Elt: ThunkAttrs.getParamAttrs(ArgNo: I));
224 NewFn->setAttributes(llvm::AttributeList::get(
225 C&: getLLVMContext(), FnAttrs: NewFn->getAttributes().getFnAttrs(),
226 RetAttrs: ThunkAttrs.getRetAttrs(), ArgAttrs: ParamAttrs));
227
228 Fn->replaceAllUsesWith(V: NewFn);
229 NewFn->takeName(V: Fn);
230 Fn->eraseFromParent();
231 Fn = NewFn;
232
233 // "Initialize" CGF (minimally).
234 CurFn = Fn;
235
236 // Get the "this" value
237 llvm::Function::arg_iterator AI = Fn->arg_begin();
238 if (CGM.ReturnTypeUsesSRet(FI: FnInfo))
239 ++AI;
240
241 const CXXRecordDecl *ThisValueClass =
242 Thunk.ThisType->getPointeeCXXRecordDecl();
243
244 // Find the first store of "this", which will be to the alloca associated
245 // with "this".
246 Address ThisPtr = makeNaturalAddressForPointer(
247 Ptr: &*AI, T: Thunk.ThisType->getPointeeType(),
248 Alignment: CGM.getClassPointerAlignment(CD: ThisValueClass));
249 llvm::BasicBlock *EntryBB = &Fn->front();
250 llvm::BasicBlock::iterator ThisStore =
251 llvm::find_if(Range&: *EntryBB, P: [&](llvm::Instruction &I) {
252 return isa<llvm::StoreInst>(Val: I) && I.getOperand(i: 0) == &*AI;
253 });
254 assert(ThisStore != EntryBB->end() &&
255 "Store of this should be in entry block?");
256 // Adjust "this", if necessary.
257 Builder.SetInsertPoint(&*ThisStore);
258
259 llvm::Value *AdjustedThisPtr = CGM.getCXXABI().performThisAdjustment(
260 CGF&: *this, This: ThisPtr, UnadjustedClass: ThisValueClass, TI: Thunk);
261 AdjustedThisPtr = Builder.CreateBitCast(V: AdjustedThisPtr,
262 DestTy: ThisStore->getOperand(i: 0)->getType());
263 ThisStore->setOperand(i: 0, Val: AdjustedThisPtr);
264
265 if (!Thunk.Return.isEmpty()) {
266 // Fix up the returned value, if necessary.
267 for (llvm::BasicBlock &BB : *Fn) {
268 llvm::Instruction *T = BB.getTerminator();
269 if (isa<llvm::ReturnInst>(Val: T)) {
270 RValue RV = RValue::get(V: T->getOperand(i: 0));
271 T->eraseFromParent();
272 Builder.SetInsertPoint(&BB);
273 RV = PerformReturnAdjustment(CGF&: *this, ResultType, RV, Thunk);
274 Builder.CreateRet(V: RV.getScalarVal());
275 break;
276 }
277 }
278 }
279
280 return Fn;
281}
282
283void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
284 const CGFunctionInfo &FnInfo,
285 bool IsUnprototyped) {
286 assert(!CurGD.getDecl() && "CurGD was already set!");
287 CurGD = GD;
288 CurFuncIsThunk = true;
289
290 // Build FunctionArgs.
291 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
292 QualType ThisType = MD->getThisType();
293 QualType ResultType;
294 if (IsUnprototyped)
295 ResultType = CGM.getContext().VoidTy;
296 else if (CGM.getCXXABI().HasThisReturn(GD))
297 ResultType = ThisType;
298 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
299 ResultType = CGM.getContext().VoidPtrTy;
300 else
301 ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
302 FunctionArgList FunctionArgs;
303
304 // Create the implicit 'this' parameter declaration.
305 CGM.getCXXABI().buildThisParam(CGF&: *this, Params&: FunctionArgs);
306
307 // Add the rest of the parameters, if we have a prototype to work with.
308 if (!IsUnprototyped) {
309 FunctionArgs.append(in_start: MD->param_begin(), in_end: MD->param_end());
310
311 if (isa<CXXDestructorDecl>(Val: MD))
312 CGM.getCXXABI().addImplicitStructorParams(CGF&: *this, ResTy&: ResultType,
313 Params&: FunctionArgs);
314 }
315
316 // Start defining the function.
317 auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this);
318 StartFunction(GD: GlobalDecl(), RetTy: ResultType, Fn, FnInfo, Args: FunctionArgs,
319 Loc: MD->getLocation());
320 // Create a scope with an artificial location for the body of this function.
321 auto AL = ApplyDebugLocation::CreateArtificial(CGF&: *this);
322
323 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
324 CGM.getCXXABI().EmitInstanceFunctionProlog(CGF&: *this);
325 CXXThisValue = CXXABIThisValue;
326 CurCodeDecl = MD;
327 CurFuncDecl = MD;
328}
329
330void CodeGenFunction::FinishThunk() {
331 // Clear these to restore the invariants expected by
332 // StartFunction/FinishFunction.
333 CurCodeDecl = nullptr;
334 CurFuncDecl = nullptr;
335
336 FinishFunction();
337}
338
339void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
340 const ThunkInfo *Thunk,
341 bool IsUnprototyped) {
342 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
343 "Please use a new CGF for this thunk");
344 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: CurGD.getDecl());
345
346 // Adjust the 'this' pointer if necessary
347 llvm::Value *AdjustedThisPtr;
348 if (Thunk) {
349 const CXXRecordDecl *ThisValueClass =
350 Thunk->ThisType->getPointeeCXXRecordDecl();
351 Address ThisPtr = makeNaturalAddressForPointer(
352 Ptr: LoadCXXThis(), T: Thunk->ThisType->getPointeeType(),
353 Alignment: CGM.getClassPointerAlignment(CD: ThisValueClass), /*ForPointeeType=*/false,
354 /*BaseInfo=*/nullptr, /*TBAAInfo=*/nullptr, IsKnownNonNull: KnownNonNull);
355 AdjustedThisPtr = CGM.getCXXABI().performThisAdjustment(
356 CGF&: *this, This: ThisPtr, UnadjustedClass: ThisValueClass, TI: *Thunk);
357 } else {
358 AdjustedThisPtr = LoadCXXThis();
359 }
360
361 // If perfect forwarding is required a variadic method, a method using
362 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
363 // thunk requires a return adjustment, since that is impossible with musttail.
364 if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
365 if (Thunk && !Thunk->Return.isEmpty()) {
366 if (IsUnprototyped)
367 CGM.ErrorUnsupported(
368 D: MD, Type: "return-adjusting thunk with incomplete parameter type");
369 else if (CurFnInfo->isVariadic())
370 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
371 "thunks for variadic functions");
372 else
373 CGM.ErrorUnsupported(
374 D: MD, Type: "non-trivial argument copy for return-adjusting thunk");
375 }
376 EmitMustTailThunk(GD: CurGD, AdjustedThisPtr, Callee);
377 return;
378 }
379
380 // Start building CallArgs.
381 CallArgList CallArgs;
382 QualType ThisType = MD->getThisType();
383 CallArgs.add(rvalue: RValue::get(V: AdjustedThisPtr), type: ThisType);
384
385 if (isa<CXXDestructorDecl>(Val: MD))
386 CGM.getCXXABI().adjustCallArgsForDestructorThunk(CGF&: *this, GD: CurGD, CallArgs);
387
388#ifndef NDEBUG
389 unsigned PrefixArgs = CallArgs.size() - 1;
390#endif
391 // Add the rest of the arguments.
392 for (const ParmVarDecl *PD : MD->parameters())
393 EmitDelegateCallArg(args&: CallArgs, param: PD, loc: SourceLocation());
394
395 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
396
397#ifndef NDEBUG
398 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
399 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs, MD);
400 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
401 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
402 CallFnInfo.getCallingConvention() ==
403 CurFnInfo->getCallingConvention() &&
404 CallFnInfo.getX86ABIAVXLevel() == CurFnInfo->getX86ABIAVXLevel());
405 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
406 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
407 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
408 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
409 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
410 assert(similar(CallFnInfo.arg_begin()[i].info,
411 CallFnInfo.arg_begin()[i].type,
412 CurFnInfo->arg_begin()[i].info,
413 CurFnInfo->arg_begin()[i].type));
414#endif
415
416 // Determine whether we have a return value slot to use.
417 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD: CurGD)
418 ? ThisType
419 : CGM.getCXXABI().hasMostDerivedReturn(GD: CurGD)
420 ? CGM.getContext().VoidPtrTy
421 : FPT->getReturnType();
422 ReturnValueSlot Slot;
423 if (!ResultType->isVoidType() &&
424 (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
425 hasAggregateEvaluationKind(T: ResultType)))
426 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(),
427 /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
428
429 // Now emit our call.
430 llvm::CallBase *CallOrInvoke;
431 RValue RV = EmitCall(CallInfo: *CurFnInfo, Callee: CGCallee::forDirect(functionPtr: Callee, abstractInfo: CurGD), ReturnValue: Slot,
432 Args: CallArgs, CallOrInvoke: &CallOrInvoke);
433
434 // Consider return adjustment if we have ThunkInfo.
435 if (Thunk && !Thunk->Return.isEmpty())
436 RV = PerformReturnAdjustment(CGF&: *this, ResultType, RV, Thunk: *Thunk);
437 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(Val: CallOrInvoke))
438 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
439
440 // Emit return.
441 if (!ResultType->isVoidType() && Slot.isNull())
442 CGM.getCXXABI().EmitReturnFromThunk(CGF&: *this, RV, ResultType);
443
444 // Disable the final ARC autorelease.
445 AutoreleaseResult = false;
446
447 FinishThunk();
448}
449
450void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
451 llvm::Value *AdjustedThisPtr,
452 llvm::FunctionCallee Callee) {
453 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
454 // to translate AST arguments into LLVM IR arguments. For thunks, we know
455 // that the caller prototype more or less matches the callee prototype with
456 // the exception of 'this'.
457 SmallVector<llvm::Value *, 8> Args(llvm::make_pointer_range(Range: CurFn->args()));
458
459 // Set the adjusted 'this' pointer.
460 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
461 if (ThisAI.isDirect()) {
462 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
463 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
464 llvm::Type *ThisType = Args[ThisArgNo]->getType();
465 if (ThisType != AdjustedThisPtr->getType())
466 AdjustedThisPtr = Builder.CreateBitCast(V: AdjustedThisPtr, DestTy: ThisType);
467 Args[ThisArgNo] = AdjustedThisPtr;
468 } else {
469 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
470 Address ThisAddr = GetAddrOfLocalVar(VD: CXXABIThisDecl);
471 llvm::Type *ThisType = ThisAddr.getElementType();
472 if (ThisType != AdjustedThisPtr->getType())
473 AdjustedThisPtr = Builder.CreateBitCast(V: AdjustedThisPtr, DestTy: ThisType);
474 Builder.CreateStore(Val: AdjustedThisPtr, Addr: ThisAddr);
475 }
476
477 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
478 // don't actually want to run them.
479 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
480 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
481
482 // Apply the standard set of call attributes.
483 unsigned CallingConv;
484 llvm::AttributeList Attrs;
485 CGM.ConstructAttributeList(Name: Callee.getCallee()->getName(), Info: *CurFnInfo, CalleeInfo: GD,
486 Attrs, CallingConv, /*AttrOnCallSite=*/true,
487 /*IsThunk=*/false);
488 Call->setAttributes(Attrs);
489 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
490
491 if (Call->getType()->isVoidTy())
492 Builder.CreateRetVoid();
493 else
494 Builder.CreateRet(V: Call);
495
496 // Finish the function to maintain CodeGenFunction invariants.
497 // FIXME: Don't emit unreachable code.
498 EmitBlock(BB: createBasicBlock());
499
500 FinishThunk();
501}
502
503void CodeGenFunction::generateThunk(llvm::Function *Fn,
504 const CGFunctionInfo &FnInfo, GlobalDecl GD,
505 const ThunkInfo &Thunk,
506 bool IsUnprototyped) {
507 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
508 // Create a scope with an artificial location for the body of this function.
509 auto AL = ApplyDebugLocation::CreateArtificial(CGF&: *this);
510
511 // Get our callee. Use a placeholder type if this method is unprototyped so
512 // that CodeGenModule doesn't try to set attributes.
513 llvm::Type *Ty;
514 if (IsUnprototyped)
515 Ty = llvm::StructType::get(Context&: getLLVMContext());
516 else
517 Ty = CGM.getTypes().GetFunctionType(Info: FnInfo);
518
519 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
520
521 // Make the call and return the result.
522 EmitCallAndReturnForThunk(Callee: llvm::FunctionCallee(Fn->getFunctionType(), Callee),
523 Thunk: &Thunk, IsUnprototyped);
524}
525
526static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
527 bool IsUnprototyped, bool ForVTable) {
528 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
529 // provide thunks for us.
530 if (CGM.getTarget().getCXXABI().isMicrosoft())
531 return true;
532
533 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
534 // definitions of the main method. Therefore, emitting thunks with the vtable
535 // is purely an optimization. Emit the thunk if optimizations are enabled and
536 // all of the parameter types are complete.
537 if (ForVTable)
538 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
539
540 // Always emit thunks along with the method definition.
541 return true;
542}
543
544llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
545 const ThunkInfo &TI,
546 bool ForVTable) {
547 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
548
549 // First, get a declaration. Compute the mangled name. Don't worry about
550 // getting the function prototype right, since we may only need this
551 // declaration to fill in a vtable slot.
552 SmallString<256> Name;
553 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
554 llvm::raw_svector_ostream Out(Name);
555
556 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Val: MD)) {
557 MCtx.mangleCXXDtorThunk(DD, Type: GD.getDtorType(), Thunk: TI,
558 /* elideOverrideInfo */ ElideOverrideInfo: false, Out);
559 } else
560 MCtx.mangleThunk(MD, Thunk: TI, /* elideOverrideInfo */ ElideOverrideInfo: false, Out);
561
562 if (CGM.getContext().useAbbreviatedThunkName(VirtualMethodDecl: GD, MangledName: Name.str())) {
563 Name = "";
564 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Val: MD))
565 MCtx.mangleCXXDtorThunk(DD, Type: GD.getDtorType(), Thunk: TI,
566 /* elideOverrideInfo */ ElideOverrideInfo: true, Out);
567 else
568 MCtx.mangleThunk(MD, Thunk: TI, /* elideOverrideInfo */ ElideOverrideInfo: true, Out);
569 }
570
571 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
572 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, FnTy: ThunkVTableTy, GD);
573
574 // If we don't need to emit a definition, return this declaration as is.
575 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
576 FT: MD->getType()->castAs<FunctionType>());
577 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
578 return Thunk;
579
580 // Arrange a function prototype appropriate for a function definition. In some
581 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
582 const CGFunctionInfo &FnInfo =
583 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
584 : CGM.getTypes().arrangeGlobalDeclaration(GD);
585 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(Info: FnInfo);
586
587 // If the type of the underlying GlobalValue is wrong, we'll have to replace
588 // it. It should be a declaration.
589 llvm::Function *ThunkFn = cast<llvm::Function>(Val: Thunk->stripPointerCasts());
590 if (ThunkFn->getFunctionType() != ThunkFnTy) {
591 llvm::GlobalValue *OldThunkFn = ThunkFn;
592
593 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
594
595 // Remove the name from the old thunk function and get a new thunk.
596 OldThunkFn->setName(StringRef());
597 ThunkFn = llvm::Function::Create(Ty: ThunkFnTy, Linkage: llvm::Function::ExternalLinkage,
598 N: Name.str(), M: &CGM.getModule());
599 CGM.SetLLVMFunctionAttributes(GD: MD, Info: FnInfo, F: ThunkFn, /*IsThunk=*/true);
600
601 if (!OldThunkFn->use_empty()) {
602 OldThunkFn->replaceAllUsesWith(V: ThunkFn);
603 }
604
605 // Remove the old thunk.
606 OldThunkFn->eraseFromParent();
607 }
608
609 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
610 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
611
612 if (!ThunkFn->isDeclaration()) {
613 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
614 // There is already a thunk emitted for this function, do nothing.
615 return ThunkFn;
616 }
617
618 setThunkProperties(CGM, Thunk: TI, ThunkFn, ForVTable, GD);
619 return ThunkFn;
620 }
621
622 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
623 // that the return type is meaningless. These thunks can be used to call
624 // functions with differing return types, and the caller is required to cast
625 // the prototype appropriately to extract the correct value.
626 if (IsUnprototyped)
627 ThunkFn->addFnAttr(Kind: "thunk");
628
629 CGM.SetLLVMFunctionAttributesForDefinition(D: GD.getDecl(), F: ThunkFn);
630
631 // Thunks for variadic methods are special because in general variadic
632 // arguments cannot be perfectly forwarded. In the general case, clang
633 // implements such thunks by cloning the original function body. However, for
634 // thunks with no return adjustment on targets that support musttail, we can
635 // use musttail to perfectly forward the variadic arguments.
636 bool ShouldCloneVarArgs = false;
637 if (!IsUnprototyped && ThunkFn->isVarArg()) {
638 ShouldCloneVarArgs = true;
639 if (TI.Return.isEmpty()) {
640 switch (CGM.getTriple().getArch()) {
641 case llvm::Triple::x86_64:
642 case llvm::Triple::x86:
643 case llvm::Triple::aarch64:
644 ShouldCloneVarArgs = false;
645 break;
646 default:
647 break;
648 }
649 }
650 }
651
652 if (ShouldCloneVarArgs) {
653 if (UseAvailableExternallyLinkage)
654 return ThunkFn;
655 ThunkFn =
656 CodeGenFunction(CGM).GenerateVarArgsThunk(Fn: ThunkFn, FnInfo, GD, Thunk: TI);
657 } else {
658 // Normal thunk body generation.
659 CodeGenFunction(CGM).generateThunk(Fn: ThunkFn, FnInfo, GD, Thunk: TI, IsUnprototyped);
660 }
661
662 setThunkProperties(CGM, Thunk: TI, ThunkFn, ForVTable, GD);
663 return ThunkFn;
664}
665
666void CodeGenVTables::EmitThunks(GlobalDecl GD) {
667 const CXXMethodDecl *MD =
668 cast<CXXMethodDecl>(Val: GD.getDecl())->getCanonicalDecl();
669
670 // We don't need to generate thunks for the base destructor.
671 if (isa<CXXDestructorDecl>(Val: MD) && GD.getDtorType() == Dtor_Base)
672 return;
673
674 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
675 VTContext->getThunkInfo(GD);
676
677 if (!ThunkInfoVector)
678 return;
679
680 for (const ThunkInfo& Thunk : *ThunkInfoVector)
681 maybeEmitThunk(GD, TI: Thunk, /*ForVTable=*/false);
682}
683
684void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
685 llvm::Constant *component,
686 unsigned vtableAddressPoint,
687 bool vtableHasLocalLinkage,
688 bool isCompleteDtor) const {
689 // No need to get the offset of a nullptr.
690 if (component->isNullValue())
691 return builder.add(value: llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 0));
692
693 auto *globalVal =
694 cast<llvm::GlobalValue>(Val: component->stripPointerCastsAndAliases());
695 llvm::Module &module = CGM.getModule();
696
697 // We don't want to copy the linkage of the vtable exactly because we still
698 // want the stub/proxy to be emitted for properly calculating the offset.
699 // Examples where there would be no symbol emitted are available_externally
700 // and private linkages.
701 //
702 // `internal` linkage results in STB_LOCAL Elf binding while still manifesting a
703 // local symbol.
704 //
705 // `linkonce_odr` linkage results in a STB_DEFAULT Elf binding but also allows for
706 // the rtti_proxy to be transparently replaced with a GOTPCREL reloc by a
707 // target that supports this replacement.
708 auto stubLinkage = vtableHasLocalLinkage
709 ? llvm::GlobalValue::InternalLinkage
710 : llvm::GlobalValue::LinkOnceODRLinkage;
711
712 llvm::Constant *target;
713 if (auto *func = dyn_cast<llvm::Function>(Val: globalVal)) {
714 target = llvm::DSOLocalEquivalent::get(GV: func);
715 } else {
716 llvm::SmallString<16> rttiProxyName(globalVal->getName());
717 rttiProxyName.append(RHS: ".rtti_proxy");
718
719 // The RTTI component may not always be emitted in the same linkage unit as
720 // the vtable. As a general case, we can make a dso_local proxy to the RTTI
721 // that points to the actual RTTI struct somewhere. This will result in a
722 // GOTPCREL relocation when taking the relative offset to the proxy.
723 llvm::GlobalVariable *proxy = module.getNamedGlobal(Name: rttiProxyName);
724 if (!proxy) {
725 proxy = new llvm::GlobalVariable(module, globalVal->getType(),
726 /*isConstant=*/true, stubLinkage,
727 globalVal, rttiProxyName);
728 proxy->setDSOLocal(true);
729 proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
730 if (!proxy->hasLocalLinkage()) {
731 proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
732 proxy->setComdat(module.getOrInsertComdat(Name: rttiProxyName));
733 }
734 // Do not instrument the rtti proxies with hwasan to avoid a duplicate
735 // symbol error. Aliases generated by hwasan will retain the same namebut
736 // the addresses they are set to may have different tags from different
737 // compilation units. We don't run into this without hwasan because the
738 // proxies are in comdat groups, but those aren't propagated to the alias.
739 RemoveHwasanMetadata(GV: proxy);
740 }
741 target = proxy;
742 }
743
744 builder.addRelativeOffsetToPosition(type: CGM.Int32Ty, target,
745 /*position=*/vtableAddressPoint);
746}
747
748llvm::Type *CodeGenModule::getVTableComponentType() const {
749 if (getLangOpts().RelativeCXXABIVTables)
750 return Int32Ty;
751 return GlobalsInt8PtrTy;
752}
753
754llvm::Type *CodeGenVTables::getVTableComponentType() const {
755 return CGM.getVTableComponentType();
756}
757
758static void AddPointerLayoutOffset(const CodeGenModule &CGM,
759 ConstantArrayBuilder &builder,
760 CharUnits offset) {
761 builder.add(value: llvm::ConstantExpr::getIntToPtr(
762 C: llvm::ConstantInt::getSigned(Ty: CGM.PtrDiffTy, V: offset.getQuantity()),
763 Ty: CGM.GlobalsInt8PtrTy));
764}
765
766static void AddRelativeLayoutOffset(const CodeGenModule &CGM,
767 ConstantArrayBuilder &builder,
768 CharUnits offset) {
769 builder.add(value: llvm::ConstantInt::getSigned(Ty: CGM.Int32Ty, V: offset.getQuantity()));
770}
771
772void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
773 const VTableLayout &layout,
774 unsigned componentIndex,
775 llvm::Constant *rtti,
776 unsigned &nextVTableThunkIndex,
777 unsigned vtableAddressPoint,
778 bool vtableHasLocalLinkage) {
779 auto &component = layout.vtable_components()[componentIndex];
780
781 bool RelativeCXXABIVTables = CGM.getLangOpts().RelativeCXXABIVTables;
782 auto addOffsetConstant =
783 RelativeCXXABIVTables ? AddRelativeLayoutOffset : AddPointerLayoutOffset;
784
785 switch (component.getKind()) {
786 case VTableComponent::CK_VCallOffset:
787 return addOffsetConstant(CGM, builder, component.getVCallOffset());
788
789 case VTableComponent::CK_VBaseOffset:
790 return addOffsetConstant(CGM, builder, component.getVBaseOffset());
791
792 case VTableComponent::CK_OffsetToTop:
793 return addOffsetConstant(CGM, builder, component.getOffsetToTop());
794
795 case VTableComponent::CK_RTTI:
796 if (RelativeCXXABIVTables)
797 return addRelativeComponent(builder, component: rtti, vtableAddressPoint,
798 vtableHasLocalLinkage,
799 /*isCompleteDtor=*/false);
800 else
801 return builder.add(value: rtti);
802
803 case VTableComponent::CK_FunctionPointer:
804 case VTableComponent::CK_CompleteDtorPointer:
805 case VTableComponent::CK_DeletingDtorPointer: {
806 GlobalDecl GD = component.getGlobalDecl(
807 HasVectorDeletingDtors: CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
808 CGM.getContext().getLangOpts()));
809
810 const bool IsThunk =
811 nextVTableThunkIndex < layout.vtable_thunks().size() &&
812 layout.vtable_thunks()[nextVTableThunkIndex].first == componentIndex;
813
814 if (CGM.getLangOpts().CUDA) {
815 // Emit NULL for methods we can't codegen on this
816 // side. Otherwise we'd end up with vtable with unresolved
817 // references.
818 const CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: GD.getDecl());
819 // OK on device side: functions w/ __device__ attribute
820 // OK on host side: anything except __device__-only functions.
821 bool CanEmitMethod =
822 CGM.getLangOpts().CUDAIsDevice
823 ? MD->hasAttr<CUDADeviceAttr>()
824 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
825 if (!CanEmitMethod) {
826 if (IsThunk)
827 nextVTableThunkIndex++;
828 return builder.add(
829 value: llvm::ConstantExpr::getNullValue(Ty: CGM.GlobalsInt8PtrTy));
830 }
831 // Method is acceptable, continue processing as usual.
832 }
833
834 auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
835 llvm::FunctionType *fnTy =
836 llvm::FunctionType::get(Result: CGM.VoidTy, /*isVarArg=*/false);
837 auto *F = cast<llvm::Function>(
838 Val: CGM.CreateRuntimeFunction(Ty: fnTy, Name: name).getCallee());
839 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
840
841 // The Microsoft ABI uses the same function name for pure and deleted
842 // virtual functions.
843 if (!F->empty())
844 return F;
845
846 // For device compilation, provide a weak definition that
847 // traps, otherwise linking ends up with unresolved references.
848 if (CGM.getLangOpts().isTargetDevice()) {
849 F->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
850 CodeGenFunction CGF(CGM);
851 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
852 CGF.StartFunction(GD: GlobalDecl(), RetTy: CGM.getContext().VoidTy, Fn: F, FnInfo: FI,
853 Args: FunctionArgList{});
854 CGF.EmitTrapCallAndMakeUnreachable();
855 CGF.FinishFunction();
856 }
857
858 return F;
859 };
860
861 llvm::Constant *fnPtr;
862
863 // Pure virtual member functions.
864 if (cast<CXXMethodDecl>(Val: GD.getDecl())->isPureVirtual()) {
865 if (!PureVirtualFn)
866 PureVirtualFn =
867 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
868 fnPtr = PureVirtualFn;
869
870 // Deleted virtual member functions.
871 } else if (cast<CXXMethodDecl>(Val: GD.getDecl())->isDeleted()) {
872 if (!DeletedVirtualFn)
873 DeletedVirtualFn =
874 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
875 fnPtr = DeletedVirtualFn;
876
877 // Thunks.
878 } else if (IsThunk) {
879 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
880
881 nextVTableThunkIndex++;
882 fnPtr = maybeEmitThunk(GD, TI: thunkInfo, /*ForVTable=*/true);
883 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {
884 assert(thunkInfo.Method && "Method not set");
885 GD = GD.getWithDecl(D: thunkInfo.Method);
886 }
887
888 // Otherwise we can use the method definition directly.
889 } else {
890 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
891 fnPtr = CGM.GetAddrOfFunction(GD, Ty: fnTy, /*ForVTable=*/true);
892 if (CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
893 GD = getItaniumVTableContext().findOriginalMethod(GD);
894 }
895
896 if (RelativeCXXABIVTables) {
897 return addRelativeComponent(
898 builder, component: fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
899 isCompleteDtor: component.getKind() == VTableComponent::CK_CompleteDtorPointer);
900 } else {
901 // TODO: this icky and only exists due to functions being in the generic
902 // address space, rather than the global one, even though they are
903 // globals; fixing said issue might be intrusive, and will be done
904 // later.
905 unsigned FnAS = fnPtr->getType()->getPointerAddressSpace();
906 unsigned GVAS = CGM.GlobalsInt8PtrTy->getPointerAddressSpace();
907
908 if (FnAS != GVAS)
909 fnPtr =
910 llvm::ConstantExpr::getAddrSpaceCast(C: fnPtr, Ty: CGM.GlobalsInt8PtrTy);
911 if (const auto &Schema =
912 CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers)
913 return builder.addSignedPointer(Pointer: fnPtr, Schema, CalleeDecl: GD, CalleeType: QualType());
914 return builder.add(value: fnPtr);
915 }
916 }
917
918 case VTableComponent::CK_UnusedFunctionPointer:
919 if (RelativeCXXABIVTables)
920 return builder.add(value: llvm::ConstantExpr::getNullValue(Ty: CGM.Int32Ty));
921 else
922 return builder.addNullPointer(ptrTy: CGM.GlobalsInt8PtrTy);
923 }
924
925 llvm_unreachable("Unexpected vtable component kind");
926}
927
928llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
929 SmallVector<llvm::Type *, 4> tys;
930 llvm::Type *componentType = getVTableComponentType();
931 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
932 tys.push_back(Elt: llvm::ArrayType::get(ElementType: componentType, NumElements: layout.getVTableSize(i)));
933
934 return llvm::StructType::get(Context&: CGM.getLLVMContext(), Elements: tys);
935}
936
937void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
938 const VTableLayout &layout,
939 llvm::Constant *rtti,
940 bool vtableHasLocalLinkage) {
941 llvm::Type *componentType = getVTableComponentType();
942
943 const auto &addressPoints = layout.getAddressPointIndices();
944 unsigned nextVTableThunkIndex = 0;
945 for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
946 vtableIndex != endIndex; ++vtableIndex) {
947 auto vtableElem = builder.beginArray(eltTy: componentType);
948
949 size_t vtableStart = layout.getVTableOffset(i: vtableIndex);
950 size_t vtableEnd = vtableStart + layout.getVTableSize(i: vtableIndex);
951 for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
952 ++componentIndex) {
953 addVTableComponent(builder&: vtableElem, layout, componentIndex, rtti,
954 nextVTableThunkIndex, vtableAddressPoint: addressPoints[vtableIndex],
955 vtableHasLocalLinkage);
956 }
957 vtableElem.finishAndAddTo(parent&: builder);
958 }
959}
960
961llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable(
962 const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
963 llvm::GlobalVariable::LinkageTypes Linkage,
964 VTableAddressPointsMapTy &AddressPoints) {
965 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
966 DI->completeClassData(RD: Base.getBase());
967
968 std::unique_ptr<VTableLayout> VTLayout(
969 getItaniumVTableContext().createConstructionVTableLayout(
970 MostDerivedClass: Base.getBase(), MostDerivedClassOffset: Base.getBaseOffset(), MostDerivedClassIsVirtual: BaseIsVirtual, LayoutClass: RD));
971
972 // Add the address points.
973 AddressPoints = VTLayout->getAddressPoints();
974
975 // Get the mangled construction vtable name.
976 SmallString<256> OutName;
977 llvm::raw_svector_ostream Out(OutName);
978 cast<ItaniumMangleContext>(Val&: CGM.getCXXABI().getMangleContext())
979 .mangleCXXCtorVTable(RD, Offset: Base.getBaseOffset().getQuantity(),
980 Type: Base.getBase(), Out);
981 SmallString<256> Name(OutName);
982
983 bool UsingRelativeLayout = CGM.getLangOpts().RelativeCXXABIVTables;
984 bool VTableAliasExists =
985 UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
986 if (VTableAliasExists) {
987 // We previously made the vtable hidden and changed its name.
988 Name.append(RHS: ".local");
989 }
990
991 llvm::Type *VTType = getVTableType(layout: *VTLayout);
992
993 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
994 // guarantee that they actually will be available externally. Instead, when
995 // emitting an available_externally VTT, we provide references to an internal
996 // linkage construction vtable. The ABI only requires complete-object vtables
997 // to be the same for all instances of a type, not construction vtables.
998 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
999 Linkage = llvm::GlobalVariable::InternalLinkage;
1000
1001 llvm::Align Align = CGM.getDataLayout().getABITypeAlign(Ty: VTType);
1002
1003 // Create the variable that will hold the construction vtable.
1004 llvm::GlobalVariable *VTable =
1005 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Ty: VTType, Linkage, Alignment: Align);
1006
1007 // dynamic_cast assumes the vtable address is unique; see
1008 // https://github.com/llvm/llvm-project/pull/200108. The address is
1009 // insignificant either when no RTTI is emitted or for a weak vtable on a
1010 // target that may duplicate vtables. In those cases the vtable can be marked
1011 // unnamed_addr.
1012 if (!CGM.shouldEmitRTTI() || CGM.mayVTableBeDuplicated(Linkage: VTable->getLinkage()))
1013 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1014
1015 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
1016 Ty: CGM.getContext().getCanonicalTagType(TD: Base.getBase()));
1017
1018 // Create and set the initializer.
1019 ConstantInitBuilder builder(CGM);
1020 auto components = builder.beginStruct();
1021 createVTableInitializer(builder&: components, layout: *VTLayout, rtti: RTTI,
1022 vtableHasLocalLinkage: VTable->hasLocalLinkage());
1023 components.finishAndSetAsInitializer(global: VTable);
1024
1025 // Set properties only after the initializer has been set to ensure that the
1026 // GV is treated as definition and not declaration.
1027 assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
1028 CGM.setGVProperties(GV: VTable, D: RD);
1029
1030 CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout: *VTLayout);
1031
1032 if (UsingRelativeLayout) {
1033 RemoveHwasanMetadata(GV: VTable);
1034 if (!VTable->isDSOLocal())
1035 GenerateRelativeVTableAlias(VTable, AliasNameRef: OutName);
1036 }
1037
1038 return VTable;
1039}
1040
1041// Ensure this vtable is not instrumented by hwasan. That is, a global alias is
1042// not generated for it. This is mainly used by the relative-vtables ABI where
1043// vtables instead contain 32-bit offsets between the vtable and function
1044// pointers. Hwasan is disabled for these vtables for now because the tag in a
1045// vtable pointer may fail the overflow check when resolving 32-bit PLT
1046// relocations. A future alternative for this would be finding which usages of
1047// the vtable can continue to use the untagged hwasan value without any loss of
1048// value in hwasan.
1049void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *GV) const {
1050 if (CGM.getLangOpts().Sanitize.has(K: SanitizerKind::HWAddress)) {
1051 llvm::GlobalValue::SanitizerMetadata Meta;
1052 if (GV->hasSanitizerMetadata())
1053 Meta = GV->getSanitizerMetadata();
1054 Meta.NoHWAddress = true;
1055 GV->setSanitizerMetadata(Meta);
1056 }
1057}
1058
1059// If the VTable is not dso_local, then we will not be able to indicate that
1060// the VTable does not need a relocation and move into rodata. A frequent
1061// time this can occur is for classes that should be made public from a DSO
1062// (like in libc++). For cases like these, we can make the vtable hidden or
1063// internal and create a public alias with the same visibility and linkage as
1064// the original vtable type.
1065void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
1066 llvm::StringRef AliasNameRef) {
1067 assert(CGM.getLangOpts().RelativeCXXABIVTables &&
1068 "Can only use this if the relative vtable ABI is used");
1069 assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
1070 "not guaranteed to be dso_local");
1071
1072 // If the vtable is available_externally, we shouldn't (or need to) generate
1073 // an alias for it in the first place since the vtable won't actually by
1074 // emitted in this compilation unit.
1075 if (VTable->hasAvailableExternallyLinkage())
1076 return;
1077
1078 // Create a new string in the event the alias is already the name of the
1079 // vtable. Using the reference directly could lead to use of an inititialized
1080 // value in the module's StringMap.
1081 llvm::SmallString<256> AliasName(AliasNameRef);
1082 VTable->setName(AliasName + ".local");
1083
1084 auto Linkage = VTable->getLinkage();
1085 assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
1086 "Invalid vtable alias linkage");
1087
1088 llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(Name: AliasName);
1089 if (!VTableAlias) {
1090 VTableAlias = llvm::GlobalAlias::create(Ty: VTable->getValueType(),
1091 AddressSpace: VTable->getAddressSpace(), Linkage,
1092 Name: AliasName, Parent: &CGM.getModule());
1093 } else {
1094 assert(VTableAlias->getValueType() == VTable->getValueType());
1095 assert(VTableAlias->getLinkage() == Linkage);
1096 }
1097 VTableAlias->setVisibility(VTable->getVisibility());
1098 VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
1099
1100 // Both of these will now imply dso_local for the vtable.
1101 if (!VTable->hasComdat()) {
1102 VTable->setLinkage(llvm::GlobalValue::InternalLinkage);
1103 } else {
1104 // If a relocation targets an internal linkage symbol, MC will generate the
1105 // relocation against the symbol's section instead of the symbol itself
1106 // (see ELFObjectWriter::shouldRelocateWithSymbol). If an internal symbol is
1107 // in a COMDAT section group, that section might be discarded, and then the
1108 // relocation to that section will generate a linker error. We therefore
1109 // make COMDAT vtables hidden instead of internal: they'll still not be
1110 // public, but relocations will reference the symbol instead of the section
1111 // and COMDAT deduplication will thus work as expected.
1112 VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1113 }
1114
1115 VTableAlias->setAliasee(VTable);
1116}
1117
1118static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
1119 const CXXRecordDecl *RD) {
1120 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1121 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
1122}
1123
1124/// Compute the required linkage of the vtable for the given class.
1125///
1126/// Note that we only call this at the end of the translation unit.
1127llvm::GlobalVariable::LinkageTypes
1128CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1129 if (!RD->isExternallyVisible())
1130 return llvm::GlobalVariable::InternalLinkage;
1131
1132 // In windows, the linkage of vtable is not related to modules.
1133 bool IsInNamedModule = !getTarget().getCXXABI().isMicrosoft() &&
1134 RD->isInNamedModule();
1135 // If the CXXRecordDecl is not in a module unit, we need to get
1136 // its key function. We're at the end of the translation unit, so the current
1137 // key function is fully correct.
1138 const CXXMethodDecl *keyFunction =
1139 IsInNamedModule ? nullptr : Context.getCurrentKeyFunction(RD);
1140 if (IsInNamedModule || (keyFunction && !RD->hasAttr<DLLImportAttr>())) {
1141 // If this class has a key function, use that to determine the
1142 // linkage of the vtable.
1143 const FunctionDecl *def = nullptr;
1144 if (keyFunction && keyFunction->hasBody(Definition&: def))
1145 keyFunction = cast<CXXMethodDecl>(Val: def);
1146
1147 bool IsExternalDefinition =
1148 IsInNamedModule ? RD->shouldEmitInExternalSource() : !def;
1149
1150 TemplateSpecializationKind Kind =
1151 IsInNamedModule ? RD->getTemplateSpecializationKind()
1152 : keyFunction->getTemplateSpecializationKind();
1153
1154 switch (Kind) {
1155 case TSK_Undeclared:
1156 case TSK_ExplicitSpecialization:
1157 // Under OpenMP offloading we force-emit vtable definitions for classes
1158 // mapped into target regions even when the key function is defined in
1159 // another TU, so the linkage may legitimately be queried here.
1160 assert(
1161 (IsInNamedModule || def || CodeGenOpts.OptimizationLevel > 0 ||
1162 CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
1163 getLangOpts().OpenMP) &&
1164 "Shouldn't query vtable linkage without the class in module units, "
1165 "key function, optimizations, or debug info");
1166 if (IsExternalDefinition && CodeGenOpts.OptimizationLevel > 0)
1167 return llvm::GlobalVariable::AvailableExternallyLinkage;
1168
1169 if (keyFunction && keyFunction->isInlined())
1170 return !Context.getLangOpts().AppleKext
1171 ? llvm::GlobalVariable::LinkOnceODRLinkage
1172 : llvm::Function::InternalLinkage;
1173
1174 return llvm::GlobalVariable::ExternalLinkage;
1175
1176 case TSK_ImplicitInstantiation:
1177 return !Context.getLangOpts().AppleKext ?
1178 llvm::GlobalVariable::LinkOnceODRLinkage :
1179 llvm::Function::InternalLinkage;
1180
1181 case TSK_ExplicitInstantiationDefinition:
1182 return !Context.getLangOpts().AppleKext ?
1183 llvm::GlobalVariable::WeakODRLinkage :
1184 llvm::Function::InternalLinkage;
1185
1186 case TSK_ExplicitInstantiationDeclaration:
1187 return IsExternalDefinition
1188 ? llvm::GlobalVariable::AvailableExternallyLinkage
1189 : llvm::GlobalVariable::ExternalLinkage;
1190 }
1191 }
1192
1193 // -fapple-kext mode does not support weak linkage, so we must use
1194 // internal linkage.
1195 if (Context.getLangOpts().AppleKext)
1196 return llvm::Function::InternalLinkage;
1197
1198 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1199 llvm::GlobalValue::LinkOnceODRLinkage;
1200 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1201 llvm::GlobalValue::WeakODRLinkage;
1202 if (RD->hasAttr<DLLExportAttr>()) {
1203 // Cannot discard exported vtables.
1204 DiscardableODRLinkage = NonDiscardableODRLinkage;
1205 } else if (RD->hasAttr<DLLImportAttr>()) {
1206 // Imported vtables are available externally.
1207 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1208 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1209 }
1210
1211 switch (RD->getTemplateSpecializationKind()) {
1212 case TSK_Undeclared:
1213 case TSK_ExplicitSpecialization:
1214 case TSK_ImplicitInstantiation:
1215 return DiscardableODRLinkage;
1216
1217 case TSK_ExplicitInstantiationDeclaration:
1218 // Explicit instantiations in MSVC do not provide vtables, so we must emit
1219 // our own.
1220 if (getTarget().getCXXABI().isMicrosoft())
1221 return DiscardableODRLinkage;
1222 return shouldEmitAvailableExternallyVTable(CGM: *this, RD)
1223 ? llvm::GlobalVariable::AvailableExternallyLinkage
1224 : llvm::GlobalVariable::ExternalLinkage;
1225
1226 case TSK_ExplicitInstantiationDefinition:
1227 return NonDiscardableODRLinkage;
1228 }
1229
1230 llvm_unreachable("Invalid TemplateSpecializationKind!");
1231}
1232
1233bool CodeGenModule::mayVTableBeDuplicated(
1234 llvm::GlobalValue::LinkageTypes Linkage) const {
1235 return getTarget().getVTableUniqueness() ==
1236 VTableUniquenessKind::UniqueIfStrongLinkage &&
1237 llvm::GlobalValue::isWeakForLinker(Linkage);
1238}
1239
1240/// This is a callback from Sema to tell us that a particular vtable is
1241/// required to be emitted in this translation unit.
1242///
1243/// This is only called for vtables that _must_ be emitted (mainly due to key
1244/// functions). For weak vtables, CodeGen tracks when they are needed and
1245/// emits them as-needed.
1246void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
1247 VTables.GenerateClassData(RD: theClass);
1248 EmittedVTables.insert(Ptr: theClass);
1249}
1250
1251void
1252CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
1253 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1254 DI->completeClassData(RD);
1255
1256 if (RD->getNumVBases())
1257 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1258
1259 CGM.getCXXABI().emitVTableDefinitions(CGVT&: *this, RD);
1260}
1261
1262/// At this point in the translation unit, does it appear that can we
1263/// rely on the vtable being defined elsewhere in the program?
1264///
1265/// The response is really only definitive when called at the end of
1266/// the translation unit.
1267///
1268/// The only semantic restriction here is that the object file should
1269/// not contain a vtable definition when that vtable is defined
1270/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
1271/// vtables when unnecessary.
1272bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
1273 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
1274
1275 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1276 // emit them even if there is an explicit template instantiation.
1277 if (CGM.getTarget().getCXXABI().isMicrosoft())
1278 return false;
1279
1280 // If we have an explicit instantiation declaration (and not a
1281 // definition), the vtable is defined elsewhere.
1282 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1283 if (TSK == TSK_ExplicitInstantiationDeclaration)
1284 return true;
1285
1286 // Otherwise, if the class is an instantiated template, the
1287 // vtable must be defined here.
1288 if (TSK == TSK_ImplicitInstantiation ||
1289 TSK == TSK_ExplicitInstantiationDefinition)
1290 return false;
1291
1292 // Otherwise, if the class is attached to a module, the tables are uniquely
1293 // emitted in the object for the module unit in which it is defined.
1294 if (RD->isInNamedModule())
1295 return RD->shouldEmitInExternalSource();
1296
1297 // Otherwise, if the class doesn't have a key function (possibly
1298 // anymore), the vtable must be defined here.
1299 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1300 if (!keyFunction)
1301 return false;
1302
1303 // Otherwise, if we don't have a definition of the key function, the
1304 // vtable must be defined somewhere else.
1305 return !keyFunction->hasBody();
1306}
1307
1308/// Given that we're currently at the end of the translation unit, and
1309/// we've emitted a reference to the vtable for this class, should
1310/// we define that vtable?
1311static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
1312 const CXXRecordDecl *RD) {
1313 // If vtable is internal then it has to be done.
1314 if (!CGM.getVTables().isVTableExternal(RD))
1315 return true;
1316
1317 // If it's external then maybe we will need it as available_externally.
1318 return shouldEmitAvailableExternallyVTable(CGM, RD);
1319}
1320
1321/// Given that at some point we emitted a reference to one or more
1322/// vtables, and that we are now at the end of the translation unit,
1323/// decide whether we should emit them.
1324void CodeGenModule::EmitDeferredVTables() {
1325#ifndef NDEBUG
1326 // Remember the size of DeferredVTables, because we're going to assume
1327 // that this entire operation doesn't modify it.
1328 size_t savedSize = DeferredVTables.size();
1329#endif
1330
1331 for (const CXXRecordDecl *RD : DeferredVTables) {
1332 // if a table has been emitted in an earlier PTU, but was also marked
1333 // deferred, we should skip if the linkage is external
1334 if (EmittedVTables.count(Ptr: RD) &&
1335 getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1336 continue;
1337
1338 if (shouldEmitVTableAtEndOfTranslationUnit(CGM&: *this, RD))
1339 VTables.GenerateClassData(RD);
1340 else if (shouldOpportunisticallyEmitVTables())
1341 OpportunisticVTables.push_back(x: RD);
1342 }
1343
1344 assert(savedSize == DeferredVTables.size() &&
1345 "deferred extra vtables during vtable emission?");
1346 DeferredVTables.clear();
1347}
1348
1349bool CodeGenModule::AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD) {
1350 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>() ||
1351 RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1352 return true;
1353
1354 if (!getCodeGenOpts().LTOVisibilityPublicStd)
1355 return false;
1356
1357 const DeclContext *DC = RD;
1358 while (true) {
1359 auto *D = cast<Decl>(Val: DC);
1360 DC = DC->getParent();
1361 if (isa<TranslationUnitDecl>(Val: DC->getRedeclContext())) {
1362 if (auto *ND = dyn_cast<NamespaceDecl>(Val: D))
1363 if (const IdentifierInfo *II = ND->getIdentifier())
1364 if (II->isStr(Str: "std") || II->isStr(Str: "stdext"))
1365 return true;
1366 break;
1367 }
1368 }
1369
1370 return false;
1371}
1372
1373bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1374 LinkageInfo LV = RD->getLinkageAndVisibility();
1375 if (!isExternallyVisible(L: LV.getLinkage()))
1376 return true;
1377
1378 if (!getTriple().isOSBinFormatCOFF() &&
1379 LV.getVisibility() != HiddenVisibility)
1380 return false;
1381
1382 return !AlwaysHasLTOVisibilityPublic(RD);
1383}
1384
1385llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
1386 const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1387 // If we have already visited this RD (which means this is a recursive call
1388 // since the initial call should have an empty Visited set), return the max
1389 // visibility. The recursive calls below compute the min between the result
1390 // of the recursive call and the current TypeVis, so returning the max here
1391 // ensures that it will have no effect on the current TypeVis.
1392 if (!Visited.insert(V: RD).second)
1393 return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1394
1395 LinkageInfo LV = RD->getLinkageAndVisibility();
1396 llvm::GlobalObject::VCallVisibility TypeVis;
1397 if (!isExternallyVisible(L: LV.getLinkage()))
1398 TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1399 else if (HasHiddenLTOVisibility(RD))
1400 TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1401 else
1402 TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1403
1404 for (const auto &B : RD->bases())
1405 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1406 TypeVis = std::min(
1407 a: TypeVis,
1408 b: GetVCallVisibilityLevel(RD: B.getType()->getAsCXXRecordDecl(), Visited));
1409
1410 for (const auto &B : RD->vbases())
1411 if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1412 TypeVis = std::min(
1413 a: TypeVis,
1414 b: GetVCallVisibilityLevel(RD: B.getType()->getAsCXXRecordDecl(), Visited));
1415
1416 return TypeVis;
1417}
1418
1419void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1420 llvm::GlobalVariable *VTable,
1421 const VTableLayout &VTLayout) {
1422 // Emit type metadata on vtables with LTO or IR instrumentation or
1423 // speculative devirtualization.
1424 // In IR instrumentation, the type metadata is used to find out vtable
1425 // definitions (for type profiling) among all global variables.
1426 if (!getCodeGenOpts().LTOUnit && !getCodeGenOpts().hasProfileIRInstr() &&
1427 !getCodeGenOpts().DevirtualizeSpeculatively)
1428 return;
1429
1430 CharUnits ComponentWidth = GetTargetTypeStoreSize(Ty: getVTableComponentType());
1431
1432 struct AddressPoint {
1433 const CXXRecordDecl *Base;
1434 size_t Offset;
1435 std::string TypeName;
1436 bool operator<(const AddressPoint &RHS) const {
1437 int D = TypeName.compare(str: RHS.TypeName);
1438 return D < 0 || (D == 0 && Offset < RHS.Offset);
1439 }
1440 };
1441 std::vector<AddressPoint> AddressPoints;
1442 for (auto &&AP : VTLayout.getAddressPoints()) {
1443 AddressPoint N{.Base: AP.first.getBase(),
1444 .Offset: VTLayout.getVTableOffset(i: AP.second.VTableIndex) +
1445 AP.second.AddressPointIndex,
1446 .TypeName: {}};
1447 llvm::raw_string_ostream Stream(N.TypeName);
1448 CanQualType T = getContext().getCanonicalTagType(TD: N.Base);
1449 getCXXABI().getMangleContext().mangleCanonicalTypeName(T, Stream);
1450 AddressPoints.push_back(x: std::move(N));
1451 }
1452
1453 // Sort the address points for determinism.
1454 llvm::sort(C&: AddressPoints);
1455
1456 ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1457 for (auto AP : AddressPoints) {
1458 // Create type metadata for the address point.
1459 AddVTableTypeMetadata(VTable, Offset: ComponentWidth * AP.Offset, RD: AP.Base);
1460
1461 // The class associated with each address point could also potentially be
1462 // used for indirect calls via a member function pointer, so we need to
1463 // annotate the address of each function pointer with the appropriate member
1464 // function pointer type.
1465 for (unsigned I = 0; I != Comps.size(); ++I) {
1466 if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1467 continue;
1468 llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1469 T: Context.getMemberPointerType(T: Comps[I].getFunctionDecl()->getType(),
1470 /*Qualifier=*/std::nullopt, Cls: AP.Base));
1471 VTable->addTypeMetadata(Offset: (ComponentWidth * I).getQuantity(), TypeID: MD);
1472 }
1473 }
1474
1475 if (getCodeGenOpts().VirtualFunctionElimination ||
1476 getCodeGenOpts().WholeProgramVTables) {
1477 llvm::DenseSet<const CXXRecordDecl *> Visited;
1478 llvm::GlobalObject::VCallVisibility TypeVis =
1479 GetVCallVisibilityLevel(RD, Visited);
1480 if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1481 VTable->setVCallVisibilityMetadata(TypeVis);
1482 }
1483}
1484