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