clang  3.8.0
CGVTables.cpp
Go to the documentation of this file.
1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ code generation of virtual tables.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CodeGenModule.h"
18 #include "clang/AST/RecordLayout.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include <algorithm>
27 #include <cstdio>
28 
29 using namespace clang;
30 using namespace CodeGen;
31 
33  : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
34 
36  const ThunkInfo &Thunk) {
37  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38 
39  // Compute the mangled name.
41  llvm::raw_svector_ostream Out(Name);
42  if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
44  Thunk.This, Out);
45  else
46  getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
47 
49  return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
50  /*DontDefer=*/true, /*IsThunk=*/true);
51 }
52 
53 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
54  const ThunkInfo &Thunk, llvm::Function *Fn) {
55  CGM.setGlobalVisibility(Fn, MD);
56 }
57 
58 static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
59  llvm::Function *ThunkFn, bool ForVTable,
60  GlobalDecl GD) {
61  CGM.setFunctionLinkage(GD, ThunkFn);
62  CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
63  !Thunk.Return.isEmpty());
64 
65  // Set the right visibility.
66  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
67  setThunkVisibility(CGM, MD, Thunk, ThunkFn);
68 
69  if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
70  ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
71 }
72 
73 #ifndef NDEBUG
74 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
75  const ABIArgInfo &infoR, CanQualType typeR) {
76  return (infoL.getKind() == infoR.getKind() &&
77  (typeL == typeR ||
78  (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
79  (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
80 }
81 #endif
82 
84  QualType ResultType, RValue RV,
85  const ThunkInfo &Thunk) {
86  // Emit the return adjustment.
87  bool NullCheckValue = !ResultType->isReferenceType();
88 
89  llvm::BasicBlock *AdjustNull = nullptr;
90  llvm::BasicBlock *AdjustNotNull = nullptr;
91  llvm::BasicBlock *AdjustEnd = nullptr;
92 
93  llvm::Value *ReturnValue = RV.getScalarVal();
94 
95  if (NullCheckValue) {
96  AdjustNull = CGF.createBasicBlock("adjust.null");
97  AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
98  AdjustEnd = CGF.createBasicBlock("adjust.end");
99 
100  llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
101  CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
102  CGF.EmitBlock(AdjustNotNull);
103  }
104 
105  auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
106  auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
107  ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
108  Address(ReturnValue, ClassAlign),
109  Thunk.Return);
110 
111  if (NullCheckValue) {
112  CGF.Builder.CreateBr(AdjustEnd);
113  CGF.EmitBlock(AdjustNull);
114  CGF.Builder.CreateBr(AdjustEnd);
115  CGF.EmitBlock(AdjustEnd);
116 
117  llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
118  PHI->addIncoming(ReturnValue, AdjustNotNull);
119  PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
120  AdjustNull);
121  ReturnValue = PHI;
122  }
123 
124  return RValue::get(ReturnValue);
125 }
126 
127 // This function does roughly the same thing as GenerateThunk, but in a
128 // very different way, so that va_start and va_end work correctly.
129 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
130 // a function, and that there is an alloca built in the entry block
131 // for all accesses to "this".
132 // FIXME: This function assumes there is only one "ret" statement per function.
133 // FIXME: Cloning isn't correct in the presence of indirect goto!
134 // FIXME: This implementation of thunks bloats codesize by duplicating the
135 // function definition. There are alternatives:
136 // 1. Add some sort of stub support to LLVM for cases where we can
137 // do a this adjustment, then a sibcall.
138 // 2. We could transform the definition to take a va_list instead of an
139 // actual variable argument list, then have the thunks (including a
140 // no-op thunk for the regular definition) call va_start/va_end.
141 // There's a bit of per-call overhead for this solution, but it's
142 // better for codesize if the definition is long.
143 llvm::Function *
145  const CGFunctionInfo &FnInfo,
146  GlobalDecl GD, const ThunkInfo &Thunk) {
147  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
148  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
149  QualType ResultType = FPT->getReturnType();
150 
151  // Get the original function
152  assert(FnInfo.isVariadic());
153  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
154  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
155  llvm::Function *BaseFn = cast<llvm::Function>(Callee);
156 
157  // Clone to thunk.
158  llvm::ValueToValueMapTy VMap;
159  llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
160  /*ModuleLevelChanges=*/false);
161  CGM.getModule().getFunctionList().push_back(NewFn);
162  Fn->replaceAllUsesWith(NewFn);
163  NewFn->takeName(Fn);
164  Fn->eraseFromParent();
165  Fn = NewFn;
166 
167  // "Initialize" CGF (minimally).
168  CurFn = Fn;
169 
170  // Get the "this" value
171  llvm::Function::arg_iterator AI = Fn->arg_begin();
172  if (CGM.ReturnTypeUsesSRet(FnInfo))
173  ++AI;
174 
175  // Find the first store of "this", which will be to the alloca associated
176  // with "this".
177  Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
178  llvm::BasicBlock *EntryBB = &Fn->front();
179  llvm::BasicBlock::iterator ThisStore =
180  std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
181  return isa<llvm::StoreInst>(I) &&
182  I.getOperand(0) == ThisPtr.getPointer();
183  });
184  assert(ThisStore != EntryBB->end() &&
185  "Store of this should be in entry block?");
186  // Adjust "this", if necessary.
187  Builder.SetInsertPoint(&*ThisStore);
188  llvm::Value *AdjustedThisPtr =
189  CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
190  ThisStore->setOperand(0, AdjustedThisPtr);
191 
192  if (!Thunk.Return.isEmpty()) {
193  // Fix up the returned value, if necessary.
194  for (llvm::BasicBlock &BB : *Fn) {
195  llvm::Instruction *T = BB.getTerminator();
196  if (isa<llvm::ReturnInst>(T)) {
197  RValue RV = RValue::get(T->getOperand(0));
198  T->eraseFromParent();
199  Builder.SetInsertPoint(&BB);
200  RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
201  Builder.CreateRet(RV.getScalarVal());
202  break;
203  }
204  }
205  }
206 
207  return Fn;
208 }
209 
210 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
211  const CGFunctionInfo &FnInfo) {
212  assert(!CurGD.getDecl() && "CurGD was already set!");
213  CurGD = GD;
214  CurFuncIsThunk = true;
215 
216  // Build FunctionArgs.
217  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
218  QualType ThisType = MD->getThisType(getContext());
219  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
220  QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
221  ? ThisType
224  : FPT->getReturnType();
225  FunctionArgList FunctionArgs;
226 
227  // Create the implicit 'this' parameter declaration.
228  CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
229 
230  // Add the rest of the parameters.
231  FunctionArgs.append(MD->param_begin(), MD->param_end());
232 
233  if (isa<CXXDestructorDecl>(MD))
234  CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
235 
236  // Start defining the function.
237  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
238  MD->getLocation(), MD->getLocation());
239 
240  // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
242  CXXThisValue = CXXABIThisValue;
243  CurCodeDecl = MD;
244  CurFuncDecl = MD;
245 }
246 
248  // Clear these to restore the invariants expected by
249  // StartFunction/FinishFunction.
250  CurCodeDecl = nullptr;
251  CurFuncDecl = nullptr;
252 
253  FinishFunction();
254 }
255 
257  const ThunkInfo *Thunk) {
258  assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
259  "Please use a new CGF for this thunk");
260  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
261 
262  // Adjust the 'this' pointer if necessary
263  llvm::Value *AdjustedThisPtr =
265  *this, LoadCXXThisAddress(), Thunk->This)
266  : LoadCXXThis();
267 
268  if (CurFnInfo->usesInAlloca()) {
269  // We don't handle return adjusting thunks, because they require us to call
270  // the copy constructor. For now, fall through and pretend the return
271  // adjustment was empty so we don't crash.
272  if (Thunk && !Thunk->Return.isEmpty()) {
274  MD, "non-trivial argument copy for return-adjusting thunk");
275  }
276  EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
277  return;
278  }
279 
280  // Start building CallArgs.
281  CallArgList CallArgs;
282  QualType ThisType = MD->getThisType(getContext());
283  CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
284 
285  if (isa<CXXDestructorDecl>(MD))
287 
288  // Add the rest of the arguments.
289  for (const ParmVarDecl *PD : MD->params())
290  EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
291 
292  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
293 
294 #ifndef NDEBUG
295  const CGFunctionInfo &CallFnInfo =
296  CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
298  assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
299  CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
300  CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
301  assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
302  similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
304  assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
305  for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
306  assert(similar(CallFnInfo.arg_begin()[i].info,
307  CallFnInfo.arg_begin()[i].type,
308  CurFnInfo->arg_begin()[i].info,
309  CurFnInfo->arg_begin()[i].type));
310 #endif
311 
312  // Determine whether we have a return value slot to use.
313  QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
314  ? ThisType
317  : FPT->getReturnType();
318  ReturnValueSlot Slot;
319  if (!ResultType->isVoidType() &&
322  Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
323 
324  // Now emit our call.
325  llvm::Instruction *CallOrInvoke;
326  RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
327 
328  // Consider return adjustment if we have ThunkInfo.
329  if (Thunk && !Thunk->Return.isEmpty())
330  RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
331  else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
332  Call->setTailCallKind(llvm::CallInst::TCK_Tail);
333 
334  // Emit return.
335  if (!ResultType->isVoidType() && Slot.isNull())
336  CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
337 
338  // Disable the final ARC autorelease.
339  AutoreleaseResult = false;
340 
341  FinishThunk();
342 }
343 
345  llvm::Value *AdjustedThisPtr,
346  llvm::Value *Callee) {
347  // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
348  // to translate AST arguments into LLVM IR arguments. For thunks, we know
349  // that the caller prototype more or less matches the callee prototype with
350  // the exception of 'this'.
352  for (llvm::Argument &A : CurFn->args())
353  Args.push_back(&A);
354 
355  // Set the adjusted 'this' pointer.
356  const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
357  if (ThisAI.isDirect()) {
358  const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
359  int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
360  llvm::Type *ThisType = Args[ThisArgNo]->getType();
361  if (ThisType != AdjustedThisPtr->getType())
362  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
363  Args[ThisArgNo] = AdjustedThisPtr;
364  } else {
365  assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
366  Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
367  llvm::Type *ThisType = ThisAddr.getElementType();
368  if (ThisType != AdjustedThisPtr->getType())
369  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
370  Builder.CreateStore(AdjustedThisPtr, ThisAddr);
371  }
372 
373  // Emit the musttail call manually. Even if the prologue pushed cleanups, we
374  // don't actually want to run them.
375  llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
376  Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
377 
378  // Apply the standard set of call attributes.
379  unsigned CallingConv;
381  CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
382  CallingConv, /*AttrOnCallSite=*/true);
383  llvm::AttributeSet Attrs =
384  llvm::AttributeSet::get(getLLVMContext(), AttributeList);
385  Call->setAttributes(Attrs);
386  Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
387 
388  if (Call->getType()->isVoidTy())
389  Builder.CreateRetVoid();
390  else
391  Builder.CreateRet(Call);
392 
393  // Finish the function to maintain CodeGenFunction invariants.
394  // FIXME: Don't emit unreachable code.
396  FinishFunction();
397 }
398 
399 void CodeGenFunction::generateThunk(llvm::Function *Fn,
400  const CGFunctionInfo &FnInfo,
401  GlobalDecl GD, const ThunkInfo &Thunk) {
402  StartThunk(Fn, GD, FnInfo);
403 
404  // Get our callee.
405  llvm::Type *Ty =
407  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
408 
409  // Make the call and return the result.
410  EmitCallAndReturnForThunk(Callee, &Thunk);
411 }
412 
413 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
414  bool ForVTable) {
415  const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
416 
417  // FIXME: re-use FnInfo in this computation.
418  llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
419  llvm::GlobalValue *Entry;
420 
421  // Strip off a bitcast if we got one back.
422  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
423  assert(CE->getOpcode() == llvm::Instruction::BitCast);
424  Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
425  } else {
426  Entry = cast<llvm::GlobalValue>(C);
427  }
428 
429  // There's already a declaration with the same name, check if it has the same
430  // type or if we need to replace it.
431  if (Entry->getType()->getElementType() !=
433  llvm::GlobalValue *OldThunkFn = Entry;
434 
435  // If the types mismatch then we have to rewrite the definition.
436  assert(OldThunkFn->isDeclaration() &&
437  "Shouldn't replace non-declaration");
438 
439  // Remove the name from the old thunk function and get a new thunk.
440  OldThunkFn->setName(StringRef());
441  Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
442 
443  // If needed, replace the old thunk with a bitcast.
444  if (!OldThunkFn->use_empty()) {
445  llvm::Constant *NewPtrForOldDecl =
446  llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
447  OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
448  }
449 
450  // Remove the old thunk.
451  OldThunkFn->eraseFromParent();
452  }
453 
454  llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
455  bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
456  bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
457 
458  if (!ThunkFn->isDeclaration()) {
459  if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
460  // There is already a thunk emitted for this function, do nothing.
461  return;
462  }
463 
464  setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
465  return;
466  }
467 
469 
470  if (ThunkFn->isVarArg()) {
471  // Varargs thunks are special; we can't just generate a call because
472  // we can't copy the varargs. Our implementation is rather
473  // expensive/sucky at the moment, so don't generate the thunk unless
474  // we have to.
475  // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
476  if (UseAvailableExternallyLinkage)
477  return;
478  ThunkFn =
479  CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
480  } else {
481  // Normal thunk body generation.
482  CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
483  }
484 
485  setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
486 }
487 
488 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
489  const ThunkInfo &Thunk) {
490  // If the ABI has key functions, only the TU with the key function should emit
491  // the thunk. However, we can allow inlining of thunks if we emit them with
492  // available_externally linkage together with vtables when optimizations are
493  // enabled.
494  if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
495  !CGM.getCodeGenOpts().OptimizationLevel)
496  return;
497 
498  // We can't emit thunks for member functions with incomplete types.
499  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
500  if (!CGM.getTypes().isFuncTypeConvertible(
501  MD->getType()->castAs<FunctionType>()))
502  return;
503 
504  emitThunk(GD, Thunk, /*ForVTable=*/true);
505 }
506 
508 {
509  const CXXMethodDecl *MD =
510  cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
511 
512  // We don't need to generate thunks for the base destructor.
513  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
514  return;
515 
516  const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
517  VTContext->getThunkInfo(GD);
518 
519  if (!ThunkInfoVector)
520  return;
521 
522  for (const ThunkInfo& Thunk : *ThunkInfoVector)
523  emitThunk(GD, Thunk, /*ForVTable=*/false);
524 }
525 
527  const CXXRecordDecl *RD, const VTableComponent *Components,
528  unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
529  unsigned NumVTableThunks, llvm::Constant *RTTI) {
531 
532  llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
533 
534  llvm::Type *PtrDiffTy =
536 
537  unsigned NextVTableThunkIndex = 0;
538 
539  llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
540 
541  for (unsigned I = 0; I != NumComponents; ++I) {
542  VTableComponent Component = Components[I];
543 
544  llvm::Constant *Init = nullptr;
545 
546  switch (Component.getKind()) {
548  Init = llvm::ConstantInt::get(PtrDiffTy,
549  Component.getVCallOffset().getQuantity());
550  Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
551  break;
553  Init = llvm::ConstantInt::get(PtrDiffTy,
554  Component.getVBaseOffset().getQuantity());
555  Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
556  break;
558  Init = llvm::ConstantInt::get(PtrDiffTy,
559  Component.getOffsetToTop().getQuantity());
560  Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
561  break;
563  Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
564  break;
568  GlobalDecl GD;
569 
570  // Get the right global decl.
571  switch (Component.getKind()) {
572  default:
573  llvm_unreachable("Unexpected vtable component kind");
575  GD = Component.getFunctionDecl();
576  break;
578  GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
579  break;
581  GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
582  break;
583  }
584 
585  if (CGM.getLangOpts().CUDA) {
586  // Emit NULL for methods we can't codegen on this
587  // side. Otherwise we'd end up with vtable with unresolved
588  // references.
589  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
590  // OK on device side: functions w/ __device__ attribute
591  // OK on host side: anything except __device__-only functions.
592  bool CanEmitMethod = CGM.getLangOpts().CUDAIsDevice
593  ? MD->hasAttr<CUDADeviceAttr>()
594  : (MD->hasAttr<CUDAHostAttr>() ||
595  !MD->hasAttr<CUDADeviceAttr>());
596  if (!CanEmitMethod) {
597  Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
598  break;
599  }
600  // Method is acceptable, continue processing as usual.
601  }
602 
603  if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
604  // We have a pure virtual member function.
605  if (!PureVirtualFn) {
606  llvm::FunctionType *Ty =
607  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
608  StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
609  PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
610  PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
611  CGM.Int8PtrTy);
612  }
613  Init = PureVirtualFn;
614  } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
615  if (!DeletedVirtualFn) {
616  llvm::FunctionType *Ty =
617  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
618  StringRef DeletedCallName =
620  DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
621  DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
622  CGM.Int8PtrTy);
623  }
624  Init = DeletedVirtualFn;
625  } else {
626  // Check if we should use a thunk.
627  if (NextVTableThunkIndex < NumVTableThunks &&
628  VTableThunks[NextVTableThunkIndex].first == I) {
629  const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
630 
631  maybeEmitThunkForVTable(GD, Thunk);
632  Init = CGM.GetAddrOfThunk(GD, Thunk);
633 
634  NextVTableThunkIndex++;
635  } else {
637 
638  Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
639  }
640 
641  Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
642  }
643  break;
644  }
645 
647  Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
648  break;
649  };
650 
651  Inits.push_back(Init);
652  }
653 
654  llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
655  return llvm::ConstantArray::get(ArrayType, Inits);
656 }
657 
658 llvm::GlobalVariable *
660  const BaseSubobject &Base,
661  bool BaseIsVirtual,
662  llvm::GlobalVariable::LinkageTypes Linkage,
663  VTableAddressPointsMapTy& AddressPoints) {
664  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
665  DI->completeClassData(Base.getBase());
666 
667  std::unique_ptr<VTableLayout> VTLayout(
668  getItaniumVTableContext().createConstructionVTableLayout(
669  Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
670 
671  // Add the address points.
672  AddressPoints = VTLayout->getAddressPoints();
673 
674  // Get the mangled construction vtable name.
675  SmallString<256> OutName;
676  llvm::raw_svector_ostream Out(OutName);
677  cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
678  .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
679  Base.getBase(), Out);
680  StringRef Name = OutName.str();
681 
682  llvm::ArrayType *ArrayType =
683  llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
684 
685  // Construction vtable symbols are not part of the Itanium ABI, so we cannot
686  // guarantee that they actually will be available externally. Instead, when
687  // emitting an available_externally VTT, we provide references to an internal
688  // linkage construction vtable. The ABI only requires complete-object vtables
689  // to be the same for all instances of a type, not construction vtables.
690  if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
692 
693  // Create the variable that will hold the construction vtable.
694  llvm::GlobalVariable *VTable =
695  CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
696  CGM.setGlobalVisibility(VTable, RD);
697 
698  // V-tables are always unnamed_addr.
699  VTable->setUnnamedAddr(true);
700 
701  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
702  CGM.getContext().getTagDeclType(Base.getBase()));
703 
704  // Create and set the initializer.
705  llvm::Constant *Init = CreateVTableInitializer(
706  Base.getBase(), VTLayout->vtable_component_begin(),
707  VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
708  VTLayout->getNumVTableThunks(), RTTI);
709  VTable->setInitializer(Init);
710 
711  CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
712 
713  return VTable;
714 }
715 
717  const CXXRecordDecl *RD) {
718  return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
720 }
721 
722 /// Compute the required linkage of the v-table for the given class.
723 ///
724 /// Note that we only call this at the end of the translation unit.
725 llvm::GlobalVariable::LinkageTypes
727  if (!RD->isExternallyVisible())
729 
730  // We're at the end of the translation unit, so the current key
731  // function is fully correct.
732  const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
733  if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
734  // If this class has a key function, use that to determine the
735  // linkage of the vtable.
736  const FunctionDecl *def = nullptr;
737  if (keyFunction->hasBody(def))
738  keyFunction = cast<CXXMethodDecl>(def);
739 
740  switch (keyFunction->getTemplateSpecializationKind()) {
741  case TSK_Undeclared:
743  assert((def || CodeGenOpts.OptimizationLevel > 0) &&
744  "Shouldn't query vtable linkage without key function or "
745  "optimizations");
746  if (!def && CodeGenOpts.OptimizationLevel > 0)
747  return llvm::GlobalVariable::AvailableExternallyLinkage;
748 
749  if (keyFunction->isInlined())
750  return !Context.getLangOpts().AppleKext ?
751  llvm::GlobalVariable::LinkOnceODRLinkage :
753 
755 
757  return !Context.getLangOpts().AppleKext ?
758  llvm::GlobalVariable::LinkOnceODRLinkage :
760 
762  return !Context.getLangOpts().AppleKext ?
763  llvm::GlobalVariable::WeakODRLinkage :
765 
767  llvm_unreachable("Should not have been asked to emit this");
768  }
769  }
770 
771  // -fapple-kext mode does not support weak linkage, so we must use
772  // internal linkage.
773  if (Context.getLangOpts().AppleKext)
775 
776  llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
777  llvm::GlobalValue::LinkOnceODRLinkage;
778  llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
779  llvm::GlobalValue::WeakODRLinkage;
780  if (RD->hasAttr<DLLExportAttr>()) {
781  // Cannot discard exported vtables.
782  DiscardableODRLinkage = NonDiscardableODRLinkage;
783  } else if (RD->hasAttr<DLLImportAttr>()) {
784  // Imported vtables are available externally.
785  DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
786  NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
787  }
788 
789  switch (RD->getTemplateSpecializationKind()) {
790  case TSK_Undeclared:
793  return DiscardableODRLinkage;
794 
796  return shouldEmitAvailableExternallyVTable(*this, RD)
797  ? llvm::GlobalVariable::AvailableExternallyLinkage
799 
801  return NonDiscardableODRLinkage;
802  }
803 
804  llvm_unreachable("Invalid TemplateSpecializationKind!");
805 }
806 
807 /// This is a callback from Sema to tell us that that a particular v-table is
808 /// required to be emitted in this translation unit.
809 ///
810 /// This is only called for vtables that _must_ be emitted (mainly due to key
811 /// functions). For weak vtables, CodeGen tracks when they are needed and
812 /// emits them as-needed.
814  VTables.GenerateClassData(theClass);
815 }
816 
817 void
819  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
820  DI->completeClassData(RD);
821 
822  if (RD->getNumVBases())
824 
825  CGM.getCXXABI().emitVTableDefinitions(*this, RD);
826 }
827 
828 /// At this point in the translation unit, does it appear that can we
829 /// rely on the vtable being defined elsewhere in the program?
830 ///
831 /// The response is really only definitive when called at the end of
832 /// the translation unit.
833 ///
834 /// The only semantic restriction here is that the object file should
835 /// not contain a v-table definition when that v-table is defined
836 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
837 /// v-tables when unnecessary.
839  assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
840 
841  // If we have an explicit instantiation declaration (and not a
842  // definition), the v-table is defined elsewhere.
845  return true;
846 
847  // Otherwise, if the class is an instantiated template, the
848  // v-table must be defined here.
849  if (TSK == TSK_ImplicitInstantiation ||
851  return false;
852 
853  // Otherwise, if the class doesn't have a key function (possibly
854  // anymore), the v-table must be defined here.
855  const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
856  if (!keyFunction)
857  return false;
858 
859  // Otherwise, if we don't have a definition of the key function, the
860  // v-table must be defined somewhere else.
861  return !keyFunction->hasBody();
862 }
863 
864 /// Given that we're currently at the end of the translation unit, and
865 /// we've emitted a reference to the v-table for this class, should
866 /// we define that v-table?
868  const CXXRecordDecl *RD) {
869  // If vtable is internal then it has to be done.
870  if (!CGM.getVTables().isVTableExternal(RD))
871  return true;
872 
873  // If it's external then maybe we will need it as available_externally.
874  return shouldEmitAvailableExternallyVTable(CGM, RD);
875 }
876 
877 /// Given that at some point we emitted a reference to one or more
878 /// v-tables, and that we are now at the end of the translation unit,
879 /// decide whether we should emit them.
880 void CodeGenModule::EmitDeferredVTables() {
881 #ifndef NDEBUG
882  // Remember the size of DeferredVTables, because we're going to assume
883  // that this entire operation doesn't modify it.
884  size_t savedSize = DeferredVTables.size();
885 #endif
886 
887  for (const CXXRecordDecl *RD : DeferredVTables)
889  VTables.GenerateClassData(RD);
890 
891  assert(savedSize == DeferredVTables.size() &&
892  "deferred extra v-tables during v-table emission?");
893  DeferredVTables.clear();
894 }
895 
897  if (RD->hasAttr<UuidAttr>() &&
898  getContext().getSanitizerBlacklist().isBlacklistedType("attr:uuid"))
899  return true;
900 
903 }
904 
905 void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
906  const VTableLayout &VTLayout) {
907  if (!LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
908  !LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
909  !LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
910  !LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
911  return;
912 
913  CharUnits PointerWidth =
914  Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
915 
916  typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
917  std::vector<BSEntry> BitsetEntries;
918  // Create a bit set entry for each address point.
919  for (auto &&AP : VTLayout.getAddressPoints()) {
920  if (IsCFIBlacklistedRecord(AP.first.getBase()))
921  continue;
922 
923  BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
924  }
925 
926  // Sort the bit set entries for determinism.
927  std::sort(BitsetEntries.begin(), BitsetEntries.end(),
928  [this](const BSEntry &E1, const BSEntry &E2) {
929  if (&E1 == &E2)
930  return false;
931 
932  std::string S1;
933  llvm::raw_string_ostream O1(S1);
935  QualType(E1.first->getTypeForDecl(), 0), O1);
936  O1.flush();
937 
938  std::string S2;
939  llvm::raw_string_ostream O2(S2);
941  QualType(E2.first->getTypeForDecl(), 0), O2);
942  O2.flush();
943 
944  if (S1 < S2)
945  return true;
946  if (S1 != S2)
947  return false;
948 
949  return E1.second < E2.second;
950  });
951 
952  llvm::NamedMDNode *BitsetsMD =
953  getModule().getOrInsertNamedMetadata("llvm.bitsets");
954  for (auto BitsetEntry : BitsetEntries)
955  CreateVTableBitSetEntry(BitsetsMD, VTable,
956  PointerWidth * BitsetEntry.second,
957  BitsetEntry.first);
958 }
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:151
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:50
CanQualType VoidPtrTy
Definition: ASTContext.h:895
A (possibly-)qualified type.
Definition: Type.h:575
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses 'sret' when used as a return type.
Definition: CGCall.cpp:1250
CanQualType getReturnType() const
CharUnits getOffsetToTop() const
virtual void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType)
Definition: CGCXXABI.cpp:188
llvm::Module & getModule() const
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition: CGClass.cpp:35
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2847
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:79
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:171
virtual const ThunkInfoVectorTy * getThunkInfo(GlobalDecl GD)
virtual llvm::Value * performThisAdjustment(CodeGenFunction &CGF, Address This, const ThisAdjustment &TA)=0
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2424
virtual StringRef GetDeletedVirtualCallName()=0
Gets the deleted virtual member call name.
llvm::Function * GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:144
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i...
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
CGDebugInfo * getModuleDebugInfo()
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:51
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:1598
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1299
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:25
bool isVoidType() const
Definition: Type.h:5546
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:107
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body (definition).
Definition: Decl.cpp:2460
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
bool hasAttr() const
Definition: DeclBase.h:498
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...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM, const CXXRecordDecl *RD)
Definition: CGVTables.cpp:716
static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD, const ThunkInfo &Thunk, llvm::Function *Fn)
Definition: CGVTables.cpp:53
bool isReferenceType() const
Definition: Type.h:5314
RValue EmitCall(const CGFunctionInfo &FnInfo, llvm::Value *Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, CGCalleeInfo CalleeInfo=CGCalleeInfo(), llvm::Instruction **callOrInvoke=nullptr)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3159
The this pointer adjustment as well as an optional return adjustment for a thunk. ...
Definition: ABI.h:179
const Decl * getDecl() const
Definition: GlobalDecl.h:60
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
const CXXMethodDecl * getFunctionDecl() const
static bool hasScalarEvaluationKind(QualType T)
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:580
virtual void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD)=0
Emits the VTable definitions required for the given record type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:596
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
CharUnits getVCallOffset() const
QualType getReturnType() const
Definition: Type.h:2977
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1801
Deleting dtor.
Definition: ABI.h:35
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
const SanitizerBlacklist & getSanitizerBlacklist() const
Definition: ASTContext.h:598
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it's possible to emit a vtable for RD, even though we do not know that the vtable h...
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:71
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
detail::InMemoryDirectory::const_iterator I
QualType getType() const
Definition: Decl.h:530
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:352
param_iterator param_begin()
Definition: Decl.h:1906
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
const TargetInfo & getTarget() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:38
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
Definition: CGCall.cpp:2529
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:838
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
const CXXRecordDecl * getBase() const
getBase - Returns the base class declaration.
Definition: BaseSubobject.h:41
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk, llvm::Function *ThunkFn, bool ForVTable, GlobalDecl GD)
Definition: CGVTables.cpp:58
llvm::Value * getPointer() const
Definition: Address.h:38
static bool similar(const ABIArgInfo &infoL, CanQualType typeL, const ABIArgInfo &infoR, CanQualType typeR)
Definition: CGVTables.cpp:74
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:67
CGCXXABI & getCXXABI() const
bool usesInAlloca() const
Return true if this function uses inalloca arguments.
Inits[]
Definition: OpenMPClause.h:310
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2345
virtual StringRef GetPureVirtualCallName()=0
Gets the pure virtual member call function.
ASTContext & getContext() const
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:81
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:1999
llvm::LLVMContext & getLLVMContext()
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
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:235
Base object dtor.
Definition: ABI.h:37
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
Definition: CGCXXABI.h:105
bool isExternallyVisible() const
Definition: Decl.h:280
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:144
virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, CallArgList &CallArgs)
Definition: CGCXXABI.h:402
void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
Generate a thunk for the given method.
Definition: CGVTables.cpp:399
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:228
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:28
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage)
Will return a global variable of the given type.
llvm::Constant * GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk)
Get the address of the thunk for the given global decl.
Definition: CGVTables.cpp:35
The l-value was considered opaque, so the alignment was determined from a type.
virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, const ThisAdjustment &ThisAdjustment, raw_ostream &)=0
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:168
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeSet ExtraAttrs=llvm::AttributeSet())
Create a new runtime function with the specified type and name.
ASTContext & getContext() const
bool isBlacklistedType(StringRef MangledTypeName, StringRef Category=StringRef()) const
const TemplateArgument * iterator
Definition: Type.h:4070
void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk)
Definition: CGVTables.cpp:256
Represents a single component in a vtable.
Definition: VTableBuilder.h:31
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1701
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:32
const CXXDestructorDecl * getDestructorDecl() const
const CodeGenOptions & getCodeGenOpts() const
An aligned address.
Definition: Address.h:25
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
const LangOptions & getLangOpts() const
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD)=0
Emit any tables needed to implement virtual inheritance.
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:95
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:156
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:141
Complete object dtor.
Definition: ABI.h:36
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5159
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:476
const CGFunctionInfo * CurFnInfo
bool isDynamicClass() const
Definition: DeclCXX.h:693
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:659
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
virtual void mangleTypeName(QualType T, raw_ostream &)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing...
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:146
param_range params()
Definition: Decl.h:1910
void EmitVTableBitSetEntries(llvm::GlobalVariable *VTable, const VTableLayout &VTLayout)
Emit bit set entries for the given vtable using the given layout if vptr CFI is enabled.
Definition: CGVTables.cpp:905
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1243
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn'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.
ThisAdjustment This
The this pointer adjustment.
Definition: ABI.h:181
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:58
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:152
CharUnits getVBaseOffset() const
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for 'this'.
Definition: CGCXXABI.cpp:156
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:138
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:121
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
Definition: CGVTables.cpp:507
param_iterator param_end()
Definition: Decl.h:1907
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:726
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:148
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3268
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:52
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM, const CXXRecordDecl *RD)
Given that we're currently at the end of the translation unit, and we've emitted a reference to the v...
Definition: CGVTables.cpp:867
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
Definition: CGVTables.cpp:818
ReturnAdjustment Return
The return adjustment.
Definition: ABI.h:184
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1522
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:367
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo)
Definition: CGVTables.cpp:210
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1395
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl...
Definition: CGCall.cpp:1407
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:83
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or NULL if there isn't one...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool IsCFIBlacklistedRecord(const CXXRecordDecl *RD)
Returns whether the given record is blacklisted from control flow integrity checks.
Definition: CGVTables.cpp:896
virtual void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, raw_ostream &)=0
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
llvm::Constant * CreateVTableInitializer(const CXXRecordDecl *RD, const VTableComponent *Components, unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks, unsigned NumVTableThunks, llvm::Constant *RTTI)
CreateVTableInitializer - Create a vtable initializer for the given record decl.
Definition: CGVTables.cpp:526
void CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create a bitset entry for the given vtable and add it to BitsetsMD.
std::pair< uint64_t, ThunkInfo > VTableThunkTy
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
const_arg_iterator arg_begin() const
A pointer to the deleting destructor.
Definition: VTableBuilder.h:44
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
virtual llvm::Value * performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const ReturnAdjustment &RA)=0
Kind getKind() const
Get the kind of this vtable component.
const AddressPointsMapTy & getAddressPoints() const
CodeGenVTables & getVTables()
CharUnits getBaseOffset() const
getBaseOffset - Returns the base class offset.
Definition: BaseSubobject.h:44
SourceLocation getLocation() const
Definition: DeclBase.h:384
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:728
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition: CGCall.cpp:1434
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, bool IsForDefinition=false)
Return the address of the given function.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:56
A pointer to the complete destructor.
Definition: VTableBuilder.h:41
bool isEmpty() const
Definition: ABI.h:87
virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment)=0
void EmitVTable(CXXRecordDecl *Class)
This is a callback from Sema to tell us that that a particular v-table is required to be emitted in t...
Definition: CGVTables.cpp:813
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:72
void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, llvm::Value *Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
Definition: CGVTables.cpp:344
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1293