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