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