CGVTables.cpp 52 KB

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