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