CGVTables.cpp 37 KB

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