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