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