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