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