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