clang  9.0.0svn
CGVTables.cpp
Go to the documentation of this file.
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"
17 #include "clang/AST/RecordLayout.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 
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 
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 *
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.
267  CXXThisValue = CXXABIThisValue;
268  CurCodeDecl = MD;
269  CurFuncDecl = MD;
270 }
271 
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::FunctionCallee Callee,
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, Callee);
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), 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  RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
358  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 
377  llvm::Value *AdjustedThisPtr,
378  llvm::FunctionCallee Callee) {
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'.
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(Callee, 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(Callee.getCallee()->getName(), *CurFnInfo, GD,
414  Attrs, 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(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
453  &Thunk, IsUnprototyped);
454 }
455 
457  bool IsUnprototyped, bool ForVTable) {
458  // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
459  // provide thunks for us.
460  if (CGM.getTarget().getCXXABI().isMicrosoft())
461  return true;
462 
463  // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
464  // definitions of the main method. Therefore, emitting thunks with the vtable
465  // is purely an optimization. Emit the thunk if optimizations are enabled and
466  // all of the parameter types are complete.
467  if (ForVTable)
468  return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
469 
470  // Always emit thunks along with the method definition.
471  return true;
472 }
473 
474 llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
475  const ThunkInfo &TI,
476  bool ForVTable) {
477  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
478 
479  // First, get a declaration. Compute the mangled name. Don't worry about
480  // getting the function prototype right, since we may only need this
481  // declaration to fill in a vtable slot.
482  SmallString<256> Name;
483  MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
484  llvm::raw_svector_ostream Out(Name);
485  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
486  MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
487  else
488  MCtx.mangleThunk(MD, TI, Out);
489  llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
490  llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
491 
492  // If we don't need to emit a definition, return this declaration as is.
493  bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
494  MD->getType()->castAs<FunctionType>());
495  if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
496  return Thunk;
497 
498  // Arrange a function prototype appropriate for a function definition. In some
499  // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
500  const CGFunctionInfo &FnInfo =
501  IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
503  llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
504 
505  // If the type of the underlying GlobalValue is wrong, we'll have to replace
506  // it. It should be a declaration.
507  llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
508  if (ThunkFn->getFunctionType() != ThunkFnTy) {
509  llvm::GlobalValue *OldThunkFn = ThunkFn;
510 
511  assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
512 
513  // Remove the name from the old thunk function and get a new thunk.
514  OldThunkFn->setName(StringRef());
516  Name.str(), &CGM.getModule());
517  CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
518 
519  // If needed, replace the old thunk with a bitcast.
520  if (!OldThunkFn->use_empty()) {
521  llvm::Constant *NewPtrForOldDecl =
522  llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
523  OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
524  }
525 
526  // Remove the old thunk.
527  OldThunkFn->eraseFromParent();
528  }
529 
530  bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
531  bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
532 
533  if (!ThunkFn->isDeclaration()) {
534  if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
535  // There is already a thunk emitted for this function, do nothing.
536  return ThunkFn;
537  }
538 
539  setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
540  return ThunkFn;
541  }
542 
543  // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
544  // that the return type is meaningless. These thunks can be used to call
545  // functions with differing return types, and the caller is required to cast
546  // the prototype appropriately to extract the correct value.
547  if (IsUnprototyped)
548  ThunkFn->addFnAttr("thunk");
549 
551 
552  if (!IsUnprototyped && ThunkFn->isVarArg()) {
553  // Varargs thunks are special; we can't just generate a call because
554  // we can't copy the varargs. Our implementation is rather
555  // expensive/sucky at the moment, so don't generate the thunk unless
556  // we have to.
557  // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
558  if (UseAvailableExternallyLinkage)
559  return ThunkFn;
560  ThunkFn = CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD,
561  TI);
562  } else {
563  // Normal thunk body generation.
564  CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
565  }
566 
567  setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
568  return ThunkFn;
569 }
570 
572  const CXXMethodDecl *MD =
573  cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
574 
575  // We don't need to generate thunks for the base destructor.
576  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
577  return;
578 
579  const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
580  VTContext->getThunkInfo(GD);
581 
582  if (!ThunkInfoVector)
583  return;
584 
585  for (const ThunkInfo& Thunk : *ThunkInfoVector)
586  maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
587 }
588 
589 void CodeGenVTables::addVTableComponent(
590  ConstantArrayBuilder &builder, const VTableLayout &layout,
591  unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
592  auto &component = layout.vtable_components()[idx];
593 
594  auto addOffsetConstant = [&](CharUnits offset) {
595  builder.add(llvm::ConstantExpr::getIntToPtr(
596  llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
597  CGM.Int8PtrTy));
598  };
599 
600  switch (component.getKind()) {
602  return addOffsetConstant(component.getVCallOffset());
603 
605  return addOffsetConstant(component.getVBaseOffset());
606 
608  return addOffsetConstant(component.getOffsetToTop());
609 
611  return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
612 
616  GlobalDecl GD;
617 
618  // Get the right global decl.
619  switch (component.getKind()) {
620  default:
621  llvm_unreachable("Unexpected vtable component kind");
623  GD = component.getFunctionDecl();
624  break;
626  GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
627  break;
629  GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
630  break;
631  }
632 
633  if (CGM.getLangOpts().CUDA) {
634  // Emit NULL for methods we can't codegen on this
635  // side. Otherwise we'd end up with vtable with unresolved
636  // references.
637  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
638  // OK on device side: functions w/ __device__ attribute
639  // OK on host side: anything except __device__-only functions.
640  bool CanEmitMethod =
641  CGM.getLangOpts().CUDAIsDevice
642  ? MD->hasAttr<CUDADeviceAttr>()
643  : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
644  if (!CanEmitMethod)
645  return builder.addNullPointer(CGM.Int8PtrTy);
646  // Method is acceptable, continue processing as usual.
647  }
648 
649  auto getSpecialVirtualFn = [&](StringRef name) {
650  llvm::FunctionType *fnTy =
651  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
652  llvm::Constant *fn = cast<llvm::Constant>(
653  CGM.CreateRuntimeFunction(fnTy, name).getCallee());
654  if (auto f = dyn_cast<llvm::Function>(fn))
655  f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
656  return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
657  };
658 
659  llvm::Constant *fnPtr;
660 
661  // Pure virtual member functions.
662  if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
663  if (!PureVirtualFn)
664  PureVirtualFn =
665  getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
666  fnPtr = PureVirtualFn;
667 
668  // Deleted virtual member functions.
669  } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
670  if (!DeletedVirtualFn)
671  DeletedVirtualFn =
672  getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
673  fnPtr = DeletedVirtualFn;
674 
675  // Thunks.
676  } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
677  layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
678  auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
679 
680  nextVTableThunkIndex++;
681  fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
682 
683  // Otherwise we can use the method definition directly.
684  } else {
685  llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
686  fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
687  }
688 
689  fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
690  builder.add(fnPtr);
691  return;
692  }
693 
695  return builder.addNullPointer(CGM.Int8PtrTy);
696  }
697 
698  llvm_unreachable("Unexpected vtable component kind");
699 }
700 
703  for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
704  tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
705  }
706 
707  return llvm::StructType::get(CGM.getLLVMContext(), tys);
708 }
709 
711  const VTableLayout &layout,
712  llvm::Constant *rtti) {
713  unsigned nextVTableThunkIndex = 0;
714  for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
715  auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
716  size_t thisIndex = layout.getVTableOffset(i);
717  size_t nextIndex = thisIndex + layout.getVTableSize(i);
718  for (unsigned i = thisIndex; i != nextIndex; ++i) {
719  addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
720  }
721  vtableElem.finishAndAddTo(builder);
722  }
723 }
724 
725 llvm::GlobalVariable *
727  const BaseSubobject &Base,
728  bool BaseIsVirtual,
729  llvm::GlobalVariable::LinkageTypes Linkage,
730  VTableAddressPointsMapTy& AddressPoints) {
731  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
732  DI->completeClassData(Base.getBase());
733 
734  std::unique_ptr<VTableLayout> VTLayout(
735  getItaniumVTableContext().createConstructionVTableLayout(
736  Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
737 
738  // Add the address points.
739  AddressPoints = VTLayout->getAddressPoints();
740 
741  // Get the mangled construction vtable name.
742  SmallString<256> OutName;
743  llvm::raw_svector_ostream Out(OutName);
744  cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
745  .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
746  Base.getBase(), Out);
747  StringRef Name = OutName.str();
748 
749  llvm::Type *VTType = getVTableType(*VTLayout);
750 
751  // Construction vtable symbols are not part of the Itanium ABI, so we cannot
752  // guarantee that they actually will be available externally. Instead, when
753  // emitting an available_externally VTT, we provide references to an internal
754  // linkage construction vtable. The ABI only requires complete-object vtables
755  // to be the same for all instances of a type, not construction vtables.
756  if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
758 
759  unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
760 
761  // Create the variable that will hold the construction vtable.
762  llvm::GlobalVariable *VTable =
763  CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
764 
765  // V-tables are always unnamed_addr.
766  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
767 
768  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
769  CGM.getContext().getTagDeclType(Base.getBase()));
770 
771  // Create and set the initializer.
772  ConstantInitBuilder builder(CGM);
773  auto components = builder.beginStruct();
774  createVTableInitializer(components, *VTLayout, RTTI);
775  components.finishAndSetAsInitializer(VTable);
776 
777  // Set properties only after the initializer has been set to ensure that the
778  // GV is treated as definition and not declaration.
779  assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
780  CGM.setGVProperties(VTable, RD);
781 
782  CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
783 
784  return VTable;
785 }
786 
788  const CXXRecordDecl *RD) {
789  return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
791 }
792 
793 /// Compute the required linkage of the vtable for the given class.
794 ///
795 /// Note that we only call this at the end of the translation unit.
796 llvm::GlobalVariable::LinkageTypes
798  if (!RD->isExternallyVisible())
800 
801  // We're at the end of the translation unit, so the current key
802  // function is fully correct.
803  const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
804  if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
805  // If this class has a key function, use that to determine the
806  // linkage of the vtable.
807  const FunctionDecl *def = nullptr;
808  if (keyFunction->hasBody(def))
809  keyFunction = cast<CXXMethodDecl>(def);
810 
811  switch (keyFunction->getTemplateSpecializationKind()) {
812  case TSK_Undeclared:
814  assert((def || CodeGenOpts.OptimizationLevel > 0 ||
815  CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
816  "Shouldn't query vtable linkage without key function, "
817  "optimizations, or debug info");
818  if (!def && CodeGenOpts.OptimizationLevel > 0)
819  return llvm::GlobalVariable::AvailableExternallyLinkage;
820 
821  if (keyFunction->isInlined())
822  return !Context.getLangOpts().AppleKext ?
823  llvm::GlobalVariable::LinkOnceODRLinkage :
825 
827 
829  return !Context.getLangOpts().AppleKext ?
830  llvm::GlobalVariable::LinkOnceODRLinkage :
832 
834  return !Context.getLangOpts().AppleKext ?
835  llvm::GlobalVariable::WeakODRLinkage :
837 
839  llvm_unreachable("Should not have been asked to emit this");
840  }
841  }
842 
843  // -fapple-kext mode does not support weak linkage, so we must use
844  // internal linkage.
845  if (Context.getLangOpts().AppleKext)
847 
848  llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
849  llvm::GlobalValue::LinkOnceODRLinkage;
850  llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
851  llvm::GlobalValue::WeakODRLinkage;
852  if (RD->hasAttr<DLLExportAttr>()) {
853  // Cannot discard exported vtables.
854  DiscardableODRLinkage = NonDiscardableODRLinkage;
855  } else if (RD->hasAttr<DLLImportAttr>()) {
856  // Imported vtables are available externally.
857  DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
858  NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
859  }
860 
861  switch (RD->getTemplateSpecializationKind()) {
862  case TSK_Undeclared:
865  return DiscardableODRLinkage;
866 
868  // Explicit instantiations in MSVC do not provide vtables, so we must emit
869  // our own.
870  if (getTarget().getCXXABI().isMicrosoft())
871  return DiscardableODRLinkage;
872  return shouldEmitAvailableExternallyVTable(*this, RD)
873  ? llvm::GlobalVariable::AvailableExternallyLinkage
875 
877  return NonDiscardableODRLinkage;
878  }
879 
880  llvm_unreachable("Invalid TemplateSpecializationKind!");
881 }
882 
883 /// This is a callback from Sema to tell us that a particular vtable is
884 /// required to be emitted in this translation unit.
885 ///
886 /// This is only called for vtables that _must_ be emitted (mainly due to key
887 /// functions). For weak vtables, CodeGen tracks when they are needed and
888 /// emits them as-needed.
890  VTables.GenerateClassData(theClass);
891 }
892 
893 void
895  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
896  DI->completeClassData(RD);
897 
898  if (RD->getNumVBases())
900 
901  CGM.getCXXABI().emitVTableDefinitions(*this, RD);
902 }
903 
904 /// At this point in the translation unit, does it appear that can we
905 /// rely on the vtable being defined elsewhere in the program?
906 ///
907 /// The response is really only definitive when called at the end of
908 /// the translation unit.
909 ///
910 /// The only semantic restriction here is that the object file should
911 /// not contain a vtable definition when that vtable is defined
912 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
913 /// vtables when unnecessary.
915  assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
916 
917  // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
918  // emit them even if there is an explicit template instantiation.
919  if (CGM.getTarget().getCXXABI().isMicrosoft())
920  return false;
921 
922  // If we have an explicit instantiation declaration (and not a
923  // definition), the vtable is defined elsewhere.
926  return true;
927 
928  // Otherwise, if the class is an instantiated template, the
929  // vtable must be defined here.
930  if (TSK == TSK_ImplicitInstantiation ||
932  return false;
933 
934  // Otherwise, if the class doesn't have a key function (possibly
935  // anymore), the vtable must be defined here.
936  const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
937  if (!keyFunction)
938  return false;
939 
940  // Otherwise, if we don't have a definition of the key function, the
941  // vtable must be defined somewhere else.
942  return !keyFunction->hasBody();
943 }
944 
945 /// Given that we're currently at the end of the translation unit, and
946 /// we've emitted a reference to the vtable for this class, should
947 /// we define that vtable?
949  const CXXRecordDecl *RD) {
950  // If vtable is internal then it has to be done.
951  if (!CGM.getVTables().isVTableExternal(RD))
952  return true;
953 
954  // If it's external then maybe we will need it as available_externally.
955  return shouldEmitAvailableExternallyVTable(CGM, RD);
956 }
957 
958 /// Given that at some point we emitted a reference to one or more
959 /// vtables, and that we are now at the end of the translation unit,
960 /// decide whether we should emit them.
961 void CodeGenModule::EmitDeferredVTables() {
962 #ifndef NDEBUG
963  // Remember the size of DeferredVTables, because we're going to assume
964  // that this entire operation doesn't modify it.
965  size_t savedSize = DeferredVTables.size();
966 #endif
967 
968  for (const CXXRecordDecl *RD : DeferredVTables)
970  VTables.GenerateClassData(RD);
971  else if (shouldOpportunisticallyEmitVTables())
972  OpportunisticVTables.push_back(RD);
973 
974  assert(savedSize == DeferredVTables.size() &&
975  "deferred extra vtables during vtable emission?");
976  DeferredVTables.clear();
977 }
978 
981  if (!isExternallyVisible(LV.getLinkage()))
982  return true;
983 
984  if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
985  return false;
986 
987  if (getTriple().isOSBinFormatCOFF()) {
988  if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
989  return false;
990  } else {
991  if (LV.getVisibility() != HiddenVisibility)
992  return false;
993  }
994 
995  if (getCodeGenOpts().LTOVisibilityPublicStd) {
996  const DeclContext *DC = RD;
997  while (1) {
998  auto *D = cast<Decl>(DC);
999  DC = DC->getParent();
1000  if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1001  if (auto *ND = dyn_cast<NamespaceDecl>(D))
1002  if (const IdentifierInfo *II = ND->getIdentifier())
1003  if (II->isStr("std") || II->isStr("stdext"))
1004  return false;
1005  break;
1006  }
1007  }
1008  }
1009 
1010  return true;
1011 }
1012 
1013 void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1014  const VTableLayout &VTLayout) {
1015  if (!getCodeGenOpts().LTOUnit)
1016  return;
1017 
1018  CharUnits PointerWidth =
1019  Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1020 
1021  typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1022  std::vector<AddressPoint> AddressPoints;
1023  for (auto &&AP : VTLayout.getAddressPoints())
1024  AddressPoints.push_back(std::make_pair(
1025  AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1026  AP.second.AddressPointIndex));
1027 
1028  // Sort the address points for determinism.
1029  llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1030  const AddressPoint &AP2) {
1031  if (&AP1 == &AP2)
1032  return false;
1033 
1034  std::string S1;
1035  llvm::raw_string_ostream O1(S1);
1036  getCXXABI().getMangleContext().mangleTypeName(
1037  QualType(AP1.first->getTypeForDecl(), 0), O1);
1038  O1.flush();
1039 
1040  std::string S2;
1041  llvm::raw_string_ostream O2(S2);
1042  getCXXABI().getMangleContext().mangleTypeName(
1043  QualType(AP2.first->getTypeForDecl(), 0), O2);
1044  O2.flush();
1045 
1046  if (S1 < S2)
1047  return true;
1048  if (S1 != S2)
1049  return false;
1050 
1051  return AP1.second < AP2.second;
1052  });
1053 
1054  ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1055  for (auto AP : AddressPoints) {
1056  // Create type metadata for the address point.
1057  AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1058 
1059  // The class associated with each address point could also potentially be
1060  // used for indirect calls via a member function pointer, so we need to
1061  // annotate the address of each function pointer with the appropriate member
1062  // function pointer type.
1063  for (unsigned I = 0; I != Comps.size(); ++I) {
1064  if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1065  continue;
1066  llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1067  Context.getMemberPointerType(
1068  Comps[I].getFunctionDecl()->getType(),
1069  Context.getRecordType(AP.first).getTypePtr()));
1070  VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1071  }
1072  }
1073 }
const llvm::DataLayout & getDataLayout() const
size_t getNumVTables() const
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:363
static const Decl * getCanonicalDecl(const Decl *D)
Represents a function declaration or definition.
Definition: Decl.h:1748
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:59
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
CanQualType VoidPtrTy
Definition: ASTContext.h:1039
A (possibly-)qualified type.
Definition: Type.h:643
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses &#39;sret&#39; when used as a return type.
Definition: CGCall.cpp:1497
const CodeGenOptions & getCodeGenOpts() const
const AddressPointsMapTy & getAddressPoints() const
virtual void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType)
Definition: CGCXXABI.cpp:156
llvm::LLVMContext & getLLVMContext()
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:83
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
The standard implementation of ConstantInitBuilder used in Clang.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition: CGClass.cpp:36
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3372
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:838
QualType getThisType() const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:2253
bool isEmpty() const
Definition: ABI.h:86
virtual const ThunkInfoVectorTy * getThunkInfo(GlobalDecl GD)
virtual llvm::Value * performThisAdjustment(CodeGenFunction &CGF, Address This, const ThisAdjustment &TA)=0
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
virtual StringRef GetDeletedVirtualCallName()=0
Gets the deleted virtual member call name.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
llvm::Function * GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:156
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i...
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
Definition: CGVTables.cpp:979
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr or CxxCtorInitializer) selects the name&#39;s to...
void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo, bool IsUnprototyped)
Definition: CGVTables.cpp:224
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:36
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6818
Visibility getVisibility() const
Definition: Visibility.h:84
CGDebugInfo * getModuleDebugInfo()
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
llvm::Value * getPointer() const
Definition: Address.h:37
Represents a parameter to a function.
Definition: Decl.h:1564
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:23
long i
Definition: xmmintrin.h:1456
void add(RValue rvalue, QualType type)
Definition: CGCall.h:287
CharUnits getBaseOffset() const
getBaseOffset - Returns the base class offset.
Definition: BaseSubobject.h:46
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:358
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1052
void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk, bool IsUnprototyped)
Generate a thunk for the given method.
Definition: CGVTables.cpp:429
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM, const CXXRecordDecl *RD)
Definition: CGVTables.cpp:787
bool isReferenceType() const
Definition: Type.h:6363
static void resolveTopLevelMetadata(llvm::Function *Fn, llvm::ValueToValueMapTy &VMap)
This function clones a function&#39;s DISubprogram node and enters it into a value map with the intent th...
Definition: CGVTables.cpp:117
llvm::Type * getVTableType(const VTableLayout &layout)
Returns the type of a vtable with the given layout.
Definition: CGVTables.cpp:701
The this pointer adjustment as well as an optional return adjustment for a thunk. ...
Definition: ABI.h:178
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:728
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2289
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
ArrayRef< VTableComponent > vtable_components() const
virtual void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD)=0
Emits the VTable definitions required for the given record type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
Deleting dtor.
Definition: ABI.h:34
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:108
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6197
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition: CGCall.cpp:1817
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it&#39;s possible to emit a vtable for RD, even though we do not know that the vtable h...
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6127
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
ItaniumVTableContext & getItaniumVTableContext()
Definition: CGVTables.h:78
static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD, bool IsUnprototyped, bool ForVTable)
Definition: CGVTables.cpp:456
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:512
param_iterator param_begin()
Definition: Decl.h:2301
bool hasAttr() const
Definition: DeclBase.h:542
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1636
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3704
bool isDynamicClass() const
Definition: DeclCXX.h:789
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1654
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:178
bool isVTableExternal(const CXXRecordDecl *RD)
At this point in the translation unit, does it appear that can we rely on the vtable being defined el...
Definition: CGVTables.cpp:914
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns &#39;th...
Definition: CGCXXABI.h:106
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:226
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk, llvm::Function *ThunkFn, bool ForVTable, GlobalDecl GD)
Definition: CGVTables.cpp:39
static bool similar(const ABIArgInfo &infoL, CanQualType typeL, const ABIArgInfo &infoR, CanQualType typeR)
Definition: CGVTables.cpp:59
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6883
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:133
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2825
virtual bool exportThunk()=0
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
virtual StringRef GetPureVirtualCallName()=0
Gets the pure virtual member call function.
Linkage getLinkage() const
Definition: Visibility.h:83
const CXXRecordDecl * getBase() const
getBase - Returns the base class declaration.
Definition: BaseSubobject.h:43
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2772
Base object dtor.
Definition: ABI.h:36
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes &#39;this&#39; as the first parameter followed by varargs.
Definition: CGCall.cpp:529
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1772
void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, const ThunkInfo *Thunk, bool IsUnprototyped)
Definition: CGVTables.cpp:281
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:85
QualType getRecordType(const RecordDecl *Decl) const
const TargetInfo & getTarget() const
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:180
const LangOptions & getLangOpts() const
ASTContext & getContext() const
virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, CallArgList &CallArgs)
Definition: CGCXXABI.h:430
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:264
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:40
The l-value was considered opaque, so the alignment was determined from a type.
ArrayRef< VTableThunkTy > vtable_thunks() const
virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, const ThisAdjustment &ThisAdjustment, raw_ostream &)=0
llvm::Constant * GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, GlobalDecl GD)
Get the address of the thunk for the given global decl.
Definition: CGVTables.cpp:33
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3630
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
const Decl * getDecl() const
Definition: GlobalDecl.h:76
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:43
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2109
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
CodeGenVTables(CodeGenModule &CGM)
Definition: CGVTables.cpp:30
CanQualType VoidTy
Definition: ASTContext.h:1011
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti)
Add vtable components for the given vtable layout to the given global initializer.
Definition: CGVTables.cpp:710
An aligned address.
Definition: Address.h:24
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD)=0
Emit any tables needed to implement virtual inheritance.
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:96
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:192
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:177
Complete object dtor.
Definition: ABI.h:35
llvm::GlobalVariable * GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual, llvm::GlobalVariable::LinkageTypes Linkage, VTableAddressPointsMapTy &AddressPoints)
GenerateConstructionVTable - Generate a construction vtable for the given base subobject.
Definition: CGVTables.cpp:726
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:358
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:58
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn&#39;t support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
ThisAdjustment This
The this pointer adjustment.
Definition: ABI.h:180
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3638
void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable, const VTableLayout &VTLayout)
Emit type metadata for the given vtable using the given layout.
Definition: CGVTables.cpp:1013
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:188
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2232
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for &#39;this&#39;.
Definition: CGCXXABI.cpp:121
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:174
llvm::Module & getModule() const
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
Definition: CGVTables.cpp:571
param_iterator param_end()
Definition: Decl.h:2302
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class...
Definition: CGVTables.cpp:797
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition: Decl.cpp:1093
StructBuilder beginStruct(llvm::StructType *structTy=nullptr)
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:184
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM, const CXXRecordDecl *RD)
Given that we&#39;re currently at the end of the translation unit, and we&#39;ve emitted a reference to the v...
Definition: CGVTables.cpp:948
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
Definition: CGVTables.cpp:894
ReturnAdjustment Return
The return adjustment.
Definition: ABI.h:183
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create or return a runtime function declaration with the specified type and name. ...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:450
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2391
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl...
Definition: CGCall.cpp:1669
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:68
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn&#39;t on...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isVoidType() const
Definition: Type.h:6610
virtual void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, raw_ostream &)=0
A helper class of ConstantInitBuilder, used for building constant struct initializers.
size_t getVTableSize(size_t i) const
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:153
A pointer to the deleting destructor.
Definition: VTableBuilder.h:42
CGCXXABI & getCXXABI() const
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, unsigned Alignment)
Will return a global variable of the given type.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:943
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
virtual llvm::Value * performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const ReturnAdjustment &RA)=0
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
Definition: CGDebugInfo.h:745
QualType getType() const
Definition: Decl.h:647
CodeGenVTables & getVTables()
void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, llvm::FunctionCallee Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
Definition: CGVTables.cpp:376
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:262
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:674
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
A pointer to the complete destructor.
Definition: VTableBuilder.h:39
A helper class of ConstantInitBuilder, used for building constant array initializers.
size_t getVTableOffset(size_t i) const
virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment)=0
SourceLocation getLocation() const
Definition: DeclBase.h:429
bool isExternallyVisible() const
Definition: Decl.h:379
void EmitVTable(CXXRecordDecl *Class)
This is a callback from Sema to tell us that a particular vtable is required to be emitted in this tr...
Definition: CGVTables.cpp:889
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1541