CGVTables.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. #include "CGCXXABI.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/RecordLayout.h"
  17. #include "clang/Basic/CodeGenOptions.h"
  18. #include "clang/CodeGen/CGFunctionInfo.h"
  19. #include "clang/CodeGen/ConstantInitBuilder.h"
  20. #include "llvm/IR/IntrinsicInst.h"
  21. #include "llvm/Support/Format.h"
  22. #include "llvm/Transforms/Utils/Cloning.h"
  23. #include <algorithm>
  24. #include <cstdio>
  25. using namespace clang;
  26. using namespace CodeGen;
  27. CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
  28. : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
  29. llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
  30. GlobalDecl GD) {
  31. return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
  32. /*DontDefer=*/true, /*IsThunk=*/true);
  33. }
  34. static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
  35. llvm::Function *ThunkFn, bool ForVTable,
  36. GlobalDecl GD) {
  37. CGM.setFunctionLinkage(GD, ThunkFn);
  38. CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
  39. !Thunk.Return.isEmpty());
  40. // Set the right visibility.
  41. CGM.setGVProperties(ThunkFn, GD);
  42. if (!CGM.getCXXABI().exportThunk()) {
  43. ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  44. ThunkFn->setDSOLocal(true);
  45. }
  46. if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
  47. ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
  48. }
  49. #ifndef NDEBUG
  50. static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
  51. const ABIArgInfo &infoR, CanQualType typeR) {
  52. return (infoL.getKind() == infoR.getKind() &&
  53. (typeL == typeR ||
  54. (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
  55. (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
  56. }
  57. #endif
  58. static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
  59. QualType ResultType, RValue RV,
  60. const ThunkInfo &Thunk) {
  61. // Emit the return adjustment.
  62. bool NullCheckValue = !ResultType->isReferenceType();
  63. llvm::BasicBlock *AdjustNull = nullptr;
  64. llvm::BasicBlock *AdjustNotNull = nullptr;
  65. llvm::BasicBlock *AdjustEnd = nullptr;
  66. llvm::Value *ReturnValue = RV.getScalarVal();
  67. if (NullCheckValue) {
  68. AdjustNull = CGF.createBasicBlock("adjust.null");
  69. AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
  70. AdjustEnd = CGF.createBasicBlock("adjust.end");
  71. llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
  72. CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
  73. CGF.EmitBlock(AdjustNotNull);
  74. }
  75. auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
  76. auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
  77. ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
  78. Address(ReturnValue, ClassAlign),
  79. Thunk.Return);
  80. if (NullCheckValue) {
  81. CGF.Builder.CreateBr(AdjustEnd);
  82. CGF.EmitBlock(AdjustNull);
  83. CGF.Builder.CreateBr(AdjustEnd);
  84. CGF.EmitBlock(AdjustEnd);
  85. llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
  86. PHI->addIncoming(ReturnValue, AdjustNotNull);
  87. PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
  88. AdjustNull);
  89. ReturnValue = PHI;
  90. }
  91. return RValue::get(ReturnValue);
  92. }
  93. /// This function clones a function's DISubprogram node and enters it into
  94. /// a value map with the intent that the map can be utilized by the cloner
  95. /// to short-circuit Metadata node mapping.
  96. /// Furthermore, the function resolves any DILocalVariable nodes referenced
  97. /// by dbg.value intrinsics so they can be properly mapped during cloning.
  98. static void resolveTopLevelMetadata(llvm::Function *Fn,
  99. llvm::ValueToValueMapTy &VMap) {
  100. // Clone the DISubprogram node and put it into the Value map.
  101. auto *DIS = Fn->getSubprogram();
  102. if (!DIS)
  103. return;
  104. auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
  105. VMap.MD()[DIS].reset(NewDIS);
  106. // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
  107. // they are referencing.
  108. for (auto &BB : Fn->getBasicBlockList()) {
  109. for (auto &I : BB) {
  110. if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
  111. auto *DILocal = DII->getVariable();
  112. if (!DILocal->isResolved())
  113. DILocal->resolve();
  114. }
  115. }
  116. }
  117. }
  118. // This function does roughly the same thing as GenerateThunk, but in a
  119. // very different way, so that va_start and va_end work correctly.
  120. // FIXME: This function assumes "this" is the first non-sret LLVM argument of
  121. // a function, and that there is an alloca built in the entry block
  122. // for all accesses to "this".
  123. // FIXME: This function assumes there is only one "ret" statement per function.
  124. // FIXME: Cloning isn't correct in the presence of indirect goto!
  125. // FIXME: This implementation of thunks bloats codesize by duplicating the
  126. // function definition. There are alternatives:
  127. // 1. Add some sort of stub support to LLVM for cases where we can
  128. // do a this adjustment, then a sibcall.
  129. // 2. We could transform the definition to take a va_list instead of an
  130. // actual variable argument list, then have the thunks (including a
  131. // no-op thunk for the regular definition) call va_start/va_end.
  132. // There's a bit of per-call overhead for this solution, but it's
  133. // better for codesize if the definition is long.
  134. llvm::Function *
  135. CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
  136. const CGFunctionInfo &FnInfo,
  137. GlobalDecl GD, const ThunkInfo &Thunk) {
  138. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  139. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  140. QualType ResultType = FPT->getReturnType();
  141. // Get the original function
  142. assert(FnInfo.isVariadic());
  143. llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
  144. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  145. llvm::Function *BaseFn = cast<llvm::Function>(Callee);
  146. // Clone to thunk.
  147. llvm::ValueToValueMapTy VMap;
  148. // We are cloning a function while some Metadata nodes are still unresolved.
  149. // Ensure that the value mapper does not encounter any of them.
  150. resolveTopLevelMetadata(BaseFn, VMap);
  151. llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
  152. Fn->replaceAllUsesWith(NewFn);
  153. NewFn->takeName(Fn);
  154. Fn->eraseFromParent();
  155. Fn = NewFn;
  156. // "Initialize" CGF (minimally).
  157. CurFn = Fn;
  158. // Get the "this" value
  159. llvm::Function::arg_iterator AI = Fn->arg_begin();
  160. if (CGM.ReturnTypeUsesSRet(FnInfo))
  161. ++AI;
  162. // Find the first store of "this", which will be to the alloca associated
  163. // with "this".
  164. Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
  165. llvm::BasicBlock *EntryBB = &Fn->front();
  166. llvm::BasicBlock::iterator ThisStore =
  167. std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
  168. return isa<llvm::StoreInst>(I) &&
  169. I.getOperand(0) == ThisPtr.getPointer();
  170. });
  171. assert(ThisStore != EntryBB->end() &&
  172. "Store of this should be in entry block?");
  173. // Adjust "this", if necessary.
  174. Builder.SetInsertPoint(&*ThisStore);
  175. llvm::Value *AdjustedThisPtr =
  176. CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
  177. ThisStore->setOperand(0, AdjustedThisPtr);
  178. if (!Thunk.Return.isEmpty()) {
  179. // Fix up the returned value, if necessary.
  180. for (llvm::BasicBlock &BB : *Fn) {
  181. llvm::Instruction *T = BB.getTerminator();
  182. if (isa<llvm::ReturnInst>(T)) {
  183. RValue RV = RValue::get(T->getOperand(0));
  184. T->eraseFromParent();
  185. Builder.SetInsertPoint(&BB);
  186. RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
  187. Builder.CreateRet(RV.getScalarVal());
  188. break;
  189. }
  190. }
  191. }
  192. return Fn;
  193. }
  194. void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
  195. const CGFunctionInfo &FnInfo,
  196. bool IsUnprototyped) {
  197. assert(!CurGD.getDecl() && "CurGD was already set!");
  198. CurGD = GD;
  199. CurFuncIsThunk = true;
  200. // Build FunctionArgs.
  201. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  202. QualType ThisType = MD->getThisType();
  203. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  204. QualType ResultType;
  205. if (IsUnprototyped)
  206. ResultType = CGM.getContext().VoidTy;
  207. else if (CGM.getCXXABI().HasThisReturn(GD))
  208. ResultType = ThisType;
  209. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  210. ResultType = CGM.getContext().VoidPtrTy;
  211. else
  212. ResultType = FPT->getReturnType();
  213. FunctionArgList FunctionArgs;
  214. // Create the implicit 'this' parameter declaration.
  215. CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
  216. // Add the rest of the parameters, if we have a prototype to work with.
  217. if (!IsUnprototyped) {
  218. FunctionArgs.append(MD->param_begin(), MD->param_end());
  219. if (isa<CXXDestructorDecl>(MD))
  220. CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
  221. FunctionArgs);
  222. }
  223. // Start defining the function.
  224. auto NL = ApplyDebugLocation::CreateEmpty(*this);
  225. StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
  226. MD->getLocation());
  227. // Create a scope with an artificial location for the body of this function.
  228. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  229. // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
  230. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  231. CXXThisValue = CXXABIThisValue;
  232. CurCodeDecl = MD;
  233. CurFuncDecl = MD;
  234. }
  235. void CodeGenFunction::FinishThunk() {
  236. // Clear these to restore the invariants expected by
  237. // StartFunction/FinishFunction.
  238. CurCodeDecl = nullptr;
  239. CurFuncDecl = nullptr;
  240. FinishFunction();
  241. }
  242. void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
  243. const ThunkInfo *Thunk,
  244. bool IsUnprototyped) {
  245. assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
  246. "Please use a new CGF for this thunk");
  247. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
  248. // Adjust the 'this' pointer if necessary
  249. llvm::Value *AdjustedThisPtr =
  250. Thunk ? CGM.getCXXABI().performThisAdjustment(
  251. *this, LoadCXXThisAddress(), Thunk->This)
  252. : LoadCXXThis();
  253. if (CurFnInfo->usesInAlloca() || IsUnprototyped) {
  254. // We don't handle return adjusting thunks, because they require us to call
  255. // the copy constructor. For now, fall through and pretend the return
  256. // adjustment was empty so we don't crash.
  257. if (Thunk && !Thunk->Return.isEmpty()) {
  258. if (IsUnprototyped)
  259. CGM.ErrorUnsupported(
  260. MD, "return-adjusting thunk with incomplete parameter type");
  261. else
  262. CGM.ErrorUnsupported(
  263. MD, "non-trivial argument copy for return-adjusting thunk");
  264. }
  265. EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
  266. return;
  267. }
  268. // Start building CallArgs.
  269. CallArgList CallArgs;
  270. QualType ThisType = MD->getThisType();
  271. CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
  272. if (isa<CXXDestructorDecl>(MD))
  273. CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
  274. #ifndef NDEBUG
  275. unsigned PrefixArgs = CallArgs.size() - 1;
  276. #endif
  277. // Add the rest of the arguments.
  278. for (const ParmVarDecl *PD : MD->parameters())
  279. EmitDelegateCallArg(CallArgs, PD, SourceLocation());
  280. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  281. #ifndef NDEBUG
  282. const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
  283. CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
  284. assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
  285. CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
  286. CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
  287. assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
  288. similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
  289. CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
  290. assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
  291. for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
  292. assert(similar(CallFnInfo.arg_begin()[i].info,
  293. CallFnInfo.arg_begin()[i].type,
  294. CurFnInfo->arg_begin()[i].info,
  295. CurFnInfo->arg_begin()[i].type));
  296. #endif
  297. // Determine whether we have a return value slot to use.
  298. QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
  299. ? ThisType
  300. : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
  301. ? CGM.getContext().VoidPtrTy
  302. : FPT->getReturnType();
  303. ReturnValueSlot Slot;
  304. if (!ResultType->isVoidType() &&
  305. CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
  306. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  307. // Now emit our call.
  308. llvm::CallBase *CallOrInvoke;
  309. RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
  310. CallArgs, &CallOrInvoke);
  311. // Consider return adjustment if we have ThunkInfo.
  312. if (Thunk && !Thunk->Return.isEmpty())
  313. RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
  314. else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
  315. Call->setTailCallKind(llvm::CallInst::TCK_Tail);
  316. // Emit return.
  317. if (!ResultType->isVoidType() && Slot.isNull())
  318. CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
  319. // Disable the final ARC autorelease.
  320. AutoreleaseResult = false;
  321. FinishThunk();
  322. }
  323. void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
  324. llvm::Value *AdjustedThisPtr,
  325. llvm::FunctionCallee Callee) {
  326. // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
  327. // to translate AST arguments into LLVM IR arguments. For thunks, we know
  328. // that the caller prototype more or less matches the callee prototype with
  329. // the exception of 'this'.
  330. SmallVector<llvm::Value *, 8> Args;
  331. for (llvm::Argument &A : CurFn->args())
  332. Args.push_back(&A);
  333. // Set the adjusted 'this' pointer.
  334. const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
  335. if (ThisAI.isDirect()) {
  336. const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
  337. int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
  338. llvm::Type *ThisType = Args[ThisArgNo]->getType();
  339. if (ThisType != AdjustedThisPtr->getType())
  340. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
  341. Args[ThisArgNo] = AdjustedThisPtr;
  342. } else {
  343. assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
  344. Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
  345. llvm::Type *ThisType = ThisAddr.getElementType();
  346. if (ThisType != AdjustedThisPtr->getType())
  347. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
  348. Builder.CreateStore(AdjustedThisPtr, ThisAddr);
  349. }
  350. // Emit the musttail call manually. Even if the prologue pushed cleanups, we
  351. // don't actually want to run them.
  352. llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
  353. Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
  354. // Apply the standard set of call attributes.
  355. unsigned CallingConv;
  356. llvm::AttributeList Attrs;
  357. CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
  358. Attrs, CallingConv, /*AttrOnCallSite=*/true);
  359. Call->setAttributes(Attrs);
  360. Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  361. if (Call->getType()->isVoidTy())
  362. Builder.CreateRetVoid();
  363. else
  364. Builder.CreateRet(Call);
  365. // Finish the function to maintain CodeGenFunction invariants.
  366. // FIXME: Don't emit unreachable code.
  367. EmitBlock(createBasicBlock());
  368. FinishFunction();
  369. }
  370. void CodeGenFunction::generateThunk(llvm::Function *Fn,
  371. const CGFunctionInfo &FnInfo, GlobalDecl GD,
  372. const ThunkInfo &Thunk,
  373. bool IsUnprototyped) {
  374. StartThunk(Fn, GD, FnInfo, IsUnprototyped);
  375. // Create a scope with an artificial location for the body of this function.
  376. auto AL = ApplyDebugLocation::CreateArtificial(*this);
  377. // Get our callee. Use a placeholder type if this method is unprototyped so
  378. // that CodeGenModule doesn't try to set attributes.
  379. llvm::Type *Ty;
  380. if (IsUnprototyped)
  381. Ty = llvm::StructType::get(getLLVMContext());
  382. else
  383. Ty = CGM.getTypes().GetFunctionType(FnInfo);
  384. llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  385. // Fix up the function type for an unprototyped musttail call.
  386. if (IsUnprototyped)
  387. Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
  388. // Make the call and return the result.
  389. EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
  390. &Thunk, IsUnprototyped);
  391. }
  392. static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
  393. bool IsUnprototyped, bool ForVTable) {
  394. // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
  395. // provide thunks for us.
  396. if (CGM.getTarget().getCXXABI().isMicrosoft())
  397. return true;
  398. // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
  399. // definitions of the main method. Therefore, emitting thunks with the vtable
  400. // is purely an optimization. Emit the thunk if optimizations are enabled and
  401. // all of the parameter types are complete.
  402. if (ForVTable)
  403. return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
  404. // Always emit thunks along with the method definition.
  405. return true;
  406. }
  407. llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
  408. const ThunkInfo &TI,
  409. bool ForVTable) {
  410. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  411. // First, get a declaration. Compute the mangled name. Don't worry about
  412. // getting the function prototype right, since we may only need this
  413. // declaration to fill in a vtable slot.
  414. SmallString<256> Name;
  415. MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
  416. llvm::raw_svector_ostream Out(Name);
  417. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
  418. MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
  419. else
  420. MCtx.mangleThunk(MD, TI, Out);
  421. llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
  422. llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
  423. // If we don't need to emit a definition, return this declaration as is.
  424. bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
  425. MD->getType()->castAs<FunctionType>());
  426. if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
  427. return Thunk;
  428. // Arrange a function prototype appropriate for a function definition. In some
  429. // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
  430. const CGFunctionInfo &FnInfo =
  431. IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
  432. : CGM.getTypes().arrangeGlobalDeclaration(GD);
  433. llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
  434. // If the type of the underlying GlobalValue is wrong, we'll have to replace
  435. // it. It should be a declaration.
  436. llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
  437. if (ThunkFn->getFunctionType() != ThunkFnTy) {
  438. llvm::GlobalValue *OldThunkFn = ThunkFn;
  439. assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
  440. // Remove the name from the old thunk function and get a new thunk.
  441. OldThunkFn->setName(StringRef());
  442. ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
  443. Name.str(), &CGM.getModule());
  444. CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
  445. // If needed, replace the old thunk with a bitcast.
  446. if (!OldThunkFn->use_empty()) {
  447. llvm::Constant *NewPtrForOldDecl =
  448. llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
  449. OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
  450. }
  451. // Remove the old thunk.
  452. OldThunkFn->eraseFromParent();
  453. }
  454. bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
  455. bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
  456. if (!ThunkFn->isDeclaration()) {
  457. if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
  458. // There is already a thunk emitted for this function, do nothing.
  459. return ThunkFn;
  460. }
  461. setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
  462. return ThunkFn;
  463. }
  464. // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
  465. // that the return type is meaningless. These thunks can be used to call
  466. // functions with differing return types, and the caller is required to cast
  467. // the prototype appropriately to extract the correct value.
  468. if (IsUnprototyped)
  469. ThunkFn->addFnAttr("thunk");
  470. CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
  471. if (!IsUnprototyped && ThunkFn->isVarArg()) {
  472. // Varargs thunks are special; we can't just generate a call because
  473. // we can't copy the varargs. Our implementation is rather
  474. // expensive/sucky at the moment, so don't generate the thunk unless
  475. // we have to.
  476. // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
  477. if (UseAvailableExternallyLinkage)
  478. return ThunkFn;
  479. ThunkFn = CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD,
  480. TI);
  481. } else {
  482. // Normal thunk body generation.
  483. CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
  484. }
  485. setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
  486. return ThunkFn;
  487. }
  488. void CodeGenVTables::EmitThunks(GlobalDecl GD) {
  489. const CXXMethodDecl *MD =
  490. cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
  491. // We don't need to generate thunks for the base destructor.
  492. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  493. return;
  494. const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
  495. VTContext->getThunkInfo(GD);
  496. if (!ThunkInfoVector)
  497. return;
  498. for (const ThunkInfo& Thunk : *ThunkInfoVector)
  499. maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
  500. }
  501. void CodeGenVTables::addVTableComponent(
  502. ConstantArrayBuilder &builder, const VTableLayout &layout,
  503. unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
  504. auto &component = layout.vtable_components()[idx];
  505. auto addOffsetConstant = [&](CharUnits offset) {
  506. builder.add(llvm::ConstantExpr::getIntToPtr(
  507. llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
  508. CGM.Int8PtrTy));
  509. };
  510. switch (component.getKind()) {
  511. case VTableComponent::CK_VCallOffset:
  512. return addOffsetConstant(component.getVCallOffset());
  513. case VTableComponent::CK_VBaseOffset:
  514. return addOffsetConstant(component.getVBaseOffset());
  515. case VTableComponent::CK_OffsetToTop:
  516. return addOffsetConstant(component.getOffsetToTop());
  517. case VTableComponent::CK_RTTI:
  518. return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
  519. case VTableComponent::CK_FunctionPointer:
  520. case VTableComponent::CK_CompleteDtorPointer:
  521. case VTableComponent::CK_DeletingDtorPointer: {
  522. GlobalDecl GD;
  523. // Get the right global decl.
  524. switch (component.getKind()) {
  525. default:
  526. llvm_unreachable("Unexpected vtable component kind");
  527. case VTableComponent::CK_FunctionPointer:
  528. GD = component.getFunctionDecl();
  529. break;
  530. case VTableComponent::CK_CompleteDtorPointer:
  531. GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
  532. break;
  533. case VTableComponent::CK_DeletingDtorPointer:
  534. GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
  535. break;
  536. }
  537. if (CGM.getLangOpts().CUDA) {
  538. // Emit NULL for methods we can't codegen on this
  539. // side. Otherwise we'd end up with vtable with unresolved
  540. // references.
  541. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  542. // OK on device side: functions w/ __device__ attribute
  543. // OK on host side: anything except __device__-only functions.
  544. bool CanEmitMethod =
  545. CGM.getLangOpts().CUDAIsDevice
  546. ? MD->hasAttr<CUDADeviceAttr>()
  547. : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
  548. if (!CanEmitMethod)
  549. return builder.addNullPointer(CGM.Int8PtrTy);
  550. // Method is acceptable, continue processing as usual.
  551. }
  552. auto getSpecialVirtualFn = [&](StringRef name) {
  553. llvm::FunctionType *fnTy =
  554. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  555. llvm::Constant *fn = cast<llvm::Constant>(
  556. CGM.CreateRuntimeFunction(fnTy, name).getCallee());
  557. if (auto f = dyn_cast<llvm::Function>(fn))
  558. f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  559. return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
  560. };
  561. llvm::Constant *fnPtr;
  562. // Pure virtual member functions.
  563. if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
  564. if (!PureVirtualFn)
  565. PureVirtualFn =
  566. getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
  567. fnPtr = PureVirtualFn;
  568. // Deleted virtual member functions.
  569. } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
  570. if (!DeletedVirtualFn)
  571. DeletedVirtualFn =
  572. getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
  573. fnPtr = DeletedVirtualFn;
  574. // Thunks.
  575. } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
  576. layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
  577. auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
  578. nextVTableThunkIndex++;
  579. fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
  580. // Otherwise we can use the method definition directly.
  581. } else {
  582. llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
  583. fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
  584. }
  585. fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
  586. builder.add(fnPtr);
  587. return;
  588. }
  589. case VTableComponent::CK_UnusedFunctionPointer:
  590. return builder.addNullPointer(CGM.Int8PtrTy);
  591. }
  592. llvm_unreachable("Unexpected vtable component kind");
  593. }
  594. llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
  595. SmallVector<llvm::Type *, 4> tys;
  596. for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
  597. tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
  598. }
  599. return llvm::StructType::get(CGM.getLLVMContext(), tys);
  600. }
  601. void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
  602. const VTableLayout &layout,
  603. llvm::Constant *rtti) {
  604. unsigned nextVTableThunkIndex = 0;
  605. for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
  606. auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
  607. size_t thisIndex = layout.getVTableOffset(i);
  608. size_t nextIndex = thisIndex + layout.getVTableSize(i);
  609. for (unsigned i = thisIndex; i != nextIndex; ++i) {
  610. addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
  611. }
  612. vtableElem.finishAndAddTo(builder);
  613. }
  614. }
  615. llvm::GlobalVariable *
  616. CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
  617. const BaseSubobject &Base,
  618. bool BaseIsVirtual,
  619. llvm::GlobalVariable::LinkageTypes Linkage,
  620. VTableAddressPointsMapTy& AddressPoints) {
  621. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  622. DI->completeClassData(Base.getBase());
  623. std::unique_ptr<VTableLayout> VTLayout(
  624. getItaniumVTableContext().createConstructionVTableLayout(
  625. Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
  626. // Add the address points.
  627. AddressPoints = VTLayout->getAddressPoints();
  628. // Get the mangled construction vtable name.
  629. SmallString<256> OutName;
  630. llvm::raw_svector_ostream Out(OutName);
  631. cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
  632. .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
  633. Base.getBase(), Out);
  634. StringRef Name = OutName.str();
  635. llvm::Type *VTType = getVTableType(*VTLayout);
  636. // Construction vtable symbols are not part of the Itanium ABI, so we cannot
  637. // guarantee that they actually will be available externally. Instead, when
  638. // emitting an available_externally VTT, we provide references to an internal
  639. // linkage construction vtable. The ABI only requires complete-object vtables
  640. // to be the same for all instances of a type, not construction vtables.
  641. if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
  642. Linkage = llvm::GlobalVariable::InternalLinkage;
  643. unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
  644. // Create the variable that will hold the construction vtable.
  645. llvm::GlobalVariable *VTable =
  646. CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
  647. CGM.setGVProperties(VTable, RD);
  648. // V-tables are always unnamed_addr.
  649. VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  650. llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
  651. CGM.getContext().getTagDeclType(Base.getBase()));
  652. // Create and set the initializer.
  653. ConstantInitBuilder builder(CGM);
  654. auto components = builder.beginStruct();
  655. createVTableInitializer(components, *VTLayout, RTTI);
  656. components.finishAndSetAsInitializer(VTable);
  657. CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
  658. return VTable;
  659. }
  660. static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
  661. const CXXRecordDecl *RD) {
  662. return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  663. CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
  664. }
  665. /// Compute the required linkage of the vtable for the given class.
  666. ///
  667. /// Note that we only call this at the end of the translation unit.
  668. llvm::GlobalVariable::LinkageTypes
  669. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  670. if (!RD->isExternallyVisible())
  671. return llvm::GlobalVariable::InternalLinkage;
  672. // We're at the end of the translation unit, so the current key
  673. // function is fully correct.
  674. const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
  675. if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
  676. // If this class has a key function, use that to determine the
  677. // linkage of the vtable.
  678. const FunctionDecl *def = nullptr;
  679. if (keyFunction->hasBody(def))
  680. keyFunction = cast<CXXMethodDecl>(def);
  681. switch (keyFunction->getTemplateSpecializationKind()) {
  682. case TSK_Undeclared:
  683. case TSK_ExplicitSpecialization:
  684. assert((def || CodeGenOpts.OptimizationLevel > 0 ||
  685. CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
  686. "Shouldn't query vtable linkage without key function, "
  687. "optimizations, or debug info");
  688. if (!def && CodeGenOpts.OptimizationLevel > 0)
  689. return llvm::GlobalVariable::AvailableExternallyLinkage;
  690. if (keyFunction->isInlined())
  691. return !Context.getLangOpts().AppleKext ?
  692. llvm::GlobalVariable::LinkOnceODRLinkage :
  693. llvm::Function::InternalLinkage;
  694. return llvm::GlobalVariable::ExternalLinkage;
  695. case TSK_ImplicitInstantiation:
  696. return !Context.getLangOpts().AppleKext ?
  697. llvm::GlobalVariable::LinkOnceODRLinkage :
  698. llvm::Function::InternalLinkage;
  699. case TSK_ExplicitInstantiationDefinition:
  700. return !Context.getLangOpts().AppleKext ?
  701. llvm::GlobalVariable::WeakODRLinkage :
  702. llvm::Function::InternalLinkage;
  703. case TSK_ExplicitInstantiationDeclaration:
  704. llvm_unreachable("Should not have been asked to emit this");
  705. }
  706. }
  707. // -fapple-kext mode does not support weak linkage, so we must use
  708. // internal linkage.
  709. if (Context.getLangOpts().AppleKext)
  710. return llvm::Function::InternalLinkage;
  711. llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
  712. llvm::GlobalValue::LinkOnceODRLinkage;
  713. llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
  714. llvm::GlobalValue::WeakODRLinkage;
  715. if (RD->hasAttr<DLLExportAttr>()) {
  716. // Cannot discard exported vtables.
  717. DiscardableODRLinkage = NonDiscardableODRLinkage;
  718. } else if (RD->hasAttr<DLLImportAttr>()) {
  719. // Imported vtables are available externally.
  720. DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
  721. NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
  722. }
  723. switch (RD->getTemplateSpecializationKind()) {
  724. case TSK_Undeclared:
  725. case TSK_ExplicitSpecialization:
  726. case TSK_ImplicitInstantiation:
  727. return DiscardableODRLinkage;
  728. case TSK_ExplicitInstantiationDeclaration:
  729. // Explicit instantiations in MSVC do not provide vtables, so we must emit
  730. // our own.
  731. if (getTarget().getCXXABI().isMicrosoft())
  732. return DiscardableODRLinkage;
  733. return shouldEmitAvailableExternallyVTable(*this, RD)
  734. ? llvm::GlobalVariable::AvailableExternallyLinkage
  735. : llvm::GlobalVariable::ExternalLinkage;
  736. case TSK_ExplicitInstantiationDefinition:
  737. return NonDiscardableODRLinkage;
  738. }
  739. llvm_unreachable("Invalid TemplateSpecializationKind!");
  740. }
  741. /// This is a callback from Sema to tell us that a particular vtable is
  742. /// required to be emitted in this translation unit.
  743. ///
  744. /// This is only called for vtables that _must_ be emitted (mainly due to key
  745. /// functions). For weak vtables, CodeGen tracks when they are needed and
  746. /// emits them as-needed.
  747. void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
  748. VTables.GenerateClassData(theClass);
  749. }
  750. void
  751. CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
  752. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  753. DI->completeClassData(RD);
  754. if (RD->getNumVBases())
  755. CGM.getCXXABI().emitVirtualInheritanceTables(RD);
  756. CGM.getCXXABI().emitVTableDefinitions(*this, RD);
  757. }
  758. /// At this point in the translation unit, does it appear that can we
  759. /// rely on the vtable being defined elsewhere in the program?
  760. ///
  761. /// The response is really only definitive when called at the end of
  762. /// the translation unit.
  763. ///
  764. /// The only semantic restriction here is that the object file should
  765. /// not contain a vtable definition when that vtable is defined
  766. /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
  767. /// vtables when unnecessary.
  768. bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
  769. assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
  770. // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
  771. // emit them even if there is an explicit template instantiation.
  772. if (CGM.getTarget().getCXXABI().isMicrosoft())
  773. return false;
  774. // If we have an explicit instantiation declaration (and not a
  775. // definition), the vtable is defined elsewhere.
  776. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  777. if (TSK == TSK_ExplicitInstantiationDeclaration)
  778. return true;
  779. // Otherwise, if the class is an instantiated template, the
  780. // vtable must be defined here.
  781. if (TSK == TSK_ImplicitInstantiation ||
  782. TSK == TSK_ExplicitInstantiationDefinition)
  783. return false;
  784. // Otherwise, if the class doesn't have a key function (possibly
  785. // anymore), the vtable must be defined here.
  786. const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
  787. if (!keyFunction)
  788. return false;
  789. // Otherwise, if we don't have a definition of the key function, the
  790. // vtable must be defined somewhere else.
  791. return !keyFunction->hasBody();
  792. }
  793. /// Given that we're currently at the end of the translation unit, and
  794. /// we've emitted a reference to the vtable for this class, should
  795. /// we define that vtable?
  796. static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
  797. const CXXRecordDecl *RD) {
  798. // If vtable is internal then it has to be done.
  799. if (!CGM.getVTables().isVTableExternal(RD))
  800. return true;
  801. // If it's external then maybe we will need it as available_externally.
  802. return shouldEmitAvailableExternallyVTable(CGM, RD);
  803. }
  804. /// Given that at some point we emitted a reference to one or more
  805. /// vtables, and that we are now at the end of the translation unit,
  806. /// decide whether we should emit them.
  807. void CodeGenModule::EmitDeferredVTables() {
  808. #ifndef NDEBUG
  809. // Remember the size of DeferredVTables, because we're going to assume
  810. // that this entire operation doesn't modify it.
  811. size_t savedSize = DeferredVTables.size();
  812. #endif
  813. for (const CXXRecordDecl *RD : DeferredVTables)
  814. if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
  815. VTables.GenerateClassData(RD);
  816. else if (shouldOpportunisticallyEmitVTables())
  817. OpportunisticVTables.push_back(RD);
  818. assert(savedSize == DeferredVTables.size() &&
  819. "deferred extra vtables during vtable emission?");
  820. DeferredVTables.clear();
  821. }
  822. bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
  823. LinkageInfo LV = RD->getLinkageAndVisibility();
  824. if (!isExternallyVisible(LV.getLinkage()))
  825. return true;
  826. if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
  827. return false;
  828. if (getTriple().isOSBinFormatCOFF()) {
  829. if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
  830. return false;
  831. } else {
  832. if (LV.getVisibility() != HiddenVisibility)
  833. return false;
  834. }
  835. if (getCodeGenOpts().LTOVisibilityPublicStd) {
  836. const DeclContext *DC = RD;
  837. while (1) {
  838. auto *D = cast<Decl>(DC);
  839. DC = DC->getParent();
  840. if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
  841. if (auto *ND = dyn_cast<NamespaceDecl>(D))
  842. if (const IdentifierInfo *II = ND->getIdentifier())
  843. if (II->isStr("std") || II->isStr("stdext"))
  844. return false;
  845. break;
  846. }
  847. }
  848. }
  849. return true;
  850. }
  851. void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
  852. const VTableLayout &VTLayout) {
  853. if (!getCodeGenOpts().LTOUnit)
  854. return;
  855. CharUnits PointerWidth =
  856. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  857. typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
  858. std::vector<AddressPoint> AddressPoints;
  859. for (auto &&AP : VTLayout.getAddressPoints())
  860. AddressPoints.push_back(std::make_pair(
  861. AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
  862. AP.second.AddressPointIndex));
  863. // Sort the address points for determinism.
  864. llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
  865. const AddressPoint &AP2) {
  866. if (&AP1 == &AP2)
  867. return false;
  868. std::string S1;
  869. llvm::raw_string_ostream O1(S1);
  870. getCXXABI().getMangleContext().mangleTypeName(
  871. QualType(AP1.first->getTypeForDecl(), 0), O1);
  872. O1.flush();
  873. std::string S2;
  874. llvm::raw_string_ostream O2(S2);
  875. getCXXABI().getMangleContext().mangleTypeName(
  876. QualType(AP2.first->getTypeForDecl(), 0), O2);
  877. O2.flush();
  878. if (S1 < S2)
  879. return true;
  880. if (S1 != S2)
  881. return false;
  882. return AP1.second < AP2.second;
  883. });
  884. ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
  885. for (auto AP : AddressPoints) {
  886. // Create type metadata for the address point.
  887. AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
  888. // The class associated with each address point could also potentially be
  889. // used for indirect calls via a member function pointer, so we need to
  890. // annotate the address of each function pointer with the appropriate member
  891. // function pointer type.
  892. for (unsigned I = 0; I != Comps.size(); ++I) {
  893. if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
  894. continue;
  895. llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
  896. Context.getMemberPointerType(
  897. Comps[I].getFunctionDecl()->getType(),
  898. Context.getRecordType(AP.first).getTypePtr()));
  899. VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
  900. }
  901. }
  902. }