CGVTables.cpp 39 KB

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