CGVTables.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 "CodeGenModule.h"
  14. #include "CodeGenFunction.h"
  15. #include "CGCXXABI.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/Frontend/CodeGenOptions.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/Support/Compiler.h"
  22. #include "llvm/Support/Format.h"
  23. #include "llvm/Transforms/Utils/Cloning.h"
  24. #include <algorithm>
  25. #include <cstdio>
  26. using namespace clang;
  27. using namespace CodeGen;
  28. CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
  29. : CGM(CGM), VTContext(CGM.getContext()) { }
  30. bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
  31. assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
  32. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  33. if (TSK == TSK_ExplicitInstantiationDeclaration)
  34. return false;
  35. const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
  36. if (!KeyFunction)
  37. return true;
  38. // Itanium C++ ABI, 5.2.6 Instantiated Templates:
  39. // An instantiation of a class template requires:
  40. // - In the object where instantiated, the virtual table...
  41. if (TSK == TSK_ImplicitInstantiation ||
  42. TSK == TSK_ExplicitInstantiationDefinition)
  43. return true;
  44. // If we're building with optimization, we always emit VTables since that
  45. // allows for virtual function calls to be devirtualized.
  46. // (We don't want to do this in -fapple-kext mode however).
  47. if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().AppleKext)
  48. return true;
  49. return KeyFunction->hasBody();
  50. }
  51. llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
  52. const ThunkInfo &Thunk) {
  53. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  54. // Compute the mangled name.
  55. SmallString<256> Name;
  56. llvm::raw_svector_ostream Out(Name);
  57. if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
  58. getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
  59. Thunk.This, Out);
  60. else
  61. getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
  62. Out.flush();
  63. llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
  64. return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
  65. }
  66. static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
  67. llvm::Value *Ptr,
  68. int64_t NonVirtualAdjustment,
  69. int64_t VirtualAdjustment) {
  70. if (!NonVirtualAdjustment && !VirtualAdjustment)
  71. return Ptr;
  72. llvm::Type *Int8PtrTy =
  73. llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
  74. llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
  75. if (NonVirtualAdjustment) {
  76. // Do the non-virtual adjustment.
  77. V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
  78. }
  79. if (VirtualAdjustment) {
  80. llvm::Type *PtrDiffTy =
  81. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  82. // Do the virtual adjustment.
  83. llvm::Value *VTablePtrPtr =
  84. CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
  85. llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
  86. llvm::Value *OffsetPtr =
  87. CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
  88. OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
  89. // Load the adjustment offset from the vtable.
  90. llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
  91. // Adjust our pointer.
  92. V = CGF.Builder.CreateInBoundsGEP(V, Offset);
  93. }
  94. // Cast back to the original type.
  95. return CGF.Builder.CreateBitCast(V, Ptr->getType());
  96. }
  97. static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
  98. const ThunkInfo &Thunk, llvm::Function *Fn) {
  99. CGM.setGlobalVisibility(Fn, MD);
  100. if (!CGM.getCodeGenOpts().HiddenWeakVTables)
  101. return;
  102. // If the thunk has weak/linkonce linkage, but the function must be
  103. // emitted in every translation unit that references it, then we can
  104. // emit its thunks with hidden visibility, since its thunks must be
  105. // emitted when the function is.
  106. // This follows CodeGenModule::setTypeVisibility; see the comments
  107. // there for explanation.
  108. if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
  109. Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
  110. Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  111. return;
  112. if (MD->getExplicitVisibility())
  113. return;
  114. switch (MD->getTemplateSpecializationKind()) {
  115. case TSK_ExplicitInstantiationDefinition:
  116. case TSK_ExplicitInstantiationDeclaration:
  117. return;
  118. case TSK_Undeclared:
  119. break;
  120. case TSK_ExplicitSpecialization:
  121. case TSK_ImplicitInstantiation:
  122. if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
  123. return;
  124. break;
  125. }
  126. // If there's an explicit definition, and that definition is
  127. // out-of-line, then we can't assume that all users will have a
  128. // definition to emit.
  129. const FunctionDecl *Def = 0;
  130. if (MD->hasBody(Def) && Def->isOutOfLine())
  131. return;
  132. Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
  133. }
  134. #ifndef NDEBUG
  135. static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
  136. const ABIArgInfo &infoR, CanQualType typeR) {
  137. return (infoL.getKind() == infoR.getKind() &&
  138. (typeL == typeR ||
  139. (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
  140. (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
  141. }
  142. #endif
  143. static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
  144. QualType ResultType, RValue RV,
  145. const ThunkInfo &Thunk) {
  146. // Emit the return adjustment.
  147. bool NullCheckValue = !ResultType->isReferenceType();
  148. llvm::BasicBlock *AdjustNull = 0;
  149. llvm::BasicBlock *AdjustNotNull = 0;
  150. llvm::BasicBlock *AdjustEnd = 0;
  151. llvm::Value *ReturnValue = RV.getScalarVal();
  152. if (NullCheckValue) {
  153. AdjustNull = CGF.createBasicBlock("adjust.null");
  154. AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
  155. AdjustEnd = CGF.createBasicBlock("adjust.end");
  156. llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
  157. CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
  158. CGF.EmitBlock(AdjustNotNull);
  159. }
  160. ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
  161. Thunk.Return.NonVirtual,
  162. Thunk.Return.VBaseOffsetOffset);
  163. if (NullCheckValue) {
  164. CGF.Builder.CreateBr(AdjustEnd);
  165. CGF.EmitBlock(AdjustNull);
  166. CGF.Builder.CreateBr(AdjustEnd);
  167. CGF.EmitBlock(AdjustEnd);
  168. llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
  169. PHI->addIncoming(ReturnValue, AdjustNotNull);
  170. PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
  171. AdjustNull);
  172. ReturnValue = PHI;
  173. }
  174. return RValue::get(ReturnValue);
  175. }
  176. // This function does roughly the same thing as GenerateThunk, but in a
  177. // very different way, so that va_start and va_end work correctly.
  178. // FIXME: This function assumes "this" is the first non-sret LLVM argument of
  179. // a function, and that there is an alloca built in the entry block
  180. // for all accesses to "this".
  181. // FIXME: This function assumes there is only one "ret" statement per function.
  182. // FIXME: Cloning isn't correct in the presence of indirect goto!
  183. // FIXME: This implementation of thunks bloats codesize by duplicating the
  184. // function definition. There are alternatives:
  185. // 1. Add some sort of stub support to LLVM for cases where we can
  186. // do a this adjustment, then a sibcall.
  187. // 2. We could transform the definition to take a va_list instead of an
  188. // actual variable argument list, then have the thunks (including a
  189. // no-op thunk for the regular definition) call va_start/va_end.
  190. // There's a bit of per-call overhead for this solution, but it's
  191. // better for codesize if the definition is long.
  192. void CodeGenFunction::GenerateVarArgsThunk(
  193. llvm::Function *Fn,
  194. const CGFunctionInfo &FnInfo,
  195. GlobalDecl GD, const ThunkInfo &Thunk) {
  196. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  197. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  198. QualType ResultType = FPT->getResultType();
  199. // Get the original function
  200. llvm::Type *Ty =
  201. CGM.getTypes().GetFunctionType(FnInfo, /*IsVariadic*/true);
  202. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  203. llvm::Function *BaseFn = cast<llvm::Function>(Callee);
  204. // Clone to thunk.
  205. llvm::Function *NewFn = llvm::CloneFunction(BaseFn);
  206. CGM.getModule().getFunctionList().push_back(NewFn);
  207. Fn->replaceAllUsesWith(NewFn);
  208. NewFn->takeName(Fn);
  209. Fn->eraseFromParent();
  210. Fn = NewFn;
  211. // "Initialize" CGF (minimally).
  212. CurFn = Fn;
  213. // Get the "this" value
  214. llvm::Function::arg_iterator AI = Fn->arg_begin();
  215. if (CGM.ReturnTypeUsesSRet(FnInfo))
  216. ++AI;
  217. // Find the first store of "this", which will be to the alloca associated
  218. // with "this".
  219. llvm::Value *ThisPtr = &*AI;
  220. llvm::BasicBlock *EntryBB = Fn->begin();
  221. llvm::Instruction *ThisStore = 0;
  222. for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
  223. I != E; I++) {
  224. if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
  225. ThisStore = cast<llvm::StoreInst>(I);
  226. break;
  227. }
  228. }
  229. assert(ThisStore && "Store of this should be in entry block?");
  230. // Adjust "this", if necessary.
  231. Builder.SetInsertPoint(ThisStore);
  232. llvm::Value *AdjustedThisPtr =
  233. PerformTypeAdjustment(*this, ThisPtr,
  234. Thunk.This.NonVirtual,
  235. Thunk.This.VCallOffsetOffset);
  236. ThisStore->setOperand(0, AdjustedThisPtr);
  237. if (!Thunk.Return.isEmpty()) {
  238. // Fix up the returned value, if necessary.
  239. for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
  240. llvm::Instruction *T = I->getTerminator();
  241. if (isa<llvm::ReturnInst>(T)) {
  242. RValue RV = RValue::get(T->getOperand(0));
  243. T->eraseFromParent();
  244. Builder.SetInsertPoint(&*I);
  245. RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
  246. Builder.CreateRet(RV.getScalarVal());
  247. break;
  248. }
  249. }
  250. }
  251. }
  252. void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
  253. const CGFunctionInfo &FnInfo,
  254. GlobalDecl GD, const ThunkInfo &Thunk) {
  255. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  256. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  257. QualType ResultType = FPT->getResultType();
  258. QualType ThisType = MD->getThisType(getContext());
  259. FunctionArgList FunctionArgs;
  260. // FIXME: It would be nice if more of this code could be shared with
  261. // CodeGenFunction::GenerateCode.
  262. // Create the implicit 'this' parameter declaration.
  263. CurGD = GD;
  264. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
  265. // Add the rest of the parameters.
  266. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  267. E = MD->param_end(); I != E; ++I) {
  268. ParmVarDecl *Param = *I;
  269. FunctionArgs.push_back(Param);
  270. }
  271. StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
  272. SourceLocation());
  273. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  274. // Adjust the 'this' pointer if necessary.
  275. llvm::Value *AdjustedThisPtr =
  276. PerformTypeAdjustment(*this, LoadCXXThis(),
  277. Thunk.This.NonVirtual,
  278. Thunk.This.VCallOffsetOffset);
  279. CallArgList CallArgs;
  280. // Add our adjusted 'this' pointer.
  281. CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
  282. // Add the rest of the parameters.
  283. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  284. E = MD->param_end(); I != E; ++I) {
  285. ParmVarDecl *param = *I;
  286. EmitDelegateCallArg(CallArgs, param);
  287. }
  288. // Get our callee.
  289. llvm::Type *Ty =
  290. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
  291. FPT->isVariadic());
  292. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  293. #ifndef NDEBUG
  294. const CGFunctionInfo &CallFnInfo =
  295. CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo());
  296. assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
  297. CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
  298. CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
  299. assert(similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
  300. FnInfo.getReturnInfo(), FnInfo.getReturnType()));
  301. assert(CallFnInfo.arg_size() == FnInfo.arg_size());
  302. for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
  303. assert(similar(CallFnInfo.arg_begin()[i].info,
  304. CallFnInfo.arg_begin()[i].type,
  305. FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
  306. #endif
  307. // Determine whether we have a return value slot to use.
  308. ReturnValueSlot Slot;
  309. if (!ResultType->isVoidType() &&
  310. FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  311. hasAggregateLLVMType(CurFnInfo->getReturnType()))
  312. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  313. // Now emit our call.
  314. RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
  315. if (!Thunk.Return.isEmpty())
  316. RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
  317. if (!ResultType->isVoidType() && Slot.isNull())
  318. CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
  319. FinishFunction();
  320. // Set the right linkage.
  321. CGM.setFunctionLinkage(MD, Fn);
  322. // Set the right visibility.
  323. setThunkVisibility(CGM, MD, Thunk, Fn);
  324. }
  325. void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
  326. bool UseAvailableExternallyLinkage)
  327. {
  328. const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(GD);
  329. // FIXME: re-use FnInfo in this computation.
  330. llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
  331. // Strip off a bitcast if we got one back.
  332. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  333. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  334. Entry = CE->getOperand(0);
  335. }
  336. // There's already a declaration with the same name, check if it has the same
  337. // type or if we need to replace it.
  338. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
  339. CGM.getTypes().GetFunctionTypeForVTable(GD)) {
  340. llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
  341. // If the types mismatch then we have to rewrite the definition.
  342. assert(OldThunkFn->isDeclaration() &&
  343. "Shouldn't replace non-declaration");
  344. // Remove the name from the old thunk function and get a new thunk.
  345. OldThunkFn->setName(StringRef());
  346. Entry = CGM.GetAddrOfThunk(GD, Thunk);
  347. // If needed, replace the old thunk with a bitcast.
  348. if (!OldThunkFn->use_empty()) {
  349. llvm::Constant *NewPtrForOldDecl =
  350. llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
  351. OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
  352. }
  353. // Remove the old thunk.
  354. OldThunkFn->eraseFromParent();
  355. }
  356. llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
  357. if (!ThunkFn->isDeclaration()) {
  358. if (UseAvailableExternallyLinkage) {
  359. // There is already a thunk emitted for this function, do nothing.
  360. return;
  361. }
  362. // If a function has a body, it should have available_externally linkage.
  363. assert(ThunkFn->hasAvailableExternallyLinkage() &&
  364. "Function should have available_externally linkage!");
  365. // Change the linkage.
  366. CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
  367. return;
  368. }
  369. if (ThunkFn->isVarArg()) {
  370. // Varargs thunks are special; we can't just generate a call because
  371. // we can't copy the varargs. Our implementation is rather
  372. // expensive/sucky at the moment, so don't generate the thunk unless
  373. // we have to.
  374. // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
  375. if (!UseAvailableExternallyLinkage)
  376. CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
  377. } else {
  378. // Normal thunk body generation.
  379. CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
  380. }
  381. if (UseAvailableExternallyLinkage)
  382. ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  383. }
  384. void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
  385. const ThunkInfo &Thunk) {
  386. // We only want to do this when building with optimizations.
  387. if (!CGM.getCodeGenOpts().OptimizationLevel)
  388. return;
  389. // We can't emit thunks for member functions with incomplete types.
  390. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  391. if (!CGM.getTypes().isFuncTypeConvertible(
  392. cast<FunctionType>(MD->getType().getTypePtr())))
  393. return;
  394. EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
  395. }
  396. void CodeGenVTables::EmitThunks(GlobalDecl GD)
  397. {
  398. const CXXMethodDecl *MD =
  399. cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
  400. // We don't need to generate thunks for the base destructor.
  401. if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
  402. return;
  403. const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
  404. VTContext.getThunkInfo(MD);
  405. if (!ThunkInfoVector)
  406. return;
  407. for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
  408. EmitThunk(GD, (*ThunkInfoVector)[I],
  409. /*UseAvailableExternallyLinkage=*/false);
  410. }
  411. llvm::Constant *
  412. CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
  413. const VTableComponent *Components,
  414. unsigned NumComponents,
  415. const VTableLayout::VTableThunkTy *VTableThunks,
  416. unsigned NumVTableThunks) {
  417. SmallVector<llvm::Constant *, 64> Inits;
  418. llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  419. llvm::Type *PtrDiffTy =
  420. CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
  421. QualType ClassType = CGM.getContext().getTagDeclType(RD);
  422. llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
  423. unsigned NextVTableThunkIndex = 0;
  424. llvm::Constant* PureVirtualFn = 0;
  425. for (unsigned I = 0; I != NumComponents; ++I) {
  426. VTableComponent Component = Components[I];
  427. llvm::Constant *Init = 0;
  428. switch (Component.getKind()) {
  429. case VTableComponent::CK_VCallOffset:
  430. Init = llvm::ConstantInt::get(PtrDiffTy,
  431. Component.getVCallOffset().getQuantity());
  432. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  433. break;
  434. case VTableComponent::CK_VBaseOffset:
  435. Init = llvm::ConstantInt::get(PtrDiffTy,
  436. Component.getVBaseOffset().getQuantity());
  437. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  438. break;
  439. case VTableComponent::CK_OffsetToTop:
  440. Init = llvm::ConstantInt::get(PtrDiffTy,
  441. Component.getOffsetToTop().getQuantity());
  442. Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
  443. break;
  444. case VTableComponent::CK_RTTI:
  445. Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
  446. break;
  447. case VTableComponent::CK_FunctionPointer:
  448. case VTableComponent::CK_CompleteDtorPointer:
  449. case VTableComponent::CK_DeletingDtorPointer: {
  450. GlobalDecl GD;
  451. // Get the right global decl.
  452. switch (Component.getKind()) {
  453. default:
  454. llvm_unreachable("Unexpected vtable component kind");
  455. case VTableComponent::CK_FunctionPointer:
  456. GD = Component.getFunctionDecl();
  457. break;
  458. case VTableComponent::CK_CompleteDtorPointer:
  459. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
  460. break;
  461. case VTableComponent::CK_DeletingDtorPointer:
  462. GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
  463. break;
  464. }
  465. if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
  466. // We have a pure virtual member function.
  467. if (!PureVirtualFn) {
  468. llvm::FunctionType *Ty =
  469. llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
  470. /*isVarArg=*/false);
  471. PureVirtualFn =
  472. CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
  473. PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
  474. Int8PtrTy);
  475. }
  476. Init = PureVirtualFn;
  477. } else {
  478. // Check if we should use a thunk.
  479. if (NextVTableThunkIndex < NumVTableThunks &&
  480. VTableThunks[NextVTableThunkIndex].first == I) {
  481. const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
  482. Init = CGM.GetAddrOfThunk(GD, Thunk);
  483. MaybeEmitThunkAvailableExternally(GD, Thunk);
  484. NextVTableThunkIndex++;
  485. } else {
  486. llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
  487. Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
  488. }
  489. Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
  490. }
  491. break;
  492. }
  493. case VTableComponent::CK_UnusedFunctionPointer:
  494. Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
  495. break;
  496. };
  497. Inits.push_back(Init);
  498. }
  499. llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
  500. return llvm::ConstantArray::get(ArrayType, Inits);
  501. }
  502. llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
  503. llvm::GlobalVariable *&VTable = VTables[RD];
  504. if (VTable)
  505. return VTable;
  506. // We may need to generate a definition for this vtable.
  507. if (ShouldEmitVTableInThisTU(RD))
  508. CGM.DeferredVTables.push_back(RD);
  509. SmallString<256> OutName;
  510. llvm::raw_svector_ostream Out(OutName);
  511. CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
  512. Out.flush();
  513. StringRef Name = OutName.str();
  514. llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  515. llvm::ArrayType *ArrayType =
  516. llvm::ArrayType::get(Int8PtrTy,
  517. VTContext.getVTableLayout(RD).getNumVTableComponents());
  518. VTable =
  519. CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
  520. llvm::GlobalValue::ExternalLinkage);
  521. VTable->setUnnamedAddr(true);
  522. return VTable;
  523. }
  524. void
  525. CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
  526. llvm::GlobalVariable::LinkageTypes Linkage,
  527. const CXXRecordDecl *RD) {
  528. const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
  529. // Create and set the initializer.
  530. llvm::Constant *Init =
  531. CreateVTableInitializer(RD,
  532. VTLayout.vtable_component_begin(),
  533. VTLayout.getNumVTableComponents(),
  534. VTLayout.vtable_thunk_begin(),
  535. VTLayout.getNumVTableThunks());
  536. VTable->setInitializer(Init);
  537. // Set the correct linkage.
  538. VTable->setLinkage(Linkage);
  539. // Set the right visibility.
  540. CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
  541. }
  542. llvm::GlobalVariable *
  543. CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
  544. const BaseSubobject &Base,
  545. bool BaseIsVirtual,
  546. llvm::GlobalVariable::LinkageTypes Linkage,
  547. VTableAddressPointsMapTy& AddressPoints) {
  548. OwningPtr<VTableLayout> VTLayout(
  549. VTContext.createConstructionVTableLayout(Base.getBase(),
  550. Base.getBaseOffset(),
  551. BaseIsVirtual, RD));
  552. // Add the address points.
  553. AddressPoints = VTLayout->getAddressPoints();
  554. // Get the mangled construction vtable name.
  555. SmallString<256> OutName;
  556. llvm::raw_svector_ostream Out(OutName);
  557. CGM.getCXXABI().getMangleContext().
  558. mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
  559. Out);
  560. Out.flush();
  561. StringRef Name = OutName.str();
  562. llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  563. llvm::ArrayType *ArrayType =
  564. llvm::ArrayType::get(Int8PtrTy, VTLayout->getNumVTableComponents());
  565. // Create the variable that will hold the construction vtable.
  566. llvm::GlobalVariable *VTable =
  567. CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
  568. CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
  569. // V-tables are always unnamed_addr.
  570. VTable->setUnnamedAddr(true);
  571. // Create and set the initializer.
  572. llvm::Constant *Init =
  573. CreateVTableInitializer(Base.getBase(),
  574. VTLayout->vtable_component_begin(),
  575. VTLayout->getNumVTableComponents(),
  576. VTLayout->vtable_thunk_begin(),
  577. VTLayout->getNumVTableThunks());
  578. VTable->setInitializer(Init);
  579. return VTable;
  580. }
  581. void
  582. CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
  583. const CXXRecordDecl *RD) {
  584. llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
  585. if (VTable->hasInitializer())
  586. return;
  587. EmitVTableDefinition(VTable, Linkage, RD);
  588. if (RD->getNumVBases()) {
  589. llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
  590. EmitVTTDefinition(VTT, Linkage, RD);
  591. }
  592. // If this is the magic class __cxxabiv1::__fundamental_type_info,
  593. // we will emit the typeinfo for the fundamental types. This is the
  594. // same behaviour as GCC.
  595. const DeclContext *DC = RD->getDeclContext();
  596. if (RD->getIdentifier() &&
  597. RD->getIdentifier()->isStr("__fundamental_type_info") &&
  598. isa<NamespaceDecl>(DC) &&
  599. cast<NamespaceDecl>(DC)->getIdentifier() &&
  600. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
  601. DC->getParent()->isTranslationUnit())
  602. CGM.EmitFundamentalRTTIDescriptors();
  603. }