CGVTables.cpp 35 KB

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