1 1.1 joerg //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===// 2 1.1 joerg // 3 1.1 joerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 1.1 joerg // See https://llvm.org/LICENSE.txt for license information. 5 1.1 joerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 1.1 joerg // 7 1.1 joerg //===----------------------------------------------------------------------===// 8 1.1 joerg // 9 1.1 joerg // This contains code dealing with C++ code generation of virtual tables. 10 1.1 joerg // 11 1.1 joerg //===----------------------------------------------------------------------===// 12 1.1 joerg 13 1.1 joerg #include "CGCXXABI.h" 14 1.1 joerg #include "CodeGenFunction.h" 15 1.1 joerg #include "CodeGenModule.h" 16 1.1.1.2 joerg #include "clang/AST/Attr.h" 17 1.1 joerg #include "clang/AST/CXXInheritance.h" 18 1.1 joerg #include "clang/AST/RecordLayout.h" 19 1.1 joerg #include "clang/Basic/CodeGenOptions.h" 20 1.1 joerg #include "clang/CodeGen/CGFunctionInfo.h" 21 1.1 joerg #include "clang/CodeGen/ConstantInitBuilder.h" 22 1.1 joerg #include "llvm/IR/IntrinsicInst.h" 23 1.1 joerg #include "llvm/Support/Format.h" 24 1.1 joerg #include "llvm/Transforms/Utils/Cloning.h" 25 1.1 joerg #include <algorithm> 26 1.1 joerg #include <cstdio> 27 1.1 joerg 28 1.1 joerg using namespace clang; 29 1.1 joerg using namespace CodeGen; 30 1.1 joerg 31 1.1 joerg CodeGenVTables::CodeGenVTables(CodeGenModule &CGM) 32 1.1 joerg : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {} 33 1.1 joerg 34 1.1 joerg llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, 35 1.1 joerg GlobalDecl GD) { 36 1.1 joerg return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true, 37 1.1 joerg /*DontDefer=*/true, /*IsThunk=*/true); 38 1.1 joerg } 39 1.1 joerg 40 1.1 joerg static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk, 41 1.1 joerg llvm::Function *ThunkFn, bool ForVTable, 42 1.1 joerg GlobalDecl GD) { 43 1.1 joerg CGM.setFunctionLinkage(GD, ThunkFn); 44 1.1 joerg CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD, 45 1.1 joerg !Thunk.Return.isEmpty()); 46 1.1 joerg 47 1.1 joerg // Set the right visibility. 48 1.1 joerg CGM.setGVProperties(ThunkFn, GD); 49 1.1 joerg 50 1.1 joerg if (!CGM.getCXXABI().exportThunk()) { 51 1.1 joerg ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 52 1.1 joerg ThunkFn->setDSOLocal(true); 53 1.1 joerg } 54 1.1 joerg 55 1.1 joerg if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker()) 56 1.1 joerg ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName())); 57 1.1 joerg } 58 1.1 joerg 59 1.1 joerg #ifndef NDEBUG 60 1.1 joerg static bool similar(const ABIArgInfo &infoL, CanQualType typeL, 61 1.1 joerg const ABIArgInfo &infoR, CanQualType typeR) { 62 1.1 joerg return (infoL.getKind() == infoR.getKind() && 63 1.1 joerg (typeL == typeR || 64 1.1 joerg (isa<PointerType>(typeL) && isa<PointerType>(typeR)) || 65 1.1 joerg (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR)))); 66 1.1 joerg } 67 1.1 joerg #endif 68 1.1 joerg 69 1.1 joerg static RValue PerformReturnAdjustment(CodeGenFunction &CGF, 70 1.1 joerg QualType ResultType, RValue RV, 71 1.1 joerg const ThunkInfo &Thunk) { 72 1.1 joerg // Emit the return adjustment. 73 1.1 joerg bool NullCheckValue = !ResultType->isReferenceType(); 74 1.1 joerg 75 1.1 joerg llvm::BasicBlock *AdjustNull = nullptr; 76 1.1 joerg llvm::BasicBlock *AdjustNotNull = nullptr; 77 1.1 joerg llvm::BasicBlock *AdjustEnd = nullptr; 78 1.1 joerg 79 1.1 joerg llvm::Value *ReturnValue = RV.getScalarVal(); 80 1.1 joerg 81 1.1 joerg if (NullCheckValue) { 82 1.1 joerg AdjustNull = CGF.createBasicBlock("adjust.null"); 83 1.1 joerg AdjustNotNull = CGF.createBasicBlock("adjust.notnull"); 84 1.1 joerg AdjustEnd = CGF.createBasicBlock("adjust.end"); 85 1.1 joerg 86 1.1 joerg llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue); 87 1.1 joerg CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull); 88 1.1 joerg CGF.EmitBlock(AdjustNotNull); 89 1.1 joerg } 90 1.1 joerg 91 1.1 joerg auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl(); 92 1.1 joerg auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl); 93 1.1 joerg ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, 94 1.1 joerg Address(ReturnValue, ClassAlign), 95 1.1 joerg Thunk.Return); 96 1.1 joerg 97 1.1 joerg if (NullCheckValue) { 98 1.1 joerg CGF.Builder.CreateBr(AdjustEnd); 99 1.1 joerg CGF.EmitBlock(AdjustNull); 100 1.1 joerg CGF.Builder.CreateBr(AdjustEnd); 101 1.1 joerg CGF.EmitBlock(AdjustEnd); 102 1.1 joerg 103 1.1 joerg llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2); 104 1.1 joerg PHI->addIncoming(ReturnValue, AdjustNotNull); 105 1.1 joerg PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()), 106 1.1 joerg AdjustNull); 107 1.1 joerg ReturnValue = PHI; 108 1.1 joerg } 109 1.1 joerg 110 1.1 joerg return RValue::get(ReturnValue); 111 1.1 joerg } 112 1.1 joerg 113 1.1 joerg /// This function clones a function's DISubprogram node and enters it into 114 1.1 joerg /// a value map with the intent that the map can be utilized by the cloner 115 1.1 joerg /// to short-circuit Metadata node mapping. 116 1.1 joerg /// Furthermore, the function resolves any DILocalVariable nodes referenced 117 1.1 joerg /// by dbg.value intrinsics so they can be properly mapped during cloning. 118 1.1 joerg static void resolveTopLevelMetadata(llvm::Function *Fn, 119 1.1 joerg llvm::ValueToValueMapTy &VMap) { 120 1.1 joerg // Clone the DISubprogram node and put it into the Value map. 121 1.1 joerg auto *DIS = Fn->getSubprogram(); 122 1.1 joerg if (!DIS) 123 1.1 joerg return; 124 1.1 joerg auto *NewDIS = DIS->replaceWithDistinct(DIS->clone()); 125 1.1 joerg VMap.MD()[DIS].reset(NewDIS); 126 1.1 joerg 127 1.1 joerg // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes 128 1.1 joerg // they are referencing. 129 1.1 joerg for (auto &BB : Fn->getBasicBlockList()) { 130 1.1 joerg for (auto &I : BB) { 131 1.1 joerg if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) { 132 1.1 joerg auto *DILocal = DII->getVariable(); 133 1.1 joerg if (!DILocal->isResolved()) 134 1.1 joerg DILocal->resolve(); 135 1.1 joerg } 136 1.1 joerg } 137 1.1 joerg } 138 1.1 joerg } 139 1.1 joerg 140 1.1 joerg // This function does roughly the same thing as GenerateThunk, but in a 141 1.1 joerg // very different way, so that va_start and va_end work correctly. 142 1.1 joerg // FIXME: This function assumes "this" is the first non-sret LLVM argument of 143 1.1 joerg // a function, and that there is an alloca built in the entry block 144 1.1 joerg // for all accesses to "this". 145 1.1 joerg // FIXME: This function assumes there is only one "ret" statement per function. 146 1.1 joerg // FIXME: Cloning isn't correct in the presence of indirect goto! 147 1.1 joerg // FIXME: This implementation of thunks bloats codesize by duplicating the 148 1.1 joerg // function definition. There are alternatives: 149 1.1 joerg // 1. Add some sort of stub support to LLVM for cases where we can 150 1.1 joerg // do a this adjustment, then a sibcall. 151 1.1 joerg // 2. We could transform the definition to take a va_list instead of an 152 1.1 joerg // actual variable argument list, then have the thunks (including a 153 1.1 joerg // no-op thunk for the regular definition) call va_start/va_end. 154 1.1 joerg // There's a bit of per-call overhead for this solution, but it's 155 1.1 joerg // better for codesize if the definition is long. 156 1.1 joerg llvm::Function * 157 1.1 joerg CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn, 158 1.1 joerg const CGFunctionInfo &FnInfo, 159 1.1 joerg GlobalDecl GD, const ThunkInfo &Thunk) { 160 1.1 joerg const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 161 1.1 joerg const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 162 1.1 joerg QualType ResultType = FPT->getReturnType(); 163 1.1 joerg 164 1.1 joerg // Get the original function 165 1.1 joerg assert(FnInfo.isVariadic()); 166 1.1 joerg llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo); 167 1.1 joerg llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 168 1.1 joerg llvm::Function *BaseFn = cast<llvm::Function>(Callee); 169 1.1 joerg 170 1.1 joerg // Cloning can't work if we don't have a definition. The Microsoft ABI may 171 1.1 joerg // require thunks when a definition is not available. Emit an error in these 172 1.1 joerg // cases. 173 1.1 joerg if (!MD->isDefined()) { 174 1.1 joerg CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments"); 175 1.1 joerg return Fn; 176 1.1 joerg } 177 1.1 joerg assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method"); 178 1.1 joerg 179 1.1 joerg // Clone to thunk. 180 1.1 joerg llvm::ValueToValueMapTy VMap; 181 1.1 joerg 182 1.1 joerg // We are cloning a function while some Metadata nodes are still unresolved. 183 1.1 joerg // Ensure that the value mapper does not encounter any of them. 184 1.1 joerg resolveTopLevelMetadata(BaseFn, VMap); 185 1.1 joerg llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap); 186 1.1 joerg Fn->replaceAllUsesWith(NewFn); 187 1.1 joerg NewFn->takeName(Fn); 188 1.1 joerg Fn->eraseFromParent(); 189 1.1 joerg Fn = NewFn; 190 1.1 joerg 191 1.1 joerg // "Initialize" CGF (minimally). 192 1.1 joerg CurFn = Fn; 193 1.1 joerg 194 1.1 joerg // Get the "this" value 195 1.1 joerg llvm::Function::arg_iterator AI = Fn->arg_begin(); 196 1.1 joerg if (CGM.ReturnTypeUsesSRet(FnInfo)) 197 1.1 joerg ++AI; 198 1.1 joerg 199 1.1 joerg // Find the first store of "this", which will be to the alloca associated 200 1.1 joerg // with "this". 201 1.1 joerg Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent())); 202 1.1 joerg llvm::BasicBlock *EntryBB = &Fn->front(); 203 1.1 joerg llvm::BasicBlock::iterator ThisStore = 204 1.1 joerg std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) { 205 1.1 joerg return isa<llvm::StoreInst>(I) && 206 1.1 joerg I.getOperand(0) == ThisPtr.getPointer(); 207 1.1 joerg }); 208 1.1 joerg assert(ThisStore != EntryBB->end() && 209 1.1 joerg "Store of this should be in entry block?"); 210 1.1 joerg // Adjust "this", if necessary. 211 1.1 joerg Builder.SetInsertPoint(&*ThisStore); 212 1.1 joerg llvm::Value *AdjustedThisPtr = 213 1.1 joerg CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This); 214 1.1 joerg AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, 215 1.1 joerg ThisStore->getOperand(0)->getType()); 216 1.1 joerg ThisStore->setOperand(0, AdjustedThisPtr); 217 1.1 joerg 218 1.1 joerg if (!Thunk.Return.isEmpty()) { 219 1.1 joerg // Fix up the returned value, if necessary. 220 1.1 joerg for (llvm::BasicBlock &BB : *Fn) { 221 1.1 joerg llvm::Instruction *T = BB.getTerminator(); 222 1.1 joerg if (isa<llvm::ReturnInst>(T)) { 223 1.1 joerg RValue RV = RValue::get(T->getOperand(0)); 224 1.1 joerg T->eraseFromParent(); 225 1.1 joerg Builder.SetInsertPoint(&BB); 226 1.1 joerg RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk); 227 1.1 joerg Builder.CreateRet(RV.getScalarVal()); 228 1.1 joerg break; 229 1.1 joerg } 230 1.1 joerg } 231 1.1 joerg } 232 1.1 joerg 233 1.1 joerg return Fn; 234 1.1 joerg } 235 1.1 joerg 236 1.1 joerg void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD, 237 1.1 joerg const CGFunctionInfo &FnInfo, 238 1.1 joerg bool IsUnprototyped) { 239 1.1 joerg assert(!CurGD.getDecl() && "CurGD was already set!"); 240 1.1 joerg CurGD = GD; 241 1.1 joerg CurFuncIsThunk = true; 242 1.1 joerg 243 1.1 joerg // Build FunctionArgs. 244 1.1 joerg const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 245 1.1 joerg QualType ThisType = MD->getThisType(); 246 1.1 joerg QualType ResultType; 247 1.1 joerg if (IsUnprototyped) 248 1.1 joerg ResultType = CGM.getContext().VoidTy; 249 1.1 joerg else if (CGM.getCXXABI().HasThisReturn(GD)) 250 1.1 joerg ResultType = ThisType; 251 1.1 joerg else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 252 1.1 joerg ResultType = CGM.getContext().VoidPtrTy; 253 1.1 joerg else 254 1.1 joerg ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType(); 255 1.1 joerg FunctionArgList FunctionArgs; 256 1.1 joerg 257 1.1 joerg // Create the implicit 'this' parameter declaration. 258 1.1 joerg CGM.getCXXABI().buildThisParam(*this, FunctionArgs); 259 1.1 joerg 260 1.1 joerg // Add the rest of the parameters, if we have a prototype to work with. 261 1.1 joerg if (!IsUnprototyped) { 262 1.1 joerg FunctionArgs.append(MD->param_begin(), MD->param_end()); 263 1.1 joerg 264 1.1 joerg if (isa<CXXDestructorDecl>(MD)) 265 1.1 joerg CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, 266 1.1 joerg FunctionArgs); 267 1.1 joerg } 268 1.1 joerg 269 1.1 joerg // Start defining the function. 270 1.1 joerg auto NL = ApplyDebugLocation::CreateEmpty(*this); 271 1.1 joerg StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs, 272 1.1 joerg MD->getLocation()); 273 1.1 joerg // Create a scope with an artificial location for the body of this function. 274 1.1 joerg auto AL = ApplyDebugLocation::CreateArtificial(*this); 275 1.1 joerg 276 1.1 joerg // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves. 277 1.1 joerg CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 278 1.1 joerg CXXThisValue = CXXABIThisValue; 279 1.1 joerg CurCodeDecl = MD; 280 1.1 joerg CurFuncDecl = MD; 281 1.1 joerg } 282 1.1 joerg 283 1.1 joerg void CodeGenFunction::FinishThunk() { 284 1.1 joerg // Clear these to restore the invariants expected by 285 1.1 joerg // StartFunction/FinishFunction. 286 1.1 joerg CurCodeDecl = nullptr; 287 1.1 joerg CurFuncDecl = nullptr; 288 1.1 joerg 289 1.1 joerg FinishFunction(); 290 1.1 joerg } 291 1.1 joerg 292 1.1 joerg void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, 293 1.1 joerg const ThunkInfo *Thunk, 294 1.1 joerg bool IsUnprototyped) { 295 1.1 joerg assert(isa<CXXMethodDecl>(CurGD.getDecl()) && 296 1.1 joerg "Please use a new CGF for this thunk"); 297 1.1 joerg const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl()); 298 1.1 joerg 299 1.1 joerg // Adjust the 'this' pointer if necessary 300 1.1 joerg llvm::Value *AdjustedThisPtr = 301 1.1 joerg Thunk ? CGM.getCXXABI().performThisAdjustment( 302 1.1 joerg *this, LoadCXXThisAddress(), Thunk->This) 303 1.1 joerg : LoadCXXThis(); 304 1.1 joerg 305 1.1 joerg // If perfect forwarding is required a variadic method, a method using 306 1.1 joerg // inalloca, or an unprototyped thunk, use musttail. Emit an error if this 307 1.1 joerg // thunk requires a return adjustment, since that is impossible with musttail. 308 1.1 joerg if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) { 309 1.1 joerg if (Thunk && !Thunk->Return.isEmpty()) { 310 1.1 joerg if (IsUnprototyped) 311 1.1 joerg CGM.ErrorUnsupported( 312 1.1 joerg MD, "return-adjusting thunk with incomplete parameter type"); 313 1.1 joerg else if (CurFnInfo->isVariadic()) 314 1.1 joerg llvm_unreachable("shouldn't try to emit musttail return-adjusting " 315 1.1 joerg "thunks for variadic functions"); 316 1.1 joerg else 317 1.1 joerg CGM.ErrorUnsupported( 318 1.1 joerg MD, "non-trivial argument copy for return-adjusting thunk"); 319 1.1 joerg } 320 1.1 joerg EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee); 321 1.1 joerg return; 322 1.1 joerg } 323 1.1 joerg 324 1.1 joerg // Start building CallArgs. 325 1.1 joerg CallArgList CallArgs; 326 1.1 joerg QualType ThisType = MD->getThisType(); 327 1.1 joerg CallArgs.add(RValue::get(AdjustedThisPtr), ThisType); 328 1.1 joerg 329 1.1 joerg if (isa<CXXDestructorDecl>(MD)) 330 1.1 joerg CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs); 331 1.1 joerg 332 1.1 joerg #ifndef NDEBUG 333 1.1 joerg unsigned PrefixArgs = CallArgs.size() - 1; 334 1.1 joerg #endif 335 1.1 joerg // Add the rest of the arguments. 336 1.1 joerg for (const ParmVarDecl *PD : MD->parameters()) 337 1.1 joerg EmitDelegateCallArg(CallArgs, PD, SourceLocation()); 338 1.1 joerg 339 1.1.1.2 joerg const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 340 1.1 joerg 341 1.1 joerg #ifndef NDEBUG 342 1.1 joerg const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall( 343 1.1 joerg CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs); 344 1.1 joerg assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() && 345 1.1 joerg CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() && 346 1.1 joerg CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention()); 347 1.1 joerg assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types 348 1.1 joerg similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(), 349 1.1 joerg CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType())); 350 1.1 joerg assert(CallFnInfo.arg_size() == CurFnInfo->arg_size()); 351 1.1 joerg for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i) 352 1.1 joerg assert(similar(CallFnInfo.arg_begin()[i].info, 353 1.1 joerg CallFnInfo.arg_begin()[i].type, 354 1.1 joerg CurFnInfo->arg_begin()[i].info, 355 1.1 joerg CurFnInfo->arg_begin()[i].type)); 356 1.1 joerg #endif 357 1.1 joerg 358 1.1 joerg // Determine whether we have a return value slot to use. 359 1.1 joerg QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD) 360 1.1 joerg ? ThisType 361 1.1 joerg : CGM.getCXXABI().hasMostDerivedReturn(CurGD) 362 1.1 joerg ? CGM.getContext().VoidPtrTy 363 1.1 joerg : FPT->getReturnType(); 364 1.1 joerg ReturnValueSlot Slot; 365 1.1 joerg if (!ResultType->isVoidType() && 366 1.1.1.2 joerg (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect || 367 1.1.1.2 joerg hasAggregateEvaluationKind(ResultType))) 368 1.1.1.2 joerg Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(), 369 1.1.1.2 joerg /*IsUnused=*/false, /*IsExternallyDestructed=*/true); 370 1.1 joerg 371 1.1 joerg // Now emit our call. 372 1.1 joerg llvm::CallBase *CallOrInvoke; 373 1.1 joerg RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot, 374 1.1 joerg CallArgs, &CallOrInvoke); 375 1.1 joerg 376 1.1 joerg // Consider return adjustment if we have ThunkInfo. 377 1.1 joerg if (Thunk && !Thunk->Return.isEmpty()) 378 1.1 joerg RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk); 379 1.1 joerg else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke)) 380 1.1 joerg Call->setTailCallKind(llvm::CallInst::TCK_Tail); 381 1.1 joerg 382 1.1 joerg // Emit return. 383 1.1 joerg if (!ResultType->isVoidType() && Slot.isNull()) 384 1.1 joerg CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType); 385 1.1 joerg 386 1.1 joerg // Disable the final ARC autorelease. 387 1.1 joerg AutoreleaseResult = false; 388 1.1 joerg 389 1.1 joerg FinishThunk(); 390 1.1 joerg } 391 1.1 joerg 392 1.1 joerg void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD, 393 1.1 joerg llvm::Value *AdjustedThisPtr, 394 1.1 joerg llvm::FunctionCallee Callee) { 395 1.1 joerg // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery 396 1.1 joerg // to translate AST arguments into LLVM IR arguments. For thunks, we know 397 1.1 joerg // that the caller prototype more or less matches the callee prototype with 398 1.1 joerg // the exception of 'this'. 399 1.1 joerg SmallVector<llvm::Value *, 8> Args; 400 1.1 joerg for (llvm::Argument &A : CurFn->args()) 401 1.1 joerg Args.push_back(&A); 402 1.1 joerg 403 1.1 joerg // Set the adjusted 'this' pointer. 404 1.1 joerg const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info; 405 1.1 joerg if (ThisAI.isDirect()) { 406 1.1 joerg const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo(); 407 1.1 joerg int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0; 408 1.1 joerg llvm::Type *ThisType = Args[ThisArgNo]->getType(); 409 1.1 joerg if (ThisType != AdjustedThisPtr->getType()) 410 1.1 joerg AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType); 411 1.1 joerg Args[ThisArgNo] = AdjustedThisPtr; 412 1.1 joerg } else { 413 1.1 joerg assert(ThisAI.isInAlloca() && "this is passed directly or inalloca"); 414 1.1 joerg Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl); 415 1.1 joerg llvm::Type *ThisType = ThisAddr.getElementType(); 416 1.1 joerg if (ThisType != AdjustedThisPtr->getType()) 417 1.1 joerg AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType); 418 1.1 joerg Builder.CreateStore(AdjustedThisPtr, ThisAddr); 419 1.1 joerg } 420 1.1 joerg 421 1.1 joerg // Emit the musttail call manually. Even if the prologue pushed cleanups, we 422 1.1 joerg // don't actually want to run them. 423 1.1 joerg llvm::CallInst *Call = Builder.CreateCall(Callee, Args); 424 1.1 joerg Call->setTailCallKind(llvm::CallInst::TCK_MustTail); 425 1.1 joerg 426 1.1 joerg // Apply the standard set of call attributes. 427 1.1 joerg unsigned CallingConv; 428 1.1 joerg llvm::AttributeList Attrs; 429 1.1 joerg CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD, 430 1.1.1.2 joerg Attrs, CallingConv, /*AttrOnCallSite=*/true, 431 1.1.1.2 joerg /*IsThunk=*/false); 432 1.1 joerg Call->setAttributes(Attrs); 433 1.1 joerg Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 434 1.1 joerg 435 1.1 joerg if (Call->getType()->isVoidTy()) 436 1.1 joerg Builder.CreateRetVoid(); 437 1.1 joerg else 438 1.1 joerg Builder.CreateRet(Call); 439 1.1 joerg 440 1.1 joerg // Finish the function to maintain CodeGenFunction invariants. 441 1.1 joerg // FIXME: Don't emit unreachable code. 442 1.1 joerg EmitBlock(createBasicBlock()); 443 1.1.1.2 joerg 444 1.1.1.2 joerg FinishThunk(); 445 1.1 joerg } 446 1.1 joerg 447 1.1 joerg void CodeGenFunction::generateThunk(llvm::Function *Fn, 448 1.1 joerg const CGFunctionInfo &FnInfo, GlobalDecl GD, 449 1.1 joerg const ThunkInfo &Thunk, 450 1.1 joerg bool IsUnprototyped) { 451 1.1 joerg StartThunk(Fn, GD, FnInfo, IsUnprototyped); 452 1.1 joerg // Create a scope with an artificial location for the body of this function. 453 1.1 joerg auto AL = ApplyDebugLocation::CreateArtificial(*this); 454 1.1 joerg 455 1.1 joerg // Get our callee. Use a placeholder type if this method is unprototyped so 456 1.1 joerg // that CodeGenModule doesn't try to set attributes. 457 1.1 joerg llvm::Type *Ty; 458 1.1 joerg if (IsUnprototyped) 459 1.1 joerg Ty = llvm::StructType::get(getLLVMContext()); 460 1.1 joerg else 461 1.1 joerg Ty = CGM.getTypes().GetFunctionType(FnInfo); 462 1.1 joerg 463 1.1 joerg llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true); 464 1.1 joerg 465 1.1 joerg // Fix up the function type for an unprototyped musttail call. 466 1.1 joerg if (IsUnprototyped) 467 1.1 joerg Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType()); 468 1.1 joerg 469 1.1 joerg // Make the call and return the result. 470 1.1 joerg EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee), 471 1.1 joerg &Thunk, IsUnprototyped); 472 1.1 joerg } 473 1.1 joerg 474 1.1 joerg static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD, 475 1.1 joerg bool IsUnprototyped, bool ForVTable) { 476 1.1 joerg // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to 477 1.1 joerg // provide thunks for us. 478 1.1 joerg if (CGM.getTarget().getCXXABI().isMicrosoft()) 479 1.1 joerg return true; 480 1.1 joerg 481 1.1 joerg // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide 482 1.1 joerg // definitions of the main method. Therefore, emitting thunks with the vtable 483 1.1 joerg // is purely an optimization. Emit the thunk if optimizations are enabled and 484 1.1 joerg // all of the parameter types are complete. 485 1.1 joerg if (ForVTable) 486 1.1 joerg return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped; 487 1.1 joerg 488 1.1 joerg // Always emit thunks along with the method definition. 489 1.1 joerg return true; 490 1.1 joerg } 491 1.1 joerg 492 1.1 joerg llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD, 493 1.1 joerg const ThunkInfo &TI, 494 1.1 joerg bool ForVTable) { 495 1.1 joerg const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 496 1.1 joerg 497 1.1 joerg // First, get a declaration. Compute the mangled name. Don't worry about 498 1.1 joerg // getting the function prototype right, since we may only need this 499 1.1 joerg // declaration to fill in a vtable slot. 500 1.1 joerg SmallString<256> Name; 501 1.1 joerg MangleContext &MCtx = CGM.getCXXABI().getMangleContext(); 502 1.1 joerg llvm::raw_svector_ostream Out(Name); 503 1.1 joerg if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) 504 1.1 joerg MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out); 505 1.1 joerg else 506 1.1 joerg MCtx.mangleThunk(MD, TI, Out); 507 1.1 joerg llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD); 508 1.1 joerg llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD); 509 1.1 joerg 510 1.1 joerg // If we don't need to emit a definition, return this declaration as is. 511 1.1 joerg bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible( 512 1.1 joerg MD->getType()->castAs<FunctionType>()); 513 1.1 joerg if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable)) 514 1.1 joerg return Thunk; 515 1.1 joerg 516 1.1 joerg // Arrange a function prototype appropriate for a function definition. In some 517 1.1 joerg // cases in the MS ABI, we may need to build an unprototyped musttail thunk. 518 1.1 joerg const CGFunctionInfo &FnInfo = 519 1.1 joerg IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD) 520 1.1 joerg : CGM.getTypes().arrangeGlobalDeclaration(GD); 521 1.1 joerg llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo); 522 1.1 joerg 523 1.1 joerg // If the type of the underlying GlobalValue is wrong, we'll have to replace 524 1.1 joerg // it. It should be a declaration. 525 1.1 joerg llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts()); 526 1.1 joerg if (ThunkFn->getFunctionType() != ThunkFnTy) { 527 1.1 joerg llvm::GlobalValue *OldThunkFn = ThunkFn; 528 1.1 joerg 529 1.1 joerg assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration"); 530 1.1 joerg 531 1.1 joerg // Remove the name from the old thunk function and get a new thunk. 532 1.1 joerg OldThunkFn->setName(StringRef()); 533 1.1 joerg ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage, 534 1.1 joerg Name.str(), &CGM.getModule()); 535 1.1.1.2 joerg CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false); 536 1.1 joerg 537 1.1 joerg // If needed, replace the old thunk with a bitcast. 538 1.1 joerg if (!OldThunkFn->use_empty()) { 539 1.1 joerg llvm::Constant *NewPtrForOldDecl = 540 1.1 joerg llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType()); 541 1.1 joerg OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl); 542 1.1 joerg } 543 1.1 joerg 544 1.1 joerg // Remove the old thunk. 545 1.1 joerg OldThunkFn->eraseFromParent(); 546 1.1 joerg } 547 1.1 joerg 548 1.1 joerg bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions(); 549 1.1 joerg bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions; 550 1.1 joerg 551 1.1 joerg if (!ThunkFn->isDeclaration()) { 552 1.1 joerg if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) { 553 1.1 joerg // There is already a thunk emitted for this function, do nothing. 554 1.1 joerg return ThunkFn; 555 1.1 joerg } 556 1.1 joerg 557 1.1 joerg setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD); 558 1.1 joerg return ThunkFn; 559 1.1 joerg } 560 1.1 joerg 561 1.1 joerg // If this will be unprototyped, add the "thunk" attribute so that LLVM knows 562 1.1 joerg // that the return type is meaningless. These thunks can be used to call 563 1.1 joerg // functions with differing return types, and the caller is required to cast 564 1.1 joerg // the prototype appropriately to extract the correct value. 565 1.1 joerg if (IsUnprototyped) 566 1.1 joerg ThunkFn->addFnAttr("thunk"); 567 1.1 joerg 568 1.1 joerg CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn); 569 1.1 joerg 570 1.1 joerg // Thunks for variadic methods are special because in general variadic 571 1.1.1.2 joerg // arguments cannot be perfectly forwarded. In the general case, clang 572 1.1 joerg // implements such thunks by cloning the original function body. However, for 573 1.1 joerg // thunks with no return adjustment on targets that support musttail, we can 574 1.1 joerg // use musttail to perfectly forward the variadic arguments. 575 1.1 joerg bool ShouldCloneVarArgs = false; 576 1.1 joerg if (!IsUnprototyped && ThunkFn->isVarArg()) { 577 1.1 joerg ShouldCloneVarArgs = true; 578 1.1 joerg if (TI.Return.isEmpty()) { 579 1.1 joerg switch (CGM.getTriple().getArch()) { 580 1.1 joerg case llvm::Triple::x86_64: 581 1.1 joerg case llvm::Triple::x86: 582 1.1 joerg case llvm::Triple::aarch64: 583 1.1 joerg ShouldCloneVarArgs = false; 584 1.1 joerg break; 585 1.1 joerg default: 586 1.1 joerg break; 587 1.1 joerg } 588 1.1 joerg } 589 1.1 joerg } 590 1.1 joerg 591 1.1 joerg if (ShouldCloneVarArgs) { 592 1.1 joerg if (UseAvailableExternallyLinkage) 593 1.1 joerg return ThunkFn; 594 1.1 joerg ThunkFn = 595 1.1 joerg CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI); 596 1.1 joerg } else { 597 1.1 joerg // Normal thunk body generation. 598 1.1 joerg CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped); 599 1.1 joerg } 600 1.1 joerg 601 1.1 joerg setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD); 602 1.1 joerg return ThunkFn; 603 1.1 joerg } 604 1.1 joerg 605 1.1 joerg void CodeGenVTables::EmitThunks(GlobalDecl GD) { 606 1.1 joerg const CXXMethodDecl *MD = 607 1.1 joerg cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl(); 608 1.1 joerg 609 1.1 joerg // We don't need to generate thunks for the base destructor. 610 1.1 joerg if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 611 1.1 joerg return; 612 1.1 joerg 613 1.1 joerg const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector = 614 1.1 joerg VTContext->getThunkInfo(GD); 615 1.1 joerg 616 1.1 joerg if (!ThunkInfoVector) 617 1.1 joerg return; 618 1.1 joerg 619 1.1 joerg for (const ThunkInfo& Thunk : *ThunkInfoVector) 620 1.1 joerg maybeEmitThunk(GD, Thunk, /*ForVTable=*/false); 621 1.1 joerg } 622 1.1 joerg 623 1.1.1.2 joerg void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder, 624 1.1.1.2 joerg llvm::Constant *component, 625 1.1.1.2 joerg unsigned vtableAddressPoint, 626 1.1.1.2 joerg bool vtableHasLocalLinkage, 627 1.1.1.2 joerg bool isCompleteDtor) const { 628 1.1.1.2 joerg // No need to get the offset of a nullptr. 629 1.1.1.2 joerg if (component->isNullValue()) 630 1.1.1.2 joerg return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0)); 631 1.1.1.2 joerg 632 1.1.1.2 joerg auto *globalVal = 633 1.1.1.2 joerg cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases()); 634 1.1.1.2 joerg llvm::Module &module = CGM.getModule(); 635 1.1.1.2 joerg 636 1.1.1.2 joerg // We don't want to copy the linkage of the vtable exactly because we still 637 1.1.1.2 joerg // want the stub/proxy to be emitted for properly calculating the offset. 638 1.1.1.2 joerg // Examples where there would be no symbol emitted are available_externally 639 1.1.1.2 joerg // and private linkages. 640 1.1.1.2 joerg auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage 641 1.1.1.2 joerg : llvm::GlobalValue::ExternalLinkage; 642 1.1.1.2 joerg 643 1.1.1.2 joerg llvm::Constant *target; 644 1.1.1.2 joerg if (auto *func = dyn_cast<llvm::Function>(globalVal)) { 645 1.1.1.2 joerg target = llvm::DSOLocalEquivalent::get(func); 646 1.1.1.2 joerg } else { 647 1.1.1.2 joerg llvm::SmallString<16> rttiProxyName(globalVal->getName()); 648 1.1.1.2 joerg rttiProxyName.append(".rtti_proxy"); 649 1.1.1.2 joerg 650 1.1.1.2 joerg // The RTTI component may not always be emitted in the same linkage unit as 651 1.1.1.2 joerg // the vtable. As a general case, we can make a dso_local proxy to the RTTI 652 1.1.1.2 joerg // that points to the actual RTTI struct somewhere. This will result in a 653 1.1.1.2 joerg // GOTPCREL relocation when taking the relative offset to the proxy. 654 1.1.1.2 joerg llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName); 655 1.1.1.2 joerg if (!proxy) { 656 1.1.1.2 joerg proxy = new llvm::GlobalVariable(module, globalVal->getType(), 657 1.1.1.2 joerg /*isConstant=*/true, stubLinkage, 658 1.1.1.2 joerg globalVal, rttiProxyName); 659 1.1.1.2 joerg proxy->setDSOLocal(true); 660 1.1.1.2 joerg proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 661 1.1.1.2 joerg if (!proxy->hasLocalLinkage()) { 662 1.1.1.2 joerg proxy->setVisibility(llvm::GlobalValue::HiddenVisibility); 663 1.1.1.2 joerg proxy->setComdat(module.getOrInsertComdat(rttiProxyName)); 664 1.1.1.2 joerg } 665 1.1.1.2 joerg } 666 1.1.1.2 joerg target = proxy; 667 1.1.1.2 joerg } 668 1.1.1.2 joerg 669 1.1.1.2 joerg builder.addRelativeOffsetToPosition(CGM.Int32Ty, target, 670 1.1.1.2 joerg /*position=*/vtableAddressPoint); 671 1.1.1.2 joerg } 672 1.1.1.2 joerg 673 1.1.1.2 joerg bool CodeGenVTables::useRelativeLayout() const { 674 1.1.1.2 joerg return CGM.getTarget().getCXXABI().isItaniumFamily() && 675 1.1.1.2 joerg CGM.getItaniumVTableContext().isRelativeLayout(); 676 1.1.1.2 joerg } 677 1.1.1.2 joerg 678 1.1.1.2 joerg llvm::Type *CodeGenVTables::getVTableComponentType() const { 679 1.1.1.2 joerg if (useRelativeLayout()) 680 1.1.1.2 joerg return CGM.Int32Ty; 681 1.1.1.2 joerg return CGM.Int8PtrTy; 682 1.1.1.2 joerg } 683 1.1.1.2 joerg 684 1.1.1.2 joerg static void AddPointerLayoutOffset(const CodeGenModule &CGM, 685 1.1.1.2 joerg ConstantArrayBuilder &builder, 686 1.1.1.2 joerg CharUnits offset) { 687 1.1.1.2 joerg builder.add(llvm::ConstantExpr::getIntToPtr( 688 1.1.1.2 joerg llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()), 689 1.1.1.2 joerg CGM.Int8PtrTy)); 690 1.1.1.2 joerg } 691 1.1.1.2 joerg 692 1.1.1.2 joerg static void AddRelativeLayoutOffset(const CodeGenModule &CGM, 693 1.1.1.2 joerg ConstantArrayBuilder &builder, 694 1.1.1.2 joerg CharUnits offset) { 695 1.1.1.2 joerg builder.add(llvm::ConstantInt::get(CGM.Int32Ty, offset.getQuantity())); 696 1.1.1.2 joerg } 697 1.1.1.2 joerg 698 1.1.1.2 joerg void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder, 699 1.1.1.2 joerg const VTableLayout &layout, 700 1.1.1.2 joerg unsigned componentIndex, 701 1.1.1.2 joerg llvm::Constant *rtti, 702 1.1.1.2 joerg unsigned &nextVTableThunkIndex, 703 1.1.1.2 joerg unsigned vtableAddressPoint, 704 1.1.1.2 joerg bool vtableHasLocalLinkage) { 705 1.1.1.2 joerg auto &component = layout.vtable_components()[componentIndex]; 706 1.1.1.2 joerg 707 1.1.1.2 joerg auto addOffsetConstant = 708 1.1.1.2 joerg useRelativeLayout() ? AddRelativeLayoutOffset : AddPointerLayoutOffset; 709 1.1 joerg 710 1.1 joerg switch (component.getKind()) { 711 1.1 joerg case VTableComponent::CK_VCallOffset: 712 1.1.1.2 joerg return addOffsetConstant(CGM, builder, component.getVCallOffset()); 713 1.1 joerg 714 1.1 joerg case VTableComponent::CK_VBaseOffset: 715 1.1.1.2 joerg return addOffsetConstant(CGM, builder, component.getVBaseOffset()); 716 1.1 joerg 717 1.1 joerg case VTableComponent::CK_OffsetToTop: 718 1.1.1.2 joerg return addOffsetConstant(CGM, builder, component.getOffsetToTop()); 719 1.1 joerg 720 1.1 joerg case VTableComponent::CK_RTTI: 721 1.1.1.2 joerg if (useRelativeLayout()) 722 1.1.1.2 joerg return addRelativeComponent(builder, rtti, vtableAddressPoint, 723 1.1.1.2 joerg vtableHasLocalLinkage, 724 1.1.1.2 joerg /*isCompleteDtor=*/false); 725 1.1.1.2 joerg else 726 1.1.1.2 joerg return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy)); 727 1.1 joerg 728 1.1 joerg case VTableComponent::CK_FunctionPointer: 729 1.1 joerg case VTableComponent::CK_CompleteDtorPointer: 730 1.1 joerg case VTableComponent::CK_DeletingDtorPointer: { 731 1.1.1.2 joerg GlobalDecl GD = component.getGlobalDecl(); 732 1.1 joerg 733 1.1 joerg if (CGM.getLangOpts().CUDA) { 734 1.1 joerg // Emit NULL for methods we can't codegen on this 735 1.1 joerg // side. Otherwise we'd end up with vtable with unresolved 736 1.1 joerg // references. 737 1.1 joerg const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 738 1.1 joerg // OK on device side: functions w/ __device__ attribute 739 1.1 joerg // OK on host side: anything except __device__-only functions. 740 1.1 joerg bool CanEmitMethod = 741 1.1 joerg CGM.getLangOpts().CUDAIsDevice 742 1.1 joerg ? MD->hasAttr<CUDADeviceAttr>() 743 1.1 joerg : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>()); 744 1.1 joerg if (!CanEmitMethod) 745 1.1.1.2 joerg return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy)); 746 1.1 joerg // Method is acceptable, continue processing as usual. 747 1.1 joerg } 748 1.1 joerg 749 1.1.1.2 joerg auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * { 750 1.1.1.2 joerg // FIXME(PR43094): When merging comdat groups, lld can select a local 751 1.1.1.2 joerg // symbol as the signature symbol even though it cannot be accessed 752 1.1.1.2 joerg // outside that symbol's TU. The relative vtables ABI would make 753 1.1.1.2 joerg // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and 754 1.1.1.2 joerg // depending on link order, the comdat groups could resolve to the one 755 1.1.1.2 joerg // with the local symbol. As a temporary solution, fill these components 756 1.1.1.2 joerg // with zero. We shouldn't be calling these in the first place anyway. 757 1.1.1.2 joerg if (useRelativeLayout()) 758 1.1.1.2 joerg return llvm::ConstantPointerNull::get(CGM.Int8PtrTy); 759 1.1.1.2 joerg 760 1.1.1.2 joerg // For NVPTX devices in OpenMP emit special functon as null pointers, 761 1.1.1.2 joerg // otherwise linking ends up with unresolved references. 762 1.1.1.2 joerg if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice && 763 1.1.1.2 joerg CGM.getTriple().isNVPTX()) 764 1.1.1.2 joerg return llvm::ConstantPointerNull::get(CGM.Int8PtrTy); 765 1.1 joerg llvm::FunctionType *fnTy = 766 1.1 joerg llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 767 1.1 joerg llvm::Constant *fn = cast<llvm::Constant>( 768 1.1 joerg CGM.CreateRuntimeFunction(fnTy, name).getCallee()); 769 1.1 joerg if (auto f = dyn_cast<llvm::Function>(fn)) 770 1.1 joerg f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 771 1.1 joerg return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy); 772 1.1 joerg }; 773 1.1 joerg 774 1.1 joerg llvm::Constant *fnPtr; 775 1.1 joerg 776 1.1 joerg // Pure virtual member functions. 777 1.1 joerg if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) { 778 1.1 joerg if (!PureVirtualFn) 779 1.1 joerg PureVirtualFn = 780 1.1.1.2 joerg getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName()); 781 1.1 joerg fnPtr = PureVirtualFn; 782 1.1 joerg 783 1.1 joerg // Deleted virtual member functions. 784 1.1 joerg } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) { 785 1.1 joerg if (!DeletedVirtualFn) 786 1.1 joerg DeletedVirtualFn = 787 1.1.1.2 joerg getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName()); 788 1.1 joerg fnPtr = DeletedVirtualFn; 789 1.1 joerg 790 1.1 joerg // Thunks. 791 1.1 joerg } else if (nextVTableThunkIndex < layout.vtable_thunks().size() && 792 1.1.1.2 joerg layout.vtable_thunks()[nextVTableThunkIndex].first == 793 1.1.1.2 joerg componentIndex) { 794 1.1 joerg auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second; 795 1.1 joerg 796 1.1 joerg nextVTableThunkIndex++; 797 1.1 joerg fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true); 798 1.1 joerg 799 1.1 joerg // Otherwise we can use the method definition directly. 800 1.1 joerg } else { 801 1.1 joerg llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD); 802 1.1 joerg fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true); 803 1.1 joerg } 804 1.1 joerg 805 1.1.1.2 joerg if (useRelativeLayout()) { 806 1.1.1.2 joerg return addRelativeComponent( 807 1.1.1.2 joerg builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage, 808 1.1.1.2 joerg component.getKind() == VTableComponent::CK_CompleteDtorPointer); 809 1.1.1.2 joerg } else 810 1.1.1.2 joerg return builder.add(llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy)); 811 1.1 joerg } 812 1.1 joerg 813 1.1 joerg case VTableComponent::CK_UnusedFunctionPointer: 814 1.1.1.2 joerg if (useRelativeLayout()) 815 1.1.1.2 joerg return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty)); 816 1.1.1.2 joerg else 817 1.1.1.2 joerg return builder.addNullPointer(CGM.Int8PtrTy); 818 1.1 joerg } 819 1.1 joerg 820 1.1 joerg llvm_unreachable("Unexpected vtable component kind"); 821 1.1 joerg } 822 1.1 joerg 823 1.1 joerg llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) { 824 1.1 joerg SmallVector<llvm::Type *, 4> tys; 825 1.1.1.2 joerg llvm::Type *componentType = getVTableComponentType(); 826 1.1.1.2 joerg for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) 827 1.1.1.2 joerg tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i))); 828 1.1 joerg 829 1.1 joerg return llvm::StructType::get(CGM.getLLVMContext(), tys); 830 1.1 joerg } 831 1.1 joerg 832 1.1 joerg void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder, 833 1.1 joerg const VTableLayout &layout, 834 1.1.1.2 joerg llvm::Constant *rtti, 835 1.1.1.2 joerg bool vtableHasLocalLinkage) { 836 1.1.1.2 joerg llvm::Type *componentType = getVTableComponentType(); 837 1.1.1.2 joerg 838 1.1.1.2 joerg const auto &addressPoints = layout.getAddressPointIndices(); 839 1.1 joerg unsigned nextVTableThunkIndex = 0; 840 1.1.1.2 joerg for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables(); 841 1.1.1.2 joerg vtableIndex != endIndex; ++vtableIndex) { 842 1.1.1.2 joerg auto vtableElem = builder.beginArray(componentType); 843 1.1.1.2 joerg 844 1.1.1.2 joerg size_t vtableStart = layout.getVTableOffset(vtableIndex); 845 1.1.1.2 joerg size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex); 846 1.1.1.2 joerg for (size_t componentIndex = vtableStart; componentIndex < vtableEnd; 847 1.1.1.2 joerg ++componentIndex) { 848 1.1.1.2 joerg addVTableComponent(vtableElem, layout, componentIndex, rtti, 849 1.1.1.2 joerg nextVTableThunkIndex, addressPoints[vtableIndex], 850 1.1.1.2 joerg vtableHasLocalLinkage); 851 1.1 joerg } 852 1.1 joerg vtableElem.finishAndAddTo(builder); 853 1.1 joerg } 854 1.1 joerg } 855 1.1 joerg 856 1.1.1.2 joerg llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable( 857 1.1.1.2 joerg const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual, 858 1.1.1.2 joerg llvm::GlobalVariable::LinkageTypes Linkage, 859 1.1.1.2 joerg VTableAddressPointsMapTy &AddressPoints) { 860 1.1 joerg if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) 861 1.1 joerg DI->completeClassData(Base.getBase()); 862 1.1 joerg 863 1.1 joerg std::unique_ptr<VTableLayout> VTLayout( 864 1.1 joerg getItaniumVTableContext().createConstructionVTableLayout( 865 1.1 joerg Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD)); 866 1.1 joerg 867 1.1 joerg // Add the address points. 868 1.1 joerg AddressPoints = VTLayout->getAddressPoints(); 869 1.1 joerg 870 1.1 joerg // Get the mangled construction vtable name. 871 1.1 joerg SmallString<256> OutName; 872 1.1 joerg llvm::raw_svector_ostream Out(OutName); 873 1.1 joerg cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext()) 874 1.1 joerg .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), 875 1.1 joerg Base.getBase(), Out); 876 1.1.1.2 joerg SmallString<256> Name(OutName); 877 1.1.1.2 joerg 878 1.1.1.2 joerg bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout(); 879 1.1.1.2 joerg bool VTableAliasExists = 880 1.1.1.2 joerg UsingRelativeLayout && CGM.getModule().getNamedAlias(Name); 881 1.1.1.2 joerg if (VTableAliasExists) { 882 1.1.1.2 joerg // We previously made the vtable hidden and changed its name. 883 1.1.1.2 joerg Name.append(".local"); 884 1.1.1.2 joerg } 885 1.1 joerg 886 1.1 joerg llvm::Type *VTType = getVTableType(*VTLayout); 887 1.1 joerg 888 1.1 joerg // Construction vtable symbols are not part of the Itanium ABI, so we cannot 889 1.1 joerg // guarantee that they actually will be available externally. Instead, when 890 1.1 joerg // emitting an available_externally VTT, we provide references to an internal 891 1.1 joerg // linkage construction vtable. The ABI only requires complete-object vtables 892 1.1 joerg // to be the same for all instances of a type, not construction vtables. 893 1.1 joerg if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage) 894 1.1 joerg Linkage = llvm::GlobalVariable::InternalLinkage; 895 1.1 joerg 896 1.1 joerg unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType); 897 1.1 joerg 898 1.1 joerg // Create the variable that will hold the construction vtable. 899 1.1 joerg llvm::GlobalVariable *VTable = 900 1.1 joerg CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align); 901 1.1 joerg 902 1.1 joerg // V-tables are always unnamed_addr. 903 1.1 joerg VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 904 1.1 joerg 905 1.1 joerg llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor( 906 1.1 joerg CGM.getContext().getTagDeclType(Base.getBase())); 907 1.1 joerg 908 1.1 joerg // Create and set the initializer. 909 1.1 joerg ConstantInitBuilder builder(CGM); 910 1.1 joerg auto components = builder.beginStruct(); 911 1.1.1.2 joerg createVTableInitializer(components, *VTLayout, RTTI, 912 1.1.1.2 joerg VTable->hasLocalLinkage()); 913 1.1 joerg components.finishAndSetAsInitializer(VTable); 914 1.1 joerg 915 1.1 joerg // Set properties only after the initializer has been set to ensure that the 916 1.1 joerg // GV is treated as definition and not declaration. 917 1.1 joerg assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration"); 918 1.1 joerg CGM.setGVProperties(VTable, RD); 919 1.1 joerg 920 1.1 joerg CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get()); 921 1.1 joerg 922 1.1.1.2 joerg if (UsingRelativeLayout && !VTable->isDSOLocal()) 923 1.1.1.2 joerg GenerateRelativeVTableAlias(VTable, OutName); 924 1.1.1.2 joerg 925 1.1 joerg return VTable; 926 1.1 joerg } 927 1.1 joerg 928 1.1.1.2 joerg // If the VTable is not dso_local, then we will not be able to indicate that 929 1.1.1.2 joerg // the VTable does not need a relocation and move into rodata. A frequent 930 1.1.1.2 joerg // time this can occur is for classes that should be made public from a DSO 931 1.1.1.2 joerg // (like in libc++). For cases like these, we can make the vtable hidden or 932 1.1.1.2 joerg // private and create a public alias with the same visibility and linkage as 933 1.1.1.2 joerg // the original vtable type. 934 1.1.1.2 joerg void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable, 935 1.1.1.2 joerg llvm::StringRef AliasNameRef) { 936 1.1.1.2 joerg assert(getItaniumVTableContext().isRelativeLayout() && 937 1.1.1.2 joerg "Can only use this if the relative vtable ABI is used"); 938 1.1.1.2 joerg assert(!VTable->isDSOLocal() && "This should be called only if the vtable is " 939 1.1.1.2 joerg "not guaranteed to be dso_local"); 940 1.1.1.2 joerg 941 1.1.1.2 joerg // If the vtable is available_externally, we shouldn't (or need to) generate 942 1.1.1.2 joerg // an alias for it in the first place since the vtable won't actually by 943 1.1.1.2 joerg // emitted in this compilation unit. 944 1.1.1.2 joerg if (VTable->hasAvailableExternallyLinkage()) 945 1.1.1.2 joerg return; 946 1.1.1.2 joerg 947 1.1.1.2 joerg // Create a new string in the event the alias is already the name of the 948 1.1.1.2 joerg // vtable. Using the reference directly could lead to use of an inititialized 949 1.1.1.2 joerg // value in the module's StringMap. 950 1.1.1.2 joerg llvm::SmallString<256> AliasName(AliasNameRef); 951 1.1.1.2 joerg VTable->setName(AliasName + ".local"); 952 1.1.1.2 joerg 953 1.1.1.2 joerg auto Linkage = VTable->getLinkage(); 954 1.1.1.2 joerg assert(llvm::GlobalAlias::isValidLinkage(Linkage) && 955 1.1.1.2 joerg "Invalid vtable alias linkage"); 956 1.1.1.2 joerg 957 1.1.1.2 joerg llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName); 958 1.1.1.2 joerg if (!VTableAlias) { 959 1.1.1.2 joerg VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(), 960 1.1.1.2 joerg VTable->getAddressSpace(), Linkage, 961 1.1.1.2 joerg AliasName, &CGM.getModule()); 962 1.1.1.2 joerg } else { 963 1.1.1.2 joerg assert(VTableAlias->getValueType() == VTable->getValueType()); 964 1.1.1.2 joerg assert(VTableAlias->getLinkage() == Linkage); 965 1.1.1.2 joerg } 966 1.1.1.2 joerg VTableAlias->setVisibility(VTable->getVisibility()); 967 1.1.1.2 joerg VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr()); 968 1.1.1.2 joerg 969 1.1.1.2 joerg // Both of these imply dso_local for the vtable. 970 1.1.1.2 joerg if (!VTable->hasComdat()) { 971 1.1.1.2 joerg // If this is in a comdat, then we shouldn't make the linkage private due to 972 1.1.1.2 joerg // an issue in lld where private symbols can be used as the key symbol when 973 1.1.1.2 joerg // choosing the prevelant group. This leads to "relocation refers to a 974 1.1.1.2 joerg // symbol in a discarded section". 975 1.1.1.2 joerg VTable->setLinkage(llvm::GlobalValue::PrivateLinkage); 976 1.1.1.2 joerg } else { 977 1.1.1.2 joerg // We should at least make this hidden since we don't want to expose it. 978 1.1.1.2 joerg VTable->setVisibility(llvm::GlobalValue::HiddenVisibility); 979 1.1.1.2 joerg } 980 1.1.1.2 joerg 981 1.1.1.2 joerg VTableAlias->setAliasee(VTable); 982 1.1.1.2 joerg } 983 1.1.1.2 joerg 984 1.1 joerg static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM, 985 1.1 joerg const CXXRecordDecl *RD) { 986 1.1 joerg return CGM.getCodeGenOpts().OptimizationLevel > 0 && 987 1.1 joerg CGM.getCXXABI().canSpeculativelyEmitVTable(RD); 988 1.1 joerg } 989 1.1 joerg 990 1.1 joerg /// Compute the required linkage of the vtable for the given class. 991 1.1 joerg /// 992 1.1 joerg /// Note that we only call this at the end of the translation unit. 993 1.1 joerg llvm::GlobalVariable::LinkageTypes 994 1.1 joerg CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 995 1.1 joerg if (!RD->isExternallyVisible()) 996 1.1 joerg return llvm::GlobalVariable::InternalLinkage; 997 1.1 joerg 998 1.1 joerg // We're at the end of the translation unit, so the current key 999 1.1 joerg // function is fully correct. 1000 1.1 joerg const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD); 1001 1.1 joerg if (keyFunction && !RD->hasAttr<DLLImportAttr>()) { 1002 1.1 joerg // If this class has a key function, use that to determine the 1003 1.1 joerg // linkage of the vtable. 1004 1.1 joerg const FunctionDecl *def = nullptr; 1005 1.1 joerg if (keyFunction->hasBody(def)) 1006 1.1 joerg keyFunction = cast<CXXMethodDecl>(def); 1007 1.1 joerg 1008 1.1 joerg switch (keyFunction->getTemplateSpecializationKind()) { 1009 1.1 joerg case TSK_Undeclared: 1010 1.1 joerg case TSK_ExplicitSpecialization: 1011 1.1 joerg assert((def || CodeGenOpts.OptimizationLevel > 0 || 1012 1.1 joerg CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) && 1013 1.1 joerg "Shouldn't query vtable linkage without key function, " 1014 1.1 joerg "optimizations, or debug info"); 1015 1.1 joerg if (!def && CodeGenOpts.OptimizationLevel > 0) 1016 1.1 joerg return llvm::GlobalVariable::AvailableExternallyLinkage; 1017 1.1 joerg 1018 1.1 joerg if (keyFunction->isInlined()) 1019 1.1 joerg return !Context.getLangOpts().AppleKext ? 1020 1.1 joerg llvm::GlobalVariable::LinkOnceODRLinkage : 1021 1.1 joerg llvm::Function::InternalLinkage; 1022 1.1 joerg 1023 1.1 joerg return llvm::GlobalVariable::ExternalLinkage; 1024 1.1 joerg 1025 1.1 joerg case TSK_ImplicitInstantiation: 1026 1.1 joerg return !Context.getLangOpts().AppleKext ? 1027 1.1 joerg llvm::GlobalVariable::LinkOnceODRLinkage : 1028 1.1 joerg llvm::Function::InternalLinkage; 1029 1.1 joerg 1030 1.1 joerg case TSK_ExplicitInstantiationDefinition: 1031 1.1 joerg return !Context.getLangOpts().AppleKext ? 1032 1.1 joerg llvm::GlobalVariable::WeakODRLinkage : 1033 1.1 joerg llvm::Function::InternalLinkage; 1034 1.1 joerg 1035 1.1 joerg case TSK_ExplicitInstantiationDeclaration: 1036 1.1 joerg llvm_unreachable("Should not have been asked to emit this"); 1037 1.1 joerg } 1038 1.1 joerg } 1039 1.1 joerg 1040 1.1 joerg // -fapple-kext mode does not support weak linkage, so we must use 1041 1.1 joerg // internal linkage. 1042 1.1 joerg if (Context.getLangOpts().AppleKext) 1043 1.1 joerg return llvm::Function::InternalLinkage; 1044 1.1 joerg 1045 1.1 joerg llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage = 1046 1.1 joerg llvm::GlobalValue::LinkOnceODRLinkage; 1047 1.1 joerg llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage = 1048 1.1 joerg llvm::GlobalValue::WeakODRLinkage; 1049 1.1 joerg if (RD->hasAttr<DLLExportAttr>()) { 1050 1.1 joerg // Cannot discard exported vtables. 1051 1.1 joerg DiscardableODRLinkage = NonDiscardableODRLinkage; 1052 1.1 joerg } else if (RD->hasAttr<DLLImportAttr>()) { 1053 1.1 joerg // Imported vtables are available externally. 1054 1.1 joerg DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage; 1055 1.1 joerg NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage; 1056 1.1 joerg } 1057 1.1 joerg 1058 1.1 joerg switch (RD->getTemplateSpecializationKind()) { 1059 1.1 joerg case TSK_Undeclared: 1060 1.1 joerg case TSK_ExplicitSpecialization: 1061 1.1 joerg case TSK_ImplicitInstantiation: 1062 1.1 joerg return DiscardableODRLinkage; 1063 1.1 joerg 1064 1.1 joerg case TSK_ExplicitInstantiationDeclaration: 1065 1.1 joerg // Explicit instantiations in MSVC do not provide vtables, so we must emit 1066 1.1 joerg // our own. 1067 1.1 joerg if (getTarget().getCXXABI().isMicrosoft()) 1068 1.1 joerg return DiscardableODRLinkage; 1069 1.1 joerg return shouldEmitAvailableExternallyVTable(*this, RD) 1070 1.1 joerg ? llvm::GlobalVariable::AvailableExternallyLinkage 1071 1.1 joerg : llvm::GlobalVariable::ExternalLinkage; 1072 1.1 joerg 1073 1.1 joerg case TSK_ExplicitInstantiationDefinition: 1074 1.1 joerg return NonDiscardableODRLinkage; 1075 1.1 joerg } 1076 1.1 joerg 1077 1.1 joerg llvm_unreachable("Invalid TemplateSpecializationKind!"); 1078 1.1 joerg } 1079 1.1 joerg 1080 1.1 joerg /// This is a callback from Sema to tell us that a particular vtable is 1081 1.1 joerg /// required to be emitted in this translation unit. 1082 1.1 joerg /// 1083 1.1 joerg /// This is only called for vtables that _must_ be emitted (mainly due to key 1084 1.1 joerg /// functions). For weak vtables, CodeGen tracks when they are needed and 1085 1.1 joerg /// emits them as-needed. 1086 1.1 joerg void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) { 1087 1.1 joerg VTables.GenerateClassData(theClass); 1088 1.1 joerg } 1089 1.1 joerg 1090 1.1 joerg void 1091 1.1 joerg CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) { 1092 1.1 joerg if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) 1093 1.1 joerg DI->completeClassData(RD); 1094 1.1 joerg 1095 1.1 joerg if (RD->getNumVBases()) 1096 1.1 joerg CGM.getCXXABI().emitVirtualInheritanceTables(RD); 1097 1.1 joerg 1098 1.1 joerg CGM.getCXXABI().emitVTableDefinitions(*this, RD); 1099 1.1 joerg } 1100 1.1 joerg 1101 1.1 joerg /// At this point in the translation unit, does it appear that can we 1102 1.1 joerg /// rely on the vtable being defined elsewhere in the program? 1103 1.1 joerg /// 1104 1.1 joerg /// The response is really only definitive when called at the end of 1105 1.1 joerg /// the translation unit. 1106 1.1 joerg /// 1107 1.1 joerg /// The only semantic restriction here is that the object file should 1108 1.1 joerg /// not contain a vtable definition when that vtable is defined 1109 1.1 joerg /// strongly elsewhere. Otherwise, we'd just like to avoid emitting 1110 1.1 joerg /// vtables when unnecessary. 1111 1.1 joerg bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) { 1112 1.1 joerg assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable."); 1113 1.1 joerg 1114 1.1 joerg // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't 1115 1.1 joerg // emit them even if there is an explicit template instantiation. 1116 1.1 joerg if (CGM.getTarget().getCXXABI().isMicrosoft()) 1117 1.1 joerg return false; 1118 1.1 joerg 1119 1.1 joerg // If we have an explicit instantiation declaration (and not a 1120 1.1 joerg // definition), the vtable is defined elsewhere. 1121 1.1 joerg TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind(); 1122 1.1 joerg if (TSK == TSK_ExplicitInstantiationDeclaration) 1123 1.1 joerg return true; 1124 1.1 joerg 1125 1.1 joerg // Otherwise, if the class is an instantiated template, the 1126 1.1 joerg // vtable must be defined here. 1127 1.1 joerg if (TSK == TSK_ImplicitInstantiation || 1128 1.1 joerg TSK == TSK_ExplicitInstantiationDefinition) 1129 1.1 joerg return false; 1130 1.1 joerg 1131 1.1 joerg // Otherwise, if the class doesn't have a key function (possibly 1132 1.1 joerg // anymore), the vtable must be defined here. 1133 1.1 joerg const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD); 1134 1.1 joerg if (!keyFunction) 1135 1.1 joerg return false; 1136 1.1 joerg 1137 1.1 joerg // Otherwise, if we don't have a definition of the key function, the 1138 1.1 joerg // vtable must be defined somewhere else. 1139 1.1 joerg return !keyFunction->hasBody(); 1140 1.1 joerg } 1141 1.1 joerg 1142 1.1 joerg /// Given that we're currently at the end of the translation unit, and 1143 1.1 joerg /// we've emitted a reference to the vtable for this class, should 1144 1.1 joerg /// we define that vtable? 1145 1.1 joerg static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM, 1146 1.1 joerg const CXXRecordDecl *RD) { 1147 1.1 joerg // If vtable is internal then it has to be done. 1148 1.1 joerg if (!CGM.getVTables().isVTableExternal(RD)) 1149 1.1 joerg return true; 1150 1.1 joerg 1151 1.1 joerg // If it's external then maybe we will need it as available_externally. 1152 1.1 joerg return shouldEmitAvailableExternallyVTable(CGM, RD); 1153 1.1 joerg } 1154 1.1 joerg 1155 1.1 joerg /// Given that at some point we emitted a reference to one or more 1156 1.1 joerg /// vtables, and that we are now at the end of the translation unit, 1157 1.1 joerg /// decide whether we should emit them. 1158 1.1 joerg void CodeGenModule::EmitDeferredVTables() { 1159 1.1 joerg #ifndef NDEBUG 1160 1.1 joerg // Remember the size of DeferredVTables, because we're going to assume 1161 1.1 joerg // that this entire operation doesn't modify it. 1162 1.1 joerg size_t savedSize = DeferredVTables.size(); 1163 1.1 joerg #endif 1164 1.1 joerg 1165 1.1 joerg for (const CXXRecordDecl *RD : DeferredVTables) 1166 1.1 joerg if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD)) 1167 1.1 joerg VTables.GenerateClassData(RD); 1168 1.1 joerg else if (shouldOpportunisticallyEmitVTables()) 1169 1.1 joerg OpportunisticVTables.push_back(RD); 1170 1.1 joerg 1171 1.1 joerg assert(savedSize == DeferredVTables.size() && 1172 1.1 joerg "deferred extra vtables during vtable emission?"); 1173 1.1 joerg DeferredVTables.clear(); 1174 1.1 joerg } 1175 1.1 joerg 1176 1.1.1.2 joerg bool CodeGenModule::HasLTOVisibilityPublicStd(const CXXRecordDecl *RD) { 1177 1.1.1.2 joerg if (!getCodeGenOpts().LTOVisibilityPublicStd) 1178 1.1.1.2 joerg return false; 1179 1.1.1.2 joerg 1180 1.1.1.2 joerg const DeclContext *DC = RD; 1181 1.1.1.2 joerg while (1) { 1182 1.1.1.2 joerg auto *D = cast<Decl>(DC); 1183 1.1.1.2 joerg DC = DC->getParent(); 1184 1.1.1.2 joerg if (isa<TranslationUnitDecl>(DC->getRedeclContext())) { 1185 1.1.1.2 joerg if (auto *ND = dyn_cast<NamespaceDecl>(D)) 1186 1.1.1.2 joerg if (const IdentifierInfo *II = ND->getIdentifier()) 1187 1.1.1.2 joerg if (II->isStr("std") || II->isStr("stdext")) 1188 1.1.1.2 joerg return true; 1189 1.1.1.2 joerg break; 1190 1.1.1.2 joerg } 1191 1.1.1.2 joerg } 1192 1.1.1.2 joerg 1193 1.1.1.2 joerg return false; 1194 1.1.1.2 joerg } 1195 1.1.1.2 joerg 1196 1.1 joerg bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) { 1197 1.1 joerg LinkageInfo LV = RD->getLinkageAndVisibility(); 1198 1.1 joerg if (!isExternallyVisible(LV.getLinkage())) 1199 1.1 joerg return true; 1200 1.1 joerg 1201 1.1 joerg if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>()) 1202 1.1 joerg return false; 1203 1.1 joerg 1204 1.1 joerg if (getTriple().isOSBinFormatCOFF()) { 1205 1.1 joerg if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>()) 1206 1.1 joerg return false; 1207 1.1 joerg } else { 1208 1.1 joerg if (LV.getVisibility() != HiddenVisibility) 1209 1.1 joerg return false; 1210 1.1 joerg } 1211 1.1 joerg 1212 1.1.1.2 joerg return !HasLTOVisibilityPublicStd(RD); 1213 1.1 joerg } 1214 1.1 joerg 1215 1.1.1.2 joerg llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel( 1216 1.1.1.2 joerg const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) { 1217 1.1.1.2 joerg // If we have already visited this RD (which means this is a recursive call 1218 1.1.1.2 joerg // since the initial call should have an empty Visited set), return the max 1219 1.1.1.2 joerg // visibility. The recursive calls below compute the min between the result 1220 1.1.1.2 joerg // of the recursive call and the current TypeVis, so returning the max here 1221 1.1.1.2 joerg // ensures that it will have no effect on the current TypeVis. 1222 1.1.1.2 joerg if (!Visited.insert(RD).second) 1223 1.1.1.2 joerg return llvm::GlobalObject::VCallVisibilityTranslationUnit; 1224 1.1.1.2 joerg 1225 1.1 joerg LinkageInfo LV = RD->getLinkageAndVisibility(); 1226 1.1 joerg llvm::GlobalObject::VCallVisibility TypeVis; 1227 1.1 joerg if (!isExternallyVisible(LV.getLinkage())) 1228 1.1 joerg TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit; 1229 1.1 joerg else if (HasHiddenLTOVisibility(RD)) 1230 1.1 joerg TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit; 1231 1.1 joerg else 1232 1.1 joerg TypeVis = llvm::GlobalObject::VCallVisibilityPublic; 1233 1.1 joerg 1234 1.1 joerg for (auto B : RD->bases()) 1235 1.1 joerg if (B.getType()->getAsCXXRecordDecl()->isDynamicClass()) 1236 1.1.1.2 joerg TypeVis = std::min( 1237 1.1.1.2 joerg TypeVis, 1238 1.1.1.2 joerg GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited)); 1239 1.1 joerg 1240 1.1 joerg for (auto B : RD->vbases()) 1241 1.1 joerg if (B.getType()->getAsCXXRecordDecl()->isDynamicClass()) 1242 1.1.1.2 joerg TypeVis = std::min( 1243 1.1.1.2 joerg TypeVis, 1244 1.1.1.2 joerg GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited)); 1245 1.1 joerg 1246 1.1 joerg return TypeVis; 1247 1.1 joerg } 1248 1.1 joerg 1249 1.1 joerg void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD, 1250 1.1 joerg llvm::GlobalVariable *VTable, 1251 1.1 joerg const VTableLayout &VTLayout) { 1252 1.1 joerg if (!getCodeGenOpts().LTOUnit) 1253 1.1 joerg return; 1254 1.1 joerg 1255 1.1 joerg CharUnits PointerWidth = 1256 1.1 joerg Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 1257 1.1 joerg 1258 1.1 joerg typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint; 1259 1.1 joerg std::vector<AddressPoint> AddressPoints; 1260 1.1 joerg for (auto &&AP : VTLayout.getAddressPoints()) 1261 1.1 joerg AddressPoints.push_back(std::make_pair( 1262 1.1 joerg AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) + 1263 1.1 joerg AP.second.AddressPointIndex)); 1264 1.1 joerg 1265 1.1 joerg // Sort the address points for determinism. 1266 1.1 joerg llvm::sort(AddressPoints, [this](const AddressPoint &AP1, 1267 1.1 joerg const AddressPoint &AP2) { 1268 1.1 joerg if (&AP1 == &AP2) 1269 1.1 joerg return false; 1270 1.1 joerg 1271 1.1 joerg std::string S1; 1272 1.1 joerg llvm::raw_string_ostream O1(S1); 1273 1.1 joerg getCXXABI().getMangleContext().mangleTypeName( 1274 1.1 joerg QualType(AP1.first->getTypeForDecl(), 0), O1); 1275 1.1 joerg O1.flush(); 1276 1.1 joerg 1277 1.1 joerg std::string S2; 1278 1.1 joerg llvm::raw_string_ostream O2(S2); 1279 1.1 joerg getCXXABI().getMangleContext().mangleTypeName( 1280 1.1 joerg QualType(AP2.first->getTypeForDecl(), 0), O2); 1281 1.1 joerg O2.flush(); 1282 1.1 joerg 1283 1.1 joerg if (S1 < S2) 1284 1.1 joerg return true; 1285 1.1 joerg if (S1 != S2) 1286 1.1 joerg return false; 1287 1.1 joerg 1288 1.1 joerg return AP1.second < AP2.second; 1289 1.1 joerg }); 1290 1.1 joerg 1291 1.1 joerg ArrayRef<VTableComponent> Comps = VTLayout.vtable_components(); 1292 1.1 joerg for (auto AP : AddressPoints) { 1293 1.1 joerg // Create type metadata for the address point. 1294 1.1 joerg AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first); 1295 1.1 joerg 1296 1.1 joerg // The class associated with each address point could also potentially be 1297 1.1 joerg // used for indirect calls via a member function pointer, so we need to 1298 1.1 joerg // annotate the address of each function pointer with the appropriate member 1299 1.1 joerg // function pointer type. 1300 1.1 joerg for (unsigned I = 0; I != Comps.size(); ++I) { 1301 1.1 joerg if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer) 1302 1.1 joerg continue; 1303 1.1 joerg llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType( 1304 1.1 joerg Context.getMemberPointerType( 1305 1.1 joerg Comps[I].getFunctionDecl()->getType(), 1306 1.1 joerg Context.getRecordType(AP.first).getTypePtr())); 1307 1.1 joerg VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD); 1308 1.1 joerg } 1309 1.1 joerg } 1310 1.1 joerg 1311 1.1.1.2 joerg if (getCodeGenOpts().VirtualFunctionElimination || 1312 1.1.1.2 joerg getCodeGenOpts().WholeProgramVTables) { 1313 1.1.1.2 joerg llvm::DenseSet<const CXXRecordDecl *> Visited; 1314 1.1.1.2 joerg llvm::GlobalObject::VCallVisibility TypeVis = 1315 1.1.1.2 joerg GetVCallVisibilityLevel(RD, Visited); 1316 1.1 joerg if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic) 1317 1.1.1.2 joerg VTable->setVCallVisibilityMetadata(TypeVis); 1318 1.1 joerg } 1319 1.1 joerg } 1320