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