CGVTables.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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->begin();
  153. llvm::Instruction *ThisStore =
  154. std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
  155. return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr.getPointer();
  156. });
  157. assert(ThisStore && "Store of this should be in entry block?");
  158. // Adjust "this", if necessary.
  159. Builder.SetInsertPoint(ThisStore);
  160. llvm::Value *AdjustedThisPtr =
  161. CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
  162. ThisStore->setOperand(0, AdjustedThisPtr);
  163. if (!Thunk.Return.isEmpty()) {
  164. // Fix up the returned value, if necessary.
  165. for (llvm::BasicBlock &BB : *Fn) {
  166. llvm::Instruction *T = BB.getTerminator();
  167. if (isa<llvm::ReturnInst>(T)) {
  168. RValue RV = RValue::get(T->getOperand(0));
  169. T->eraseFromParent();
  170. Builder.SetInsertPoint(&BB);
  171. RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
  172. Builder.CreateRet(RV.getScalarVal());
  173. break;
  174. }
  175. }
  176. }
  177. return Fn;
  178. }
  179. void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
  180. const CGFunctionInfo &FnInfo) {
  181. assert(!CurGD.getDecl() && "CurGD was already set!");
  182. CurGD = GD;
  183. CurFuncIsThunk = true;
  184. // Build FunctionArgs.
  185. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  186. QualType ThisType = MD->getThisType(getContext());
  187. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  188. QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
  189. ? ThisType
  190. : CGM.getCXXABI().hasMostDerivedReturn(GD)
  191. ? CGM.getContext().VoidPtrTy
  192. : FPT->getReturnType();
  193. FunctionArgList FunctionArgs;
  194. // Create the implicit 'this' parameter declaration.
  195. CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
  196. // Add the rest of the parameters.
  197. FunctionArgs.append(MD->param_begin(), MD->param_end());
  198. if (isa<CXXDestructorDecl>(MD))
  199. CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
  200. // Start defining the function.
  201. StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
  202. MD->getLocation(), MD->getLocation());
  203. // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
  204. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  205. CXXThisValue = CXXABIThisValue;
  206. CurCodeDecl = MD;
  207. CurFuncDecl = MD;
  208. }
  209. void CodeGenFunction::FinishThunk() {
  210. // Clear these to restore the invariants expected by
  211. // StartFunction/FinishFunction.
  212. CurCodeDecl = nullptr;
  213. CurFuncDecl = nullptr;
  214. FinishFunction();
  215. }
  216. void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
  217. const ThunkInfo *Thunk) {
  218. assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
  219. "Please use a new CGF for this thunk");
  220. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
  221. // Adjust the 'this' pointer if necessary
  222. llvm::Value *AdjustedThisPtr =
  223. Thunk ? CGM.getCXXABI().performThisAdjustment(
  224. *this, LoadCXXThisAddress(), Thunk->This)
  225. : LoadCXXThis();
  226. if (CurFnInfo->usesInAlloca()) {
  227. // We don't handle return adjusting thunks, because they require us to call
  228. // the copy constructor. For now, fall through and pretend the return
  229. // adjustment was empty so we don't crash.
  230. if (Thunk && !Thunk->Return.isEmpty()) {
  231. CGM.ErrorUnsupported(
  232. MD, "non-trivial argument copy for return-adjusting thunk");
  233. }
  234. EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
  235. return;
  236. }
  237. // Start building CallArgs.
  238. CallArgList CallArgs;
  239. QualType ThisType = MD->getThisType(getContext());
  240. CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
  241. if (isa<CXXDestructorDecl>(MD))
  242. CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
  243. // Add the rest of the arguments.
  244. for (const ParmVarDecl *PD : MD->params())
  245. EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
  246. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  247. #ifndef NDEBUG
  248. const CGFunctionInfo &CallFnInfo =
  249. CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
  250. RequiredArgs::forPrototypePlus(FPT, 1));
  251. assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
  252. CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
  253. CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
  254. assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
  255. similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
  256. CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
  257. assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
  258. for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
  259. assert(similar(CallFnInfo.arg_begin()[i].info,
  260. CallFnInfo.arg_begin()[i].type,
  261. CurFnInfo->arg_begin()[i].info,
  262. CurFnInfo->arg_begin()[i].type));
  263. #endif
  264. // Determine whether we have a return value slot to use.
  265. QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
  266. ? ThisType
  267. : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
  268. ? CGM.getContext().VoidPtrTy
  269. : FPT->getReturnType();
  270. ReturnValueSlot Slot;
  271. if (!ResultType->isVoidType() &&
  272. CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  273. !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
  274. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  275. // Now emit our call.
  276. llvm::Instruction *CallOrInvoke;
  277. RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
  278. // Consider return adjustment if we have ThunkInfo.
  279. if (Thunk && !Thunk->Return.isEmpty())
  280. RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
  281. else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
  282. Call->setTailCallKind(llvm::CallInst::TCK_Tail);
  283. // Emit return.
  284. if (!ResultType->isVoidType() && Slot.isNull())
  285. CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
  286. // Disable the final ARC autorelease.
  287. AutoreleaseResult = false;
  288. FinishThunk();
  289. }
  290. void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
  291. llvm::Value *AdjustedThisPtr,
  292. llvm::Value *Callee) {
  293. // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
  294. // to translate AST arguments into LLVM IR arguments. For thunks, we know
  295. // that the caller prototype more or less matches the callee prototype with
  296. // the exception of 'this'.
  297. SmallVector<llvm::Value *, 8> Args;
  298. for (llvm::Argument &A : CurFn->args())
  299. Args.push_back(&A);
  300. // Set the adjusted 'this' pointer.
  301. const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
  302. if (ThisAI.isDirect()) {
  303. const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
  304. int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
  305. llvm::Type *ThisType = Args[ThisArgNo]->getType();
  306. if (ThisType != AdjustedThisPtr->getType())
  307. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
  308. Args[ThisArgNo] = AdjustedThisPtr;
  309. } else {
  310. assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
  311. Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
  312. llvm::Type *ThisType = ThisAddr.getElementType();
  313. if (ThisType != AdjustedThisPtr->getType())
  314. AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
  315. Builder.CreateStore(AdjustedThisPtr, ThisAddr);
  316. }
  317. // Emit the musttail call manually. Even if the prologue pushed cleanups, we
  318. // don't actually want to run them.
  319. llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
  320. Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
  321. // Apply the standard set of call attributes.
  322. unsigned CallingConv;
  323. CodeGen::AttributeListType AttributeList;
  324. CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
  325. /*AttrOnCallSite=*/true);
  326. llvm::AttributeSet Attrs =
  327. llvm::AttributeSet::get(getLLVMContext(), AttributeList);
  328. Call->setAttributes(Attrs);
  329. Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  330. if (Call->getType()->isVoidTy())
  331. Builder.CreateRetVoid();
  332. else
  333. Builder.CreateRet(Call);
  334. // Finish the function to maintain CodeGenFunction invariants.
  335. // FIXME: Don't emit unreachable code.
  336. EmitBlock(createBasicBlock());
  337. FinishFunction();
  338. }
  339. void CodeGenFunction::generateThunk(llvm::Function *Fn,
  340. const CGFunctionInfo &FnInfo,
  341. GlobalDecl GD, const ThunkInfo &Thunk) {
  342. StartThunk(Fn, GD, FnInfo);
  343. // Get our callee.
  344. llvm::Type *Ty =
  345. CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
  346. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  347. // Make the call and return the result.
  348. EmitCallAndReturnForThunk(Callee, &Thunk);
  349. }
  350. void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
  351. bool ForVTable) {
  352. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
  353. // FIXME: re-use FnInfo in this computation.
  354. llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
  355. llvm::GlobalValue *Entry;
  356. // Strip off a bitcast if we got one back.
  357. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
  358. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  359. Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
  360. } else {
  361. Entry = cast<llvm::GlobalValue>(C);
  362. }
  363. // There's already a declaration with the same name, check if it has the same
  364. // type or if we need to replace it.
  365. if (Entry->getType()->getElementType() !=
  366. CGM.getTypes().GetFunctionTypeForVTable(GD)) {
  367. llvm::GlobalValue *OldThunkFn = Entry;
  368. // If the types mismatch then we have to rewrite the definition.
  369. assert(OldThunkFn->isDeclaration() &&
  370. "Shouldn't replace non-declaration");
  371. // Remove the name from the old thunk function and get a new thunk.
  372. OldThunkFn->setName(StringRef());
  373. Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
  374. // If needed, replace the old thunk with a bitcast.
  375. if (!OldThunkFn->use_empty()) {
  376. llvm::Constant *NewPtrForOldDecl =
  377. llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
  378. OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
  379. }
  380. // Remove the old thunk.
  381. OldThunkFn->eraseFromParent();
  382. }
  383. llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
  384. bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
  385. bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
  386. if (!ThunkFn->isDeclaration()) {
  387. if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
  388. // There is already a thunk emitted for this function, do nothing.
  389. return;
  390. }
  391. setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
  392. return;
  393. }
  394. CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
  395. if (ThunkFn->isVarArg()) {
  396. // Varargs thunks are special; we can't just generate a call because
  397. // we can't copy the varargs. Our implementation is rather
  398. // expensive/sucky at the moment, so don't generate the thunk unless
  399. // we have to.
  400. // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
  401. if (UseAvailableExternallyLinkage)
  402. return;
  403. ThunkFn =
  404. CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
  405. } else {
  406. // Normal thunk body generation.
  407. CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
  408. }
  409. setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
  410. }
  411. void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
  412. const ThunkInfo &Thunk) {
  413. // If the ABI has key functions, only the TU with the key function should emit
  414. // the thunk. However, we can allow inlining of thunks if we emit them with
  415. // available_externally linkage together with vtables when optimizations are
  416. // enabled.
  417. if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
  418. !CGM.getCodeGenOpts().OptimizationLevel)
  419. return;
  420. // We can't emit thunks for member functions with incomplete types.
  421. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  422. if (!CGM.getTypes().isFuncTypeConvertible(
  423. MD->getType()->castAs<FunctionType>()))
  424. return;
  425. emitThunk(GD, Thunk, /*ForVTable=*/true);
  426. }
  427. void CodeGenVTables::EmitThunks(GlobalDecl GD)
  428. {
  429. const CXXMethodDecl *MD =
  430. cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
  431. // We don't need to generate thunks for the base destructor.
  432. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  433. return;
  434. const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
  435. VTContext->getThunkInfo(GD);
  436. if (!ThunkInfoVector)
  437. return;
  438. for (const ThunkInfo& Thunk : *ThunkInfoVector)
  439. emitThunk(GD, Thunk, /*ForVTable=*/false);
  440. }
  441. llvm::Constant *CodeGenVTables::CreateVTableInitializer(
  442. const CXXRecordDecl *RD, const VTableComponent *Components,
  443. unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
  444. unsigned NumVTableThunks, llvm::Constant *RTTI) {
  445. SmallVector<llvm::Constant *, 64> Inits;
  446. llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
  447. llvm::Type *PtrDiffTy =
  448. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  449. unsigned NextVTableThunkIndex = 0;
  450. llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
  451. for (unsigned I = 0; I != NumComponents; ++I) {
  452. VTableComponent Component = Components[I];
  453. llvm::Constant *Init = nullptr;
  454. switch (Component.getKind()) {
  455. case VTableComponent::CK_VCallOffset:
  456. Init = llvm::ConstantInt::get(PtrDiffTy,
  457. Component.getVCallOffset().getQuantity());
  458. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  459. break;
  460. case VTableComponent::CK_VBaseOffset:
  461. Init = llvm::ConstantInt::get(PtrDiffTy,
  462. Component.getVBaseOffset().getQuantity());
  463. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  464. break;
  465. case VTableComponent::CK_OffsetToTop:
  466. Init = llvm::ConstantInt::get(PtrDiffTy,
  467. Component.getOffsetToTop().getQuantity());
  468. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  469. break;
  470. case VTableComponent::CK_RTTI:
  471. Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
  472. break;
  473. case VTableComponent::CK_FunctionPointer:
  474. case VTableComponent::CK_CompleteDtorPointer:
  475. case VTableComponent::CK_DeletingDtorPointer: {
  476. GlobalDecl GD;
  477. // Get the right global decl.
  478. switch (Component.getKind()) {
  479. default:
  480. llvm_unreachable("Unexpected vtable component kind");
  481. case VTableComponent::CK_FunctionPointer:
  482. GD = Component.getFunctionDecl();
  483. break;
  484. case VTableComponent::CK_CompleteDtorPointer:
  485. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
  486. break;
  487. case VTableComponent::CK_DeletingDtorPointer:
  488. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
  489. break;
  490. }
  491. if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
  492. // We have a pure virtual member function.
  493. if (!PureVirtualFn) {
  494. llvm::FunctionType *Ty =
  495. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  496. StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
  497. PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
  498. PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
  499. CGM.Int8PtrTy);
  500. }
  501. Init = PureVirtualFn;
  502. } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
  503. if (!DeletedVirtualFn) {
  504. llvm::FunctionType *Ty =
  505. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  506. StringRef DeletedCallName =
  507. CGM.getCXXABI().GetDeletedVirtualCallName();
  508. DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
  509. DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
  510. CGM.Int8PtrTy);
  511. }
  512. Init = DeletedVirtualFn;
  513. } else {
  514. // Check if we should use a thunk.
  515. if (NextVTableThunkIndex < NumVTableThunks &&
  516. VTableThunks[NextVTableThunkIndex].first == I) {
  517. const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
  518. maybeEmitThunkForVTable(GD, Thunk);
  519. Init = CGM.GetAddrOfThunk(GD, Thunk);
  520. NextVTableThunkIndex++;
  521. } else {
  522. llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
  523. Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  524. }
  525. Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
  526. }
  527. break;
  528. }
  529. case VTableComponent::CK_UnusedFunctionPointer:
  530. Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
  531. break;
  532. };
  533. Inits.push_back(Init);
  534. }
  535. llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
  536. return llvm::ConstantArray::get(ArrayType, Inits);
  537. }
  538. llvm::GlobalVariable *
  539. CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
  540. const BaseSubobject &Base,
  541. bool BaseIsVirtual,
  542. llvm::GlobalVariable::LinkageTypes Linkage,
  543. VTableAddressPointsMapTy& AddressPoints) {
  544. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  545. DI->completeClassData(Base.getBase());
  546. std::unique_ptr<VTableLayout> VTLayout(
  547. getItaniumVTableContext().createConstructionVTableLayout(
  548. Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
  549. // Add the address points.
  550. AddressPoints = VTLayout->getAddressPoints();
  551. // Get the mangled construction vtable name.
  552. SmallString<256> OutName;
  553. llvm::raw_svector_ostream Out(OutName);
  554. cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
  555. .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
  556. Base.getBase(), Out);
  557. StringRef Name = OutName.str();
  558. llvm::ArrayType *ArrayType =
  559. llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
  560. // Construction vtable symbols are not part of the Itanium ABI, so we cannot
  561. // guarantee that they actually will be available externally. Instead, when
  562. // emitting an available_externally VTT, we provide references to an internal
  563. // linkage construction vtable. The ABI only requires complete-object vtables
  564. // to be the same for all instances of a type, not construction vtables.
  565. if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
  566. Linkage = llvm::GlobalVariable::InternalLinkage;
  567. // Create the variable that will hold the construction vtable.
  568. llvm::GlobalVariable *VTable =
  569. CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
  570. CGM.setGlobalVisibility(VTable, RD);
  571. // V-tables are always unnamed_addr.
  572. VTable->setUnnamedAddr(true);
  573. llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
  574. CGM.getContext().getTagDeclType(Base.getBase()));
  575. // Create and set the initializer.
  576. llvm::Constant *Init = CreateVTableInitializer(
  577. Base.getBase(), VTLayout->vtable_component_begin(),
  578. VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
  579. VTLayout->getNumVTableThunks(), RTTI);
  580. VTable->setInitializer(Init);
  581. CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
  582. return VTable;
  583. }
  584. static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
  585. const CXXRecordDecl *RD) {
  586. return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  587. CGM.getCXXABI().canEmitAvailableExternallyVTable(RD);
  588. }
  589. /// Compute the required linkage of the v-table for the given class.
  590. ///
  591. /// Note that we only call this at the end of the translation unit.
  592. llvm::GlobalVariable::LinkageTypes
  593. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  594. if (!RD->isExternallyVisible())
  595. return llvm::GlobalVariable::InternalLinkage;
  596. // We're at the end of the translation unit, so the current key
  597. // function is fully correct.
  598. const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
  599. if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
  600. // If this class has a key function, use that to determine the
  601. // linkage of the vtable.
  602. const FunctionDecl *def = nullptr;
  603. if (keyFunction->hasBody(def))
  604. keyFunction = cast<CXXMethodDecl>(def);
  605. switch (keyFunction->getTemplateSpecializationKind()) {
  606. case TSK_Undeclared:
  607. case TSK_ExplicitSpecialization:
  608. assert((def || CodeGenOpts.OptimizationLevel > 0) &&
  609. "Shouldn't query vtable linkage without key function or "
  610. "optimizations");
  611. if (!def && CodeGenOpts.OptimizationLevel > 0)
  612. return llvm::GlobalVariable::AvailableExternallyLinkage;
  613. if (keyFunction->isInlined())
  614. return !Context.getLangOpts().AppleKext ?
  615. llvm::GlobalVariable::LinkOnceODRLinkage :
  616. llvm::Function::InternalLinkage;
  617. return llvm::GlobalVariable::ExternalLinkage;
  618. case TSK_ImplicitInstantiation:
  619. return !Context.getLangOpts().AppleKext ?
  620. llvm::GlobalVariable::LinkOnceODRLinkage :
  621. llvm::Function::InternalLinkage;
  622. case TSK_ExplicitInstantiationDefinition:
  623. return !Context.getLangOpts().AppleKext ?
  624. llvm::GlobalVariable::WeakODRLinkage :
  625. llvm::Function::InternalLinkage;
  626. case TSK_ExplicitInstantiationDeclaration:
  627. llvm_unreachable("Should not have been asked to emit this");
  628. }
  629. }
  630. // -fapple-kext mode does not support weak linkage, so we must use
  631. // internal linkage.
  632. if (Context.getLangOpts().AppleKext)
  633. return llvm::Function::InternalLinkage;
  634. llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
  635. llvm::GlobalValue::LinkOnceODRLinkage;
  636. llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
  637. llvm::GlobalValue::WeakODRLinkage;
  638. if (RD->hasAttr<DLLExportAttr>()) {
  639. // Cannot discard exported vtables.
  640. DiscardableODRLinkage = NonDiscardableODRLinkage;
  641. } else if (RD->hasAttr<DLLImportAttr>()) {
  642. // Imported vtables are available externally.
  643. DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
  644. NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
  645. }
  646. switch (RD->getTemplateSpecializationKind()) {
  647. case TSK_Undeclared:
  648. case TSK_ExplicitSpecialization:
  649. case TSK_ImplicitInstantiation:
  650. return DiscardableODRLinkage;
  651. case TSK_ExplicitInstantiationDeclaration:
  652. return shouldEmitAvailableExternallyVTable(*this, RD)
  653. ? llvm::GlobalVariable::AvailableExternallyLinkage
  654. : llvm::GlobalVariable::ExternalLinkage;
  655. case TSK_ExplicitInstantiationDefinition:
  656. return NonDiscardableODRLinkage;
  657. }
  658. llvm_unreachable("Invalid TemplateSpecializationKind!");
  659. }
  660. /// This is a callback from Sema to tell us that that a particular v-table is
  661. /// required to be emitted in this translation unit.
  662. ///
  663. /// This is only called for vtables that _must_ be emitted (mainly due to key
  664. /// functions). For weak vtables, CodeGen tracks when they are needed and
  665. /// emits them as-needed.
  666. void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
  667. VTables.GenerateClassData(theClass);
  668. }
  669. void
  670. CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
  671. if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
  672. DI->completeClassData(RD);
  673. if (RD->getNumVBases())
  674. CGM.getCXXABI().emitVirtualInheritanceTables(RD);
  675. CGM.getCXXABI().emitVTableDefinitions(*this, RD);
  676. }
  677. /// At this point in the translation unit, does it appear that can we
  678. /// rely on the vtable being defined elsewhere in the program?
  679. ///
  680. /// The response is really only definitive when called at the end of
  681. /// the translation unit.
  682. ///
  683. /// The only semantic restriction here is that the object file should
  684. /// not contain a v-table definition when that v-table is defined
  685. /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
  686. /// v-tables when unnecessary.
  687. bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
  688. assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
  689. // If we have an explicit instantiation declaration (and not a
  690. // definition), the v-table is defined elsewhere.
  691. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  692. if (TSK == TSK_ExplicitInstantiationDeclaration)
  693. return true;
  694. // Otherwise, if the class is an instantiated template, the
  695. // v-table must be defined here.
  696. if (TSK == TSK_ImplicitInstantiation ||
  697. TSK == TSK_ExplicitInstantiationDefinition)
  698. return false;
  699. // Otherwise, if the class doesn't have a key function (possibly
  700. // anymore), the v-table must be defined here.
  701. const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
  702. if (!keyFunction)
  703. return false;
  704. // Otherwise, if we don't have a definition of the key function, the
  705. // v-table must be defined somewhere else.
  706. return !keyFunction->hasBody();
  707. }
  708. /// Given that we're currently at the end of the translation unit, and
  709. /// we've emitted a reference to the v-table for this class, should
  710. /// we define that v-table?
  711. static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
  712. const CXXRecordDecl *RD) {
  713. // If vtable is internal then it has to be done
  714. if (!CGM.getVTables().isVTableExternal(RD))
  715. return true;
  716. // If it's external then maybe we will need it as available_externally
  717. return shouldEmitAvailableExternallyVTable(CGM, RD);
  718. }
  719. /// Given that at some point we emitted a reference to one or more
  720. /// v-tables, and that we are now at the end of the translation unit,
  721. /// decide whether we should emit them.
  722. void CodeGenModule::EmitDeferredVTables() {
  723. #ifndef NDEBUG
  724. // Remember the size of DeferredVTables, because we're going to assume
  725. // that this entire operation doesn't modify it.
  726. size_t savedSize = DeferredVTables.size();
  727. #endif
  728. for (const CXXRecordDecl *RD : DeferredVTables)
  729. if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
  730. VTables.GenerateClassData(RD);
  731. assert(savedSize == DeferredVTables.size() &&
  732. "deferred extra v-tables during v-table emission?");
  733. DeferredVTables.clear();
  734. }
  735. bool CodeGenModule::IsCFIBlacklistedRecord(const CXXRecordDecl *RD) {
  736. if (RD->hasAttr<UuidAttr>() &&
  737. getContext().getSanitizerBlacklist().isBlacklistedType("attr:uuid"))
  738. return true;
  739. return getContext().getSanitizerBlacklist().isBlacklistedType(
  740. RD->getQualifiedNameAsString());
  741. }
  742. void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
  743. const VTableLayout &VTLayout) {
  744. if (!LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  745. !LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  746. !LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  747. !LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
  748. return;
  749. CharUnits PointerWidth =
  750. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  751. std::vector<llvm::MDTuple *> BitsetEntries;
  752. // Create a bit set entry for each address point.
  753. for (auto &&AP : VTLayout.getAddressPoints()) {
  754. if (IsCFIBlacklistedRecord(AP.first.getBase()))
  755. continue;
  756. BitsetEntries.push_back(CreateVTableBitSetEntry(
  757. VTable, PointerWidth * AP.second, AP.first.getBase()));
  758. }
  759. // Sort the bit set entries for determinism.
  760. std::sort(BitsetEntries.begin(), BitsetEntries.end(), [](llvm::MDTuple *T1,
  761. llvm::MDTuple *T2) {
  762. if (T1 == T2)
  763. return false;
  764. StringRef S1 = cast<llvm::MDString>(T1->getOperand(0))->getString();
  765. StringRef S2 = cast<llvm::MDString>(T2->getOperand(0))->getString();
  766. if (S1 < S2)
  767. return true;
  768. if (S1 != S2)
  769. return false;
  770. uint64_t Offset1 = cast<llvm::ConstantInt>(
  771. cast<llvm::ConstantAsMetadata>(T1->getOperand(2))
  772. ->getValue())->getZExtValue();
  773. uint64_t Offset2 = cast<llvm::ConstantInt>(
  774. cast<llvm::ConstantAsMetadata>(T2->getOperand(2))
  775. ->getValue())->getZExtValue();
  776. assert(Offset1 != Offset2);
  777. return Offset1 < Offset2;
  778. });
  779. llvm::NamedMDNode *BitsetsMD =
  780. getModule().getOrInsertNamedMetadata("llvm.bitsets");
  781. for (auto BitsetEntry : BitsetEntries)
  782. BitsetsMD->addOperand(BitsetEntry);
  783. }