Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGVTables.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This contains code dealing with C++ code generation of virtual tables.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CodeGenFunction.h"
15
#include "CodeGenModule.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/RecordLayout.h"
19
#include "clang/Basic/CodeGenOptions.h"
20
#include "clang/CodeGen/CGFunctionInfo.h"
21
#include "clang/CodeGen/ConstantInitBuilder.h"
22
#include "llvm/IR/IntrinsicInst.h"
23
#include "llvm/Support/Format.h"
24
#include "llvm/Transforms/Utils/Cloning.h"
25
#include <algorithm>
26
#include <cstdio>
27
28
using namespace clang;
29
using namespace CodeGen;
30
31
CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32
45.6k
    : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33
34
llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
35
1.08k
                                              GlobalDecl GD) {
36
1.08k
  return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
37
1.08k
                                 /*DontDefer=*/true, /*IsThunk=*/true);
38
1.08k
}
39
40
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
41
                               llvm::Function *ThunkFn, bool ForVTable,
42
643
                               GlobalDecl GD) {
43
643
  CGM.setFunctionLinkage(GD, ThunkFn);
44
643
  CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
45
643
                                  !Thunk.Return.isEmpty());
46
47
  // Set the right visibility.
48
643
  CGM.setGVProperties(ThunkFn, GD);
49
50
643
  if (!CGM.getCXXABI().exportThunk()) {
51
269
    ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
52
269
    ThunkFn->setDSOLocal(true);
53
269
  }
54
55
643
  if (CGM.supportsCOMDAT() && 
ThunkFn->isWeakForLinker()447
)
56
323
    ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
57
643
}
58
59
#ifndef NDEBUG
60
static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61
1.06k
                    const ABIArgInfo &infoR, CanQualType typeR) {
62
1.06k
  return (infoL.getKind() == infoR.getKind() &&
63
1.06k
          (typeL == typeR ||
64
1.06k
           
(100
isa<PointerType>(typeL)100
&&
isa<PointerType>(typeR)100
) ||
65
1.06k
           
(0
isa<ReferenceType>(typeL)0
&&
isa<ReferenceType>(typeR)0
)));
66
1.06k
}
67
#endif
68
69
static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70
                                      QualType ResultType, RValue RV,
71
64
                                      const ThunkInfo &Thunk) {
72
  // Emit the return adjustment.
73
64
  bool NullCheckValue = !ResultType->isReferenceType();
74
75
64
  llvm::BasicBlock *AdjustNull = nullptr;
76
64
  llvm::BasicBlock *AdjustNotNull = nullptr;
77
64
  llvm::BasicBlock *AdjustEnd = nullptr;
78
79
64
  llvm::Value *ReturnValue = RV.getScalarVal();
80
81
64
  if (NullCheckValue) {
82
57
    AdjustNull = CGF.createBasicBlock("adjust.null");
83
57
    AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84
57
    AdjustEnd = CGF.createBasicBlock("adjust.end");
85
86
57
    llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87
57
    CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88
57
    CGF.EmitBlock(AdjustNotNull);
89
57
  }
90
91
64
  auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
92
64
  auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
93
64
  ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
94
64
                                            Address(ReturnValue, ClassAlign),
95
64
                                            Thunk.Return);
96
97
64
  if (NullCheckValue) {
98
57
    CGF.Builder.CreateBr(AdjustEnd);
99
57
    CGF.EmitBlock(AdjustNull);
100
57
    CGF.Builder.CreateBr(AdjustEnd);
101
57
    CGF.EmitBlock(AdjustEnd);
102
103
57
    llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
104
57
    PHI->addIncoming(ReturnValue, AdjustNotNull);
105
57
    PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
106
57
                     AdjustNull);
107
57
    ReturnValue = PHI;
108
57
  }
109
110
64
  return RValue::get(ReturnValue);
111
64
}
112
113
/// This function clones a function's DISubprogram node and enters it into
114
/// a value map with the intent that the map can be utilized by the cloner
115
/// to short-circuit Metadata node mapping.
116
/// Furthermore, the function resolves any DILocalVariable nodes referenced
117
/// by dbg.value intrinsics so they can be properly mapped during cloning.
118
static void resolveTopLevelMetadata(llvm::Function *Fn,
119
7
                                    llvm::ValueToValueMapTy &VMap) {
120
  // Clone the DISubprogram node and put it into the Value map.
121
7
  auto *DIS = Fn->getSubprogram();
122
7
  if (!DIS)
123
4
    return;
124
3
  auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
125
3
  VMap.MD()[DIS].reset(NewDIS);
126
127
  // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
128
  // they are referencing.
129
3
  for (auto &BB : Fn->getBasicBlockList()) {
130
17
    for (auto &I : BB) {
131
17
      if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
132
2
        auto *DILocal = DII->getVariable();
133
2
        if (!DILocal->isResolved())
134
0
          DILocal->resolve();
135
2
      }
136
17
    }
137
3
  }
138
3
}
139
140
// This function does roughly the same thing as GenerateThunk, but in a
141
// very different way, so that va_start and va_end work correctly.
142
// FIXME: This function assumes "this" is the first non-sret LLVM argument of
143
//        a function, and that there is an alloca built in the entry block
144
//        for all accesses to "this".
145
// FIXME: This function assumes there is only one "ret" statement per function.
146
// FIXME: Cloning isn't correct in the presence of indirect goto!
147
// FIXME: This implementation of thunks bloats codesize by duplicating the
148
//        function definition.  There are alternatives:
149
//        1. Add some sort of stub support to LLVM for cases where we can
150
//           do a this adjustment, then a sibcall.
151
//        2. We could transform the definition to take a va_list instead of an
152
//           actual variable argument list, then have the thunks (including a
153
//           no-op thunk for the regular definition) call va_start/va_end.
154
//           There's a bit of per-call overhead for this solution, but it's
155
//           better for codesize if the definition is long.
156
llvm::Function *
157
CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
158
                                      const CGFunctionInfo &FnInfo,
159
9
                                      GlobalDecl GD, const ThunkInfo &Thunk) {
160
9
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
161
9
  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
162
9
  QualType ResultType = FPT->getReturnType();
163
164
  // Get the original function
165
9
  assert(FnInfo.isVariadic());
166
0
  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
167
9
  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
168
9
  llvm::Function *BaseFn = cast<llvm::Function>(Callee);
169
170
  // Cloning can't work if we don't have a definition. The Microsoft ABI may
171
  // require thunks when a definition is not available. Emit an error in these
172
  // cases.
173
9
  if (!MD->isDefined()) {
174
2
    CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
175
2
    return Fn;
176
2
  }
177
7
  assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
178
179
  // Clone to thunk.
180
0
  llvm::ValueToValueMapTy VMap;
181
182
  // We are cloning a function while some Metadata nodes are still unresolved.
183
  // Ensure that the value mapper does not encounter any of them.
184
7
  resolveTopLevelMetadata(BaseFn, VMap);
185
7
  llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
186
7
  Fn->replaceAllUsesWith(NewFn);
187
7
  NewFn->takeName(Fn);
188
7
  Fn->eraseFromParent();
189
7
  Fn = NewFn;
190
191
  // "Initialize" CGF (minimally).
192
7
  CurFn = Fn;
193
194
  // Get the "this" value
195
7
  llvm::Function::arg_iterator AI = Fn->arg_begin();
196
7
  if (CGM.ReturnTypeUsesSRet(FnInfo))
197
0
    ++AI;
198
199
  // Find the first store of "this", which will be to the alloca associated
200
  // with "this".
201
7
  Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
202
7
  llvm::BasicBlock *EntryBB = &Fn->front();
203
7
  llvm::BasicBlock::iterator ThisStore =
204
20
      std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
205
20
        return isa<llvm::StoreInst>(I) &&
206
20
               
I.getOperand(0) == ThisPtr.getPointer()8
;
207
20
      });
208
7
  assert(ThisStore != EntryBB->end() &&
209
7
         "Store of this should be in entry block?");
210
  // Adjust "this", if necessary.
211
0
  Builder.SetInsertPoint(&*ThisStore);
212
7
  llvm::Value *AdjustedThisPtr =
213
7
      CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
214
7
  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
215
7
                                          ThisStore->getOperand(0)->getType());
216
7
  ThisStore->setOperand(0, AdjustedThisPtr);
217
218
7
  if (!Thunk.Return.isEmpty()) {
219
    // Fix up the returned value, if necessary.
220
5
    for (llvm::BasicBlock &BB : *Fn) {
221
5
      llvm::Instruction *T = BB.getTerminator();
222
5
      if (isa<llvm::ReturnInst>(T)) {
223
5
        RValue RV = RValue::get(T->getOperand(0));
224
5
        T->eraseFromParent();
225
5
        Builder.SetInsertPoint(&BB);
226
5
        RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
227
5
        Builder.CreateRet(RV.getScalarVal());
228
5
        break;
229
5
      }
230
5
    }
231
5
  }
232
233
7
  return Fn;
234
9
}
235
236
void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
237
                                 const CGFunctionInfo &FnInfo,
238
602
                                 bool IsUnprototyped) {
239
602
  assert(!CurGD.getDecl() && "CurGD was already set!");
240
0
  CurGD = GD;
241
602
  CurFuncIsThunk = true;
242
243
  // Build FunctionArgs.
244
602
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
245
602
  QualType ThisType = MD->getThisType();
246
602
  QualType ResultType;
247
602
  if (IsUnprototyped)
248
6
    ResultType = CGM.getContext().VoidTy;
249
596
  else if (CGM.getCXXABI().HasThisReturn(GD))
250
12
    ResultType = ThisType;
251
584
  else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
252
94
    ResultType = CGM.getContext().VoidPtrTy;
253
490
  else
254
490
    ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
255
602
  FunctionArgList FunctionArgs;
256
257
  // Create the implicit 'this' parameter declaration.
258
602
  CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
259
260
  // Add the rest of the parameters, if we have a prototype to work with.
261
602
  if (!IsUnprototyped) {
262
596
    FunctionArgs.append(MD->param_begin(), MD->param_end());
263
264
596
    if (isa<CXXDestructorDecl>(MD))
265
247
      CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
266
247
                                                FunctionArgs);
267
596
  }
268
269
  // Start defining the function.
270
602
  auto NL = ApplyDebugLocation::CreateEmpty(*this);
271
602
  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
272
602
                MD->getLocation());
273
  // Create a scope with an artificial location for the body of this function.
274
602
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
275
276
  // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
277
602
  CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
278
602
  CXXThisValue = CXXABIThisValue;
279
602
  CurCodeDecl = MD;
280
602
  CurFuncDecl = MD;
281
602
}
282
283
651
void CodeGenFunction::FinishThunk() {
284
  // Clear these to restore the invariants expected by
285
  // StartFunction/FinishFunction.
286
651
  CurCodeDecl = nullptr;
287
651
  CurFuncDecl = nullptr;
288
289
651
  FinishFunction();
290
651
}
291
292
void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
293
                                                const ThunkInfo *Thunk,
294
602
                                                bool IsUnprototyped) {
295
602
  assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
296
602
         "Please use a new CGF for this thunk");
297
0
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
298
299
  // Adjust the 'this' pointer if necessary
300
602
  llvm::Value *AdjustedThisPtr =
301
602
    Thunk ? CGM.getCXXABI().performThisAdjustment(
302
602
                          *this, LoadCXXThisAddress(), Thunk->This)
303
602
          : 
LoadCXXThis()0
;
304
305
  // If perfect forwarding is required a variadic method, a method using
306
  // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
307
  // thunk requires a return adjustment, since that is impossible with musttail.
308
602
  if (CurFnInfo->usesInAlloca() || 
CurFnInfo->isVariadic()597
||
IsUnprototyped583
) {
309
19
    if (Thunk && !Thunk->Return.isEmpty()) {
310
3
      if (IsUnprototyped)
311
2
        CGM.ErrorUnsupported(
312
2
            MD, "return-adjusting thunk with incomplete parameter type");
313
1
      else if (CurFnInfo->isVariadic())
314
0
        llvm_unreachable("shouldn't try to emit musttail return-adjusting "
315
1
                         "thunks for variadic functions");
316
1
      else
317
1
        CGM.ErrorUnsupported(
318
1
            MD, "non-trivial argument copy for return-adjusting thunk");
319
3
    }
320
19
    EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
321
19
    return;
322
19
  }
323
324
  // Start building CallArgs.
325
583
  CallArgList CallArgs;
326
583
  QualType ThisType = MD->getThisType();
327
583
  CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
328
329
583
  if (isa<CXXDestructorDecl>(MD))
330
247
    CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
331
332
583
#ifndef NDEBUG
333
583
  unsigned PrefixArgs = CallArgs.size() - 1;
334
583
#endif
335
  // Add the rest of the arguments.
336
583
  for (const ParmVarDecl *PD : MD->parameters())
337
49
    EmitDelegateCallArg(CallArgs, PD, SourceLocation());
338
339
583
  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
340
341
583
#ifndef NDEBUG
342
583
  const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
343
583
      CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
344
583
  assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
345
583
         CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
346
583
         CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
347
0
  assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
348
583
         similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
349
583
                 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
350
0
  assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
351
1.30k
  for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; 
++i726
)
352
726
    assert(similar(CallFnInfo.arg_begin()[i].info,
353
583
                   CallFnInfo.arg_begin()[i].type,
354
583
                   CurFnInfo->arg_begin()[i].info,
355
583
                   CurFnInfo->arg_begin()[i].type));
356
583
#endif
357
358
  // Determine whether we have a return value slot to use.
359
583
  QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
360
583
                            ? 
ThisType12
361
583
                            : 
CGM.getCXXABI().hasMostDerivedReturn(CurGD)571
362
571
                                  ? 
CGM.getContext().VoidPtrTy94
363
571
                                  : 
FPT->getReturnType()477
;
364
583
  ReturnValueSlot Slot;
365
583
  if (!ResultType->isVoidType() &&
366
583
      
(211
CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect211
||
367
211
       
hasAggregateEvaluationKind(ResultType)202
))
368
15
    Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(),
369
15
                           /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
370
371
  // Now emit our call.
372
583
  llvm::CallBase *CallOrInvoke;
373
583
  RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
374
583
                       CallArgs, &CallOrInvoke);
375
376
  // Consider return adjustment if we have ThunkInfo.
377
583
  if (Thunk && !Thunk->Return.isEmpty())
378
59
    RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
379
524
  else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
380
524
    Call->setTailCallKind(llvm::CallInst::TCK_Tail);
381
382
  // Emit return.
383
583
  if (!ResultType->isVoidType() && 
Slot.isNull()211
)
384
196
    CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
385
386
  // Disable the final ARC autorelease.
387
583
  AutoreleaseResult = false;
388
389
583
  FinishThunk();
390
583
}
391
392
void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
393
                                        llvm::Value *AdjustedThisPtr,
394
68
                                        llvm::FunctionCallee Callee) {
395
  // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
396
  // to translate AST arguments into LLVM IR arguments.  For thunks, we know
397
  // that the caller prototype more or less matches the callee prototype with
398
  // the exception of 'this'.
399
68
  SmallVector<llvm::Value *, 8> Args;
400
68
  for (llvm::Argument &A : CurFn->args())
401
79
    Args.push_back(&A);
402
403
  // Set the adjusted 'this' pointer.
404
68
  const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
405
68
  if (ThisAI.isDirect()) {
406
66
    const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
407
66
    int ThisArgNo = RetAI.isIndirect() && 
!RetAI.isSRetAfterThis()0
?
10
: 0;
408
66
    llvm::Type *ThisType = Args[ThisArgNo]->getType();
409
66
    if (ThisType != AdjustedThisPtr->getType())
410
10
      AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
411
66
    Args[ThisArgNo] = AdjustedThisPtr;
412
66
  } else {
413
2
    assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
414
0
    Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
415
2
    llvm::Type *ThisType = ThisAddr.getElementType();
416
2
    if (ThisType != AdjustedThisPtr->getType())
417
2
      AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
418
2
    Builder.CreateStore(AdjustedThisPtr, ThisAddr);
419
2
  }
420
421
  // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
422
  // don't actually want to run them.
423
0
  llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
424
68
  Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
425
426
  // Apply the standard set of call attributes.
427
68
  unsigned CallingConv;
428
68
  llvm::AttributeList Attrs;
429
68
  CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
430
68
                             Attrs, CallingConv, /*AttrOnCallSite=*/true,
431
68
                             /*IsThunk=*/false);
432
68
  Call->setAttributes(Attrs);
433
68
  Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
434
435
68
  if (Call->getType()->isVoidTy())
436
63
    Builder.CreateRetVoid();
437
5
  else
438
5
    Builder.CreateRet(Call);
439
440
  // Finish the function to maintain CodeGenFunction invariants.
441
  // FIXME: Don't emit unreachable code.
442
68
  EmitBlock(createBasicBlock());
443
444
68
  FinishThunk();
445
68
}
446
447
void CodeGenFunction::generateThunk(llvm::Function *Fn,
448
                                    const CGFunctionInfo &FnInfo, GlobalDecl GD,
449
                                    const ThunkInfo &Thunk,
450
602
                                    bool IsUnprototyped) {
451
602
  StartThunk(Fn, GD, FnInfo, IsUnprototyped);
452
  // Create a scope with an artificial location for the body of this function.
453
602
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
454
455
  // Get our callee. Use a placeholder type if this method is unprototyped so
456
  // that CodeGenModule doesn't try to set attributes.
457
602
  llvm::Type *Ty;
458
602
  if (IsUnprototyped)
459
6
    Ty = llvm::StructType::get(getLLVMContext());
460
596
  else
461
596
    Ty = CGM.getTypes().GetFunctionType(FnInfo);
462
463
602
  llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
464
465
  // Fix up the function type for an unprototyped musttail call.
466
602
  if (IsUnprototyped)
467
6
    Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
468
469
  // Make the call and return the result.
470
602
  EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
471
602
                            &Thunk, IsUnprototyped);
472
602
}
473
474
static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
475
1.08k
                                  bool IsUnprototyped, bool ForVTable) {
476
  // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
477
  // provide thunks for us.
478
1.08k
  if (CGM.getTarget().getCXXABI().isMicrosoft())
479
384
    return true;
480
481
  // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
482
  // definitions of the main method. Therefore, emitting thunks with the vtable
483
  // is purely an optimization. Emit the thunk if optimizations are enabled and
484
  // all of the parameter types are complete.
485
704
  if (ForVTable)
486
373
    return CGM.getCodeGenOpts().OptimizationLevel && 
!IsUnprototyped67
;
487
488
  // Always emit thunks along with the method definition.
489
331
  return true;
490
704
}
491
492
llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
493
                                               const ThunkInfo &TI,
494
1.08k
                                               bool ForVTable) {
495
1.08k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
496
497
  // First, get a declaration. Compute the mangled name. Don't worry about
498
  // getting the function prototype right, since we may only need this
499
  // declaration to fill in a vtable slot.
500
1.08k
  SmallString<256> Name;
501
1.08k
  MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
502
1.08k
  llvm::raw_svector_ostream Out(Name);
503
1.08k
  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
504
501
    MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
505
587
  else
506
587
    MCtx.mangleThunk(MD, TI, Out);
507
1.08k
  llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
508
1.08k
  llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
509
510
  // If we don't need to emit a definition, return this declaration as is.
511
1.08k
  bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
512
1.08k
      MD->getType()->castAs<FunctionType>());
513
1.08k
  if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
514
310
    return Thunk;
515
516
  // Arrange a function prototype appropriate for a function definition. In some
517
  // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
518
778
  const CGFunctionInfo &FnInfo =
519
778
      IsUnprototyped ? 
CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)6
520
778
                     : 
CGM.getTypes().arrangeGlobalDeclaration(GD)772
;
521
778
  llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
522
523
  // If the type of the underlying GlobalValue is wrong, we'll have to replace
524
  // it. It should be a declaration.
525
778
  llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
526
778
  if (ThunkFn->getFunctionType() != ThunkFnTy) {
527
7
    llvm::GlobalValue *OldThunkFn = ThunkFn;
528
529
7
    assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
530
531
    // Remove the name from the old thunk function and get a new thunk.
532
0
    OldThunkFn->setName(StringRef());
533
7
    ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
534
7
                                     Name.str(), &CGM.getModule());
535
7
    CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
536
537
    // If needed, replace the old thunk with a bitcast.
538
7
    if (!OldThunkFn->use_empty()) {
539
7
      llvm::Constant *NewPtrForOldDecl =
540
7
          llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
541
7
      OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
542
7
    }
543
544
    // Remove the old thunk.
545
7
    OldThunkFn->eraseFromParent();
546
7
  }
547
548
0
  bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
549
778
  bool UseAvailableExternallyLinkage = ForVTable && 
ABIHasKeyFunctions333
;
550
551
778
  if (!ThunkFn->isDeclaration()) {
552
165
    if (!ABIHasKeyFunctions || 
UseAvailableExternallyLinkage50
) {
553
      // There is already a thunk emitted for this function, do nothing.
554
133
      return ThunkFn;
555
133
    }
556
557
32
    setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
558
32
    return ThunkFn;
559
165
  }
560
561
  // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
562
  // that the return type is meaningless. These thunks can be used to call
563
  // functions with differing return types, and the caller is required to cast
564
  // the prototype appropriately to extract the correct value.
565
613
  if (IsUnprototyped)
566
6
    ThunkFn->addFnAttr("thunk");
567
568
613
  CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
569
570
  // Thunks for variadic methods are special because in general variadic
571
  // arguments cannot be perfectly forwarded. In the general case, clang
572
  // implements such thunks by cloning the original function body. However, for
573
  // thunks with no return adjustment on targets that support musttail, we can
574
  // use musttail to perfectly forward the variadic arguments.
575
613
  bool ShouldCloneVarArgs = false;
576
613
  if (!IsUnprototyped && 
ThunkFn->isVarArg()607
) {
577
19
    ShouldCloneVarArgs = true;
578
19
    if (TI.Return.isEmpty()) {
579
12
      switch (CGM.getTriple().getArch()) {
580
8
      case llvm::Triple::x86_64:
581
8
      case llvm::Triple::x86:
582
8
      case llvm::Triple::aarch64:
583
8
        ShouldCloneVarArgs = false;
584
8
        break;
585
4
      default:
586
4
        break;
587
12
      }
588
12
    }
589
19
  }
590
591
613
  if (ShouldCloneVarArgs) {
592
11
    if (UseAvailableExternallyLinkage)
593
2
      return ThunkFn;
594
9
    ThunkFn =
595
9
        CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
596
602
  } else {
597
    // Normal thunk body generation.
598
602
    CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
599
602
  }
600
601
611
  setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
602
611
  return ThunkFn;
603
613
}
604
605
4.38k
void CodeGenVTables::EmitThunks(GlobalDecl GD) {
606
4.38k
  const CXXMethodDecl *MD =
607
4.38k
    cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
608
609
  // We don't need to generate thunks for the base destructor.
610
4.38k
  if (isa<CXXDestructorDecl>(MD) && 
GD.getDtorType() == Dtor_Base2.62k
)
611
896
    return;
612
613
3.48k
  const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
614
3.48k
      VTContext->getThunkInfo(GD);
615
616
3.48k
  if (!ThunkInfoVector)
617
3.06k
    return;
618
619
420
  for (const ThunkInfo& Thunk : *ThunkInfoVector)
620
445
    maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
621
420
}
622
623
void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
624
                                          llvm::Constant *component,
625
                                          unsigned vtableAddressPoint,
626
                                          bool vtableHasLocalLinkage,
627
167
                                          bool isCompleteDtor) const {
628
  // No need to get the offset of a nullptr.
629
167
  if (component->isNullValue())
630
1
    return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
631
632
166
  auto *globalVal =
633
166
      cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
634
166
  llvm::Module &module = CGM.getModule();
635
636
  // We don't want to copy the linkage of the vtable exactly because we still
637
  // want the stub/proxy to be emitted for properly calculating the offset.
638
  // Examples where there would be no symbol emitted are available_externally
639
  // and private linkages.
640
166
  auto stubLinkage = vtableHasLocalLinkage ? 
llvm::GlobalValue::InternalLinkage8
641
166
                                           : 
llvm::GlobalValue::ExternalLinkage158
;
642
643
166
  llvm::Constant *target;
644
166
  if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
645
96
    target = llvm::DSOLocalEquivalent::get(func);
646
96
  } else {
647
70
    llvm::SmallString<16> rttiProxyName(globalVal->getName());
648
70
    rttiProxyName.append(".rtti_proxy");
649
650
    // The RTTI component may not always be emitted in the same linkage unit as
651
    // the vtable. As a general case, we can make a dso_local proxy to the RTTI
652
    // that points to the actual RTTI struct somewhere. This will result in a
653
    // GOTPCREL relocation when taking the relative offset to the proxy.
654
70
    llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
655
70
    if (!proxy) {
656
50
      proxy = new llvm::GlobalVariable(module, globalVal->getType(),
657
50
                                       /*isConstant=*/true, stubLinkage,
658
50
                                       globalVal, rttiProxyName);
659
50
      proxy->setDSOLocal(true);
660
50
      proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
661
50
      if (!proxy->hasLocalLinkage()) {
662
50
        proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
663
50
        proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
664
50
      }
665
50
    }
666
70
    target = proxy;
667
70
  }
668
669
166
  builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
670
166
                                      /*position=*/vtableAddressPoint);
671
166
}
672
673
27.4k
bool CodeGenVTables::useRelativeLayout() const {
674
27.4k
  return CGM.getTarget().getCXXABI().isItaniumFamily() &&
675
27.4k
         
CGM.getItaniumVTableContext().isRelativeLayout()22.9k
;
676
27.4k
}
677
678
6.14k
llvm::Type *CodeGenVTables::getVTableComponentType() const {
679
6.14k
  if (useRelativeLayout())
680
110
    return CGM.Int32Ty;
681
6.03k
  return CGM.Int8PtrTy;
682
6.14k
}
683
684
static void AddPointerLayoutOffset(const CodeGenModule &CGM,
685
                                   ConstantArrayBuilder &builder,
686
4.17k
                                   CharUnits offset) {
687
4.17k
  builder.add(llvm::ConstantExpr::getIntToPtr(
688
4.17k
      llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
689
4.17k
      CGM.Int8PtrTy));
690
4.17k
}
691
692
static void AddRelativeLayoutOffset(const CodeGenModule &CGM,
693
                                    ConstantArrayBuilder &builder,
694
93
                                    CharUnits offset) {
695
93
  builder.add(llvm::ConstantInt::get(CGM.Int32Ty, offset.getQuantity()));
696
93
}
697
698
void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
699
                                        const VTableLayout &layout,
700
                                        unsigned componentIndex,
701
                                        llvm::Constant *rtti,
702
                                        unsigned &nextVTableThunkIndex,
703
                                        unsigned vtableAddressPoint,
704
12.7k
                                        bool vtableHasLocalLinkage) {
705
12.7k
  auto &component = layout.vtable_components()[componentIndex];
706
707
12.7k
  auto addOffsetConstant =
708
12.7k
      useRelativeLayout() ? 
AddRelativeLayoutOffset260
:
AddPointerLayoutOffset12.4k
;
709
710
12.7k
  switch (component.getKind()) {
711
569
  case VTableComponent::CK_VCallOffset:
712
569
    return addOffsetConstant(CGM, builder, component.getVCallOffset());
713
714
1.18k
  case VTableComponent::CK_VBaseOffset:
715
1.18k
    return addOffsetConstant(CGM, builder, component.getVBaseOffset());
716
717
2.51k
  case VTableComponent::CK_OffsetToTop:
718
2.51k
    return addOffsetConstant(CGM, builder, component.getOffsetToTop());
719
720
2.76k
  case VTableComponent::CK_RTTI:
721
2.76k
    if (useRelativeLayout())
722
70
      return addRelativeComponent(builder, rtti, vtableAddressPoint,
723
70
                                  vtableHasLocalLinkage,
724
70
                                  /*isCompleteDtor=*/false);
725
2.69k
    else
726
2.69k
      return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
727
728
3.69k
  case VTableComponent::CK_FunctionPointer:
729
4.55k
  case VTableComponent::CK_CompleteDtorPointer:
730
5.67k
  case VTableComponent::CK_DeletingDtorPointer: {
731
5.67k
    GlobalDecl GD = component.getGlobalDecl();
732
733
5.67k
    if (CGM.getLangOpts().CUDA) {
734
      // Emit NULL for methods we can't codegen on this
735
      // side. Otherwise we'd end up with vtable with unresolved
736
      // references.
737
29
      const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
738
      // OK on device side: functions w/ __device__ attribute
739
      // OK on host side: anything except __device__-only functions.
740
29
      bool CanEmitMethod =
741
29
          CGM.getLangOpts().CUDAIsDevice
742
29
              ? 
MD->hasAttr<CUDADeviceAttr>()26
743
29
              : 
(3
MD->hasAttr<CUDAHostAttr>()3
||
!MD->hasAttr<CUDADeviceAttr>()3
);
744
29
      if (!CanEmitMethod)
745
2
        return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy));
746
      // Method is acceptable, continue processing as usual.
747
29
    }
748
749
5.67k
    auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
750
      // FIXME(PR43094): When merging comdat groups, lld can select a local
751
      // symbol as the signature symbol even though it cannot be accessed
752
      // outside that symbol's TU. The relative vtables ABI would make
753
      // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
754
      // depending on link order, the comdat groups could resolve to the one
755
      // with the local symbol. As a temporary solution, fill these components
756
      // with zero. We shouldn't be calling these in the first place anyway.
757
82
      if (useRelativeLayout())
758
1
        return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
759
760
      // For NVPTX devices in OpenMP emit special functon as null pointers,
761
      // otherwise linking ends up with unresolved references.
762
81
      if (CGM.getLangOpts().OpenMP && 
CGM.getLangOpts().OpenMPIsDevice5
&&
763
81
          
CGM.getTriple().isNVPTX()3
)
764
3
        return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
765
78
      llvm::FunctionType *fnTy =
766
78
          llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
767
78
      llvm::Constant *fn = cast<llvm::Constant>(
768
78
          CGM.CreateRuntimeFunction(fnTy, name).getCallee());
769
78
      if (auto f = dyn_cast<llvm::Function>(fn))
770
78
        f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
771
78
      return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
772
81
    };
773
774
5.67k
    llvm::Constant *fnPtr;
775
776
    // Pure virtual member functions.
777
5.67k
    if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
778
300
      if (!PureVirtualFn)
779
74
        PureVirtualFn =
780
74
            getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
781
300
      fnPtr = PureVirtualFn;
782
783
    // Deleted virtual member functions.
784
5.37k
    } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
785
13
      if (!DeletedVirtualFn)
786
8
        DeletedVirtualFn =
787
8
            getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
788
13
      fnPtr = DeletedVirtualFn;
789
790
    // Thunks.
791
5.36k
    } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
792
5.36k
               layout.vtable_thunks()[nextVTableThunkIndex].first ==
793
1.11k
                   componentIndex) {
794
643
      auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
795
796
643
      nextVTableThunkIndex++;
797
643
      fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
798
799
    // Otherwise we can use the method definition directly.
800
4.71k
    } else {
801
4.71k
      llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
802
4.71k
      fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
803
4.71k
    }
804
805
5.67k
    if (useRelativeLayout()) {
806
97
      return addRelativeComponent(
807
97
          builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
808
97
          component.getKind() == VTableComponent::CK_CompleteDtorPointer);
809
97
    } else
810
5.57k
      return builder.add(llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy));
811
5.67k
  }
812
813
44
  case VTableComponent::CK_UnusedFunctionPointer:
814
44
    if (useRelativeLayout())
815
0
      return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
816
44
    else
817
44
      return builder.addNullPointer(CGM.Int8PtrTy);
818
12.7k
  }
819
820
0
  llvm_unreachable("Unexpected vtable component kind");
821
0
}
822
823
3.36k
llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
824
3.36k
  SmallVector<llvm::Type *, 4> tys;
825
3.36k
  llvm::Type *componentType = getVTableComponentType();
826
7.27k
  for (unsigned i = 0, e = layout.getNumVTables(); i != e; 
++i3.91k
)
827
3.91k
    tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
828
829
3.36k
  return llvm::StructType::get(CGM.getLLVMContext(), tys);
830
3.36k
}
831
832
void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
833
                                             const VTableLayout &layout,
834
                                             llvm::Constant *rtti,
835
2.78k
                                             bool vtableHasLocalLinkage) {
836
2.78k
  llvm::Type *componentType = getVTableComponentType();
837
838
2.78k
  const auto &addressPoints = layout.getAddressPointIndices();
839
2.78k
  unsigned nextVTableThunkIndex = 0;
840
2.78k
  for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
841
6.10k
       vtableIndex != endIndex; 
++vtableIndex3.32k
) {
842
3.32k
    auto vtableElem = builder.beginArray(componentType);
843
844
3.32k
    size_t vtableStart = layout.getVTableOffset(vtableIndex);
845
3.32k
    size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
846
16.0k
    for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
847
12.7k
         ++componentIndex) {
848
12.7k
      addVTableComponent(vtableElem, layout, componentIndex, rtti,
849
12.7k
                         nextVTableThunkIndex, addressPoints[vtableIndex],
850
12.7k
                         vtableHasLocalLinkage);
851
12.7k
    }
852
3.32k
    vtableElem.finishAndAddTo(builder);
853
3.32k
  }
854
2.78k
}
855
856
llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable(
857
    const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
858
    llvm::GlobalVariable::LinkageTypes Linkage,
859
308
    VTableAddressPointsMapTy &AddressPoints) {
860
308
  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
861
41
    DI->completeClassData(Base.getBase());
862
863
308
  std::unique_ptr<VTableLayout> VTLayout(
864
308
      getItaniumVTableContext().createConstructionVTableLayout(
865
308
          Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
866
867
  // Add the address points.
868
308
  AddressPoints = VTLayout->getAddressPoints();
869
870
  // Get the mangled construction vtable name.
871
308
  SmallString<256> OutName;
872
308
  llvm::raw_svector_ostream Out(OutName);
873
308
  cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
874
308
      .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
875
308
                           Base.getBase(), Out);
876
308
  SmallString<256> Name(OutName);
877
878
308
  bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
879
308
  bool VTableAliasExists =
880
308
      UsingRelativeLayout && 
CGM.getModule().getNamedAlias(Name)4
;
881
308
  if (VTableAliasExists) {
882
    // We previously made the vtable hidden and changed its name.
883
2
    Name.append(".local");
884
2
  }
885
886
308
  llvm::Type *VTType = getVTableType(*VTLayout);
887
888
  // Construction vtable symbols are not part of the Itanium ABI, so we cannot
889
  // guarantee that they actually will be available externally. Instead, when
890
  // emitting an available_externally VTT, we provide references to an internal
891
  // linkage construction vtable. The ABI only requires complete-object vtables
892
  // to be the same for all instances of a type, not construction vtables.
893
308
  if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
894
6
    Linkage = llvm::GlobalVariable::InternalLinkage;
895
896
308
  unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
897
898
  // Create the variable that will hold the construction vtable.
899
308
  llvm::GlobalVariable *VTable =
900
308
      CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
901
902
  // V-tables are always unnamed_addr.
903
308
  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
904
905
308
  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
906
308
      CGM.getContext().getTagDeclType(Base.getBase()));
907
908
  // Create and set the initializer.
909
308
  ConstantInitBuilder builder(CGM);
910
308
  auto components = builder.beginStruct();
911
308
  createVTableInitializer(components, *VTLayout, RTTI,
912
308
                          VTable->hasLocalLinkage());
913
308
  components.finishAndSetAsInitializer(VTable);
914
915
  // Set properties only after the initializer has been set to ensure that the
916
  // GV is treated as definition and not declaration.
917
308
  assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
918
0
  CGM.setGVProperties(VTable, RD);
919
920
308
  CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
921
922
308
  if (UsingRelativeLayout && 
!VTable->isDSOLocal()4
)
923
2
    GenerateRelativeVTableAlias(VTable, OutName);
924
925
308
  return VTable;
926
308
}
927
928
// If the VTable is not dso_local, then we will not be able to indicate that
929
// the VTable does not need a relocation and move into rodata. A frequent
930
// time this can occur is for classes that should be made public from a DSO
931
// (like in libc++). For cases like these, we can make the vtable hidden or
932
// private and create a public alias with the same visibility and linkage as
933
// the original vtable type.
934
void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
935
51
                                                 llvm::StringRef AliasNameRef) {
936
51
  assert(getItaniumVTableContext().isRelativeLayout() &&
937
51
         "Can only use this if the relative vtable ABI is used");
938
0
  assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
939
51
                                  "not guaranteed to be dso_local");
940
941
  // If the vtable is available_externally, we shouldn't (or need to) generate
942
  // an alias for it in the first place since the vtable won't actually by
943
  // emitted in this compilation unit.
944
51
  if (VTable->hasAvailableExternallyLinkage())
945
2
    return;
946
947
  // Create a new string in the event the alias is already the name of the
948
  // vtable. Using the reference directly could lead to use of an inititialized
949
  // value in the module's StringMap.
950
49
  llvm::SmallString<256> AliasName(AliasNameRef);
951
49
  VTable->setName(AliasName + ".local");
952
953
49
  auto Linkage = VTable->getLinkage();
954
49
  assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
955
49
         "Invalid vtable alias linkage");
956
957
0
  llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
958
49
  if (!VTableAlias) {
959
49
    VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
960
49
                                            VTable->getAddressSpace(), Linkage,
961
49
                                            AliasName, &CGM.getModule());
962
49
  } else {
963
0
    assert(VTableAlias->getValueType() == VTable->getValueType());
964
0
    assert(VTableAlias->getLinkage() == Linkage);
965
0
  }
966
0
  VTableAlias->setVisibility(VTable->getVisibility());
967
49
  VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
968
969
  // Both of these imply dso_local for the vtable.
970
49
  if (!VTable->hasComdat()) {
971
    // If this is in a comdat, then we shouldn't make the linkage private due to
972
    // an issue in lld where private symbols can be used as the key symbol when
973
    // choosing the prevelant group. This leads to "relocation refers to a
974
    // symbol in a discarded section".
975
39
    VTable->setLinkage(llvm::GlobalValue::PrivateLinkage);
976
39
  } else {
977
    // We should at least make this hidden since we don't want to expose it.
978
10
    VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
979
10
  }
980
981
49
  VTableAlias->setAliasee(VTable);
982
49
}
983
984
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
985
1.30k
                                                const CXXRecordDecl *RD) {
986
1.30k
  return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
987
1.30k
         
CGM.getCXXABI().canSpeculativelyEmitVTable(RD)136
;
988
1.30k
}
989
990
/// Compute the required linkage of the vtable for the given class.
991
///
992
/// Note that we only call this at the end of the translation unit.
993
llvm::GlobalVariable::LinkageTypes
994
8.88k
CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
995
8.88k
  if (!RD->isExternallyVisible())
996
165
    return llvm::GlobalVariable::InternalLinkage;
997
998
  // We're at the end of the translation unit, so the current key
999
  // function is fully correct.
1000
8.71k
  const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
1001
8.71k
  if (keyFunction && 
!RD->hasAttr<DLLImportAttr>()3.45k
) {
1002
    // If this class has a key function, use that to determine the
1003
    // linkage of the vtable.
1004
3.44k
    const FunctionDecl *def = nullptr;
1005
3.44k
    if (keyFunction->hasBody(def))
1006
1.41k
      keyFunction = cast<CXXMethodDecl>(def);
1007
1008
3.44k
    switch (keyFunction->getTemplateSpecializationKind()) {
1009
3.44k
      case TSK_Undeclared:
1010
3.44k
      case TSK_ExplicitSpecialization:
1011
3.44k
        assert((def || CodeGenOpts.OptimizationLevel > 0 ||
1012
3.44k
                CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
1013
3.44k
               "Shouldn't query vtable linkage without key function, "
1014
3.44k
               "optimizations, or debug info");
1015
3.44k
        if (!def && 
CodeGenOpts.OptimizationLevel > 02.02k
)
1016
112
          return llvm::GlobalVariable::AvailableExternallyLinkage;
1017
1018
3.33k
        if (keyFunction->isInlined())
1019
73
          return !Context.getLangOpts().AppleKext ?
1020
73
                   llvm::GlobalVariable::LinkOnceODRLinkage :
1021
73
                   
llvm::Function::InternalLinkage0
;
1022
1023
3.25k
        return llvm::GlobalVariable::ExternalLinkage;
1024
1025
0
      case TSK_ImplicitInstantiation:
1026
0
        return !Context.getLangOpts().AppleKext ?
1027
0
                 llvm::GlobalVariable::LinkOnceODRLinkage :
1028
0
                 llvm::Function::InternalLinkage;
1029
1030
0
      case TSK_ExplicitInstantiationDefinition:
1031
0
        return !Context.getLangOpts().AppleKext ?
1032
0
                 llvm::GlobalVariable::WeakODRLinkage :
1033
0
                 llvm::Function::InternalLinkage;
1034
1035
0
      case TSK_ExplicitInstantiationDeclaration:
1036
0
        llvm_unreachable("Should not have been asked to emit this");
1037
3.44k
    }
1038
3.44k
  }
1039
1040
  // -fapple-kext mode does not support weak linkage, so we must use
1041
  // internal linkage.
1042
5.27k
  if (Context.getLangOpts().AppleKext)
1043
5
    return llvm::Function::InternalLinkage;
1044
1045
5.27k
  llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1046
5.27k
      llvm::GlobalValue::LinkOnceODRLinkage;
1047
5.27k
  llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1048
5.27k
      llvm::GlobalValue::WeakODRLinkage;
1049
5.27k
  if (RD->hasAttr<DLLExportAttr>()) {
1050
    // Cannot discard exported vtables.
1051
94
    DiscardableODRLinkage = NonDiscardableODRLinkage;
1052
5.17k
  } else if (RD->hasAttr<DLLImportAttr>()) {
1053
    // Imported vtables are available externally.
1054
48
    DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1055
48
    NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1056
48
  }
1057
1058
5.27k
  switch (RD->getTemplateSpecializationKind()) {
1059
3.65k
    case TSK_Undeclared:
1060
3.66k
    case TSK_ExplicitSpecialization:
1061
4.50k
    case TSK_ImplicitInstantiation:
1062
4.50k
      return DiscardableODRLinkage;
1063
1064
622
    case TSK_ExplicitInstantiationDeclaration:
1065
      // Explicit instantiations in MSVC do not provide vtables, so we must emit
1066
      // our own.
1067
622
      if (getTarget().getCXXABI().isMicrosoft())
1068
7
        return DiscardableODRLinkage;
1069
615
      return shouldEmitAvailableExternallyVTable(*this, RD)
1070
615
                 ? 
llvm::GlobalVariable::AvailableExternallyLinkage9
1071
615
                 : 
llvm::GlobalVariable::ExternalLinkage606
;
1072
1073
139
    case TSK_ExplicitInstantiationDefinition:
1074
139
      return NonDiscardableODRLinkage;
1075
5.27k
  }
1076
1077
0
  llvm_unreachable("Invalid TemplateSpecializationKind!");
1078
0
}
1079
1080
/// This is a callback from Sema to tell us that a particular vtable is
1081
/// required to be emitted in this translation unit.
1082
///
1083
/// This is only called for vtables that _must_ be emitted (mainly due to key
1084
/// functions).  For weak vtables, CodeGen tracks when they are needed and
1085
/// emits them as-needed.
1086
797
void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
1087
797
  VTables.GenerateClassData(theClass);
1088
797
}
1089
1090
void
1091
3.26k
CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
1092
3.26k
  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1093
681
    DI->completeClassData(RD);
1094
1095
3.26k
  if (RD->getNumVBases())
1096
741
    CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1097
1098
3.26k
  CGM.getCXXABI().emitVTableDefinitions(*this, RD);
1099
3.26k
}
1100
1101
/// At this point in the translation unit, does it appear that can we
1102
/// rely on the vtable being defined elsewhere in the program?
1103
///
1104
/// The response is really only definitive when called at the end of
1105
/// the translation unit.
1106
///
1107
/// The only semantic restriction here is that the object file should
1108
/// not contain a vtable definition when that vtable is defined
1109
/// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
1110
/// vtables when unnecessary.
1111
5.63k
bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
1112
5.63k
  assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
1113
1114
  // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1115
  // emit them even if there is an explicit template instantiation.
1116
5.63k
  if (CGM.getTarget().getCXXABI().isMicrosoft())
1117
803
    return false;
1118
1119
  // If we have an explicit instantiation declaration (and not a
1120
  // definition), the vtable is defined elsewhere.
1121
4.82k
  TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1122
4.82k
  if (TSK == TSK_ExplicitInstantiationDeclaration)
1123
82
    return true;
1124
1125
  // Otherwise, if the class is an instantiated template, the
1126
  // vtable must be defined here.
1127
4.74k
  if (TSK == TSK_ImplicitInstantiation ||
1128
4.74k
      
TSK == TSK_ExplicitInstantiationDefinition4.31k
)
1129
563
    return false;
1130
1131
  // Otherwise, if the class doesn't have a key function (possibly
1132
  // anymore), the vtable must be defined here.
1133
4.18k
  const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1134
4.18k
  if (!keyFunction)
1135
1.71k
    return false;
1136
1137
  // Otherwise, if we don't have a definition of the key function, the
1138
  // vtable must be defined somewhere else.
1139
2.46k
  return !keyFunction->hasBody();
1140
4.18k
}
1141
1142
/// Given that we're currently at the end of the translation unit, and
1143
/// we've emitted a reference to the vtable for this class, should
1144
/// we define that vtable?
1145
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
1146
3.04k
                                                   const CXXRecordDecl *RD) {
1147
  // If vtable is internal then it has to be done.
1148
3.04k
  if (!CGM.getVTables().isVTableExternal(RD))
1149
2.35k
    return true;
1150
1151
  // If it's external then maybe we will need it as available_externally.
1152
685
  return shouldEmitAvailableExternallyVTable(CGM, RD);
1153
3.04k
}
1154
1155
/// Given that at some point we emitted a reference to one or more
1156
/// vtables, and that we are now at the end of the translation unit,
1157
/// decide whether we should emit them.
1158
2.34k
void CodeGenModule::EmitDeferredVTables() {
1159
2.34k
#ifndef NDEBUG
1160
  // Remember the size of DeferredVTables, because we're going to assume
1161
  // that this entire operation doesn't modify it.
1162
2.34k
  size_t savedSize = DeferredVTables.size();
1163
2.34k
#endif
1164
1165
2.34k
  for (const CXXRecordDecl *RD : DeferredVTables)
1166
3.04k
    if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
1167
2.46k
      VTables.GenerateClassData(RD);
1168
582
    else if (shouldOpportunisticallyEmitVTables())
1169
24
      OpportunisticVTables.push_back(RD);
1170
1171
2.34k
  assert(savedSize == DeferredVTables.size() &&
1172
2.34k
         "deferred extra vtables during vtable emission?");
1173
0
  DeferredVTables.clear();
1174
2.34k
}
1175
1176
363
bool CodeGenModule::HasLTOVisibilityPublicStd(const CXXRecordDecl *RD) {
1177
363
  if (!getCodeGenOpts().LTOVisibilityPublicStd)
1178
346
    return false;
1179
1180
17
  const DeclContext *DC = RD;
1181
28
  while (1) {
1182
28
    auto *D = cast<Decl>(DC);
1183
28
    DC = DC->getParent();
1184
28
    if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1185
17
      if (auto *ND = dyn_cast<NamespaceDecl>(D))
1186
9
        if (const IdentifierInfo *II = ND->getIdentifier())
1187
8
          if (II->isStr("std") || 
II->isStr("stdext")4
)
1188
6
            return true;
1189
11
      break;
1190
17
    }
1191
28
  }
1192
1193
11
  return false;
1194
17
}
1195
1196
543
bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1197
543
  LinkageInfo LV = RD->getLinkageAndVisibility();
1198
543
  if (!isExternallyVisible(LV.getLinkage()))
1199
134
    return true;
1200
1201
409
  if (RD->hasAttr<LTOVisibilityPublicAttr>() || 
RD->hasAttr<UuidAttr>()388
)
1202
24
    return false;
1203
1204
385
  if (getTriple().isOSBinFormatCOFF()) {
1205
105
    if (RD->hasAttr<DLLExportAttr>() || 
RD->hasAttr<DLLImportAttr>()103
)
1206
4
      return false;
1207
280
  } else {
1208
280
    if (LV.getVisibility() != HiddenVisibility)
1209
94
      return false;
1210
280
  }
1211
1212
287
  return !HasLTOVisibilityPublicStd(RD);
1213
385
}
1214
1215
llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
1216
235
    const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1217
  // If we have already visited this RD (which means this is a recursive call
1218
  // since the initial call should have an empty Visited set), return the max
1219
  // visibility. The recursive calls below compute the min between the result
1220
  // of the recursive call and the current TypeVis, so returning the max here
1221
  // ensures that it will have no effect on the current TypeVis.
1222
235
  if (!Visited.insert(RD).second)
1223
79
    return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1224
1225
156
  LinkageInfo LV = RD->getLinkageAndVisibility();
1226
156
  llvm::GlobalObject::VCallVisibility TypeVis;
1227
156
  if (!isExternallyVisible(LV.getLinkage()))
1228
34
    TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1229
122
  else if (HasHiddenLTOVisibility(RD))
1230
75
    TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1231
47
  else
1232
47
    TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1233
1234
156
  for (auto B : RD->bases())
1235
97
    if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1236
97
      TypeVis = std::min(
1237
97
          TypeVis,
1238
97
          GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1239
1240
156
  for (auto B : RD->vbases())
1241
63
    if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1242
63
      TypeVis = std::min(
1243
63
          TypeVis,
1244
63
          GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1245
1246
156
  return TypeVis;
1247
235
}
1248
1249
void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1250
                                           llvm::GlobalVariable *VTable,
1251
1.83k
                                           const VTableLayout &VTLayout) {
1252
1.83k
  if (!getCodeGenOpts().LTOUnit)
1253
1.75k
    return;
1254
1255
77
  CharUnits PointerWidth =
1256
77
      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1257
1258
77
  typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1259
77
  std::vector<AddressPoint> AddressPoints;
1260
77
  for (auto &&AP : VTLayout.getAddressPoints())
1261
143
    AddressPoints.push_back(std::make_pair(
1262
143
        AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1263
143
                                AP.second.AddressPointIndex));
1264
1265
  // Sort the address points for determinism.
1266
77
  llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1267
77
                                   const AddressPoint &AP2) {
1268
77
    if (&AP1 == &AP2)
1269
0
      return false;
1270
1271
77
    std::string S1;
1272
77
    llvm::raw_string_ostream O1(S1);
1273
77
    getCXXABI().getMangleContext().mangleTypeName(
1274
77
        QualType(AP1.first->getTypeForDecl(), 0), O1);
1275
77
    O1.flush();
1276
1277
77
    std::string S2;
1278
77
    llvm::raw_string_ostream O2(S2);
1279
77
    getCXXABI().getMangleContext().mangleTypeName(
1280
77
        QualType(AP2.first->getTypeForDecl(), 0), O2);
1281
77
    O2.flush();
1282
1283
77
    if (S1 < S2)
1284
41
      return true;
1285
36
    if (S1 != S2)
1286
36
      return false;
1287
1288
0
    return AP1.second < AP2.second;
1289
36
  });
1290
1291
77
  ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1292
143
  for (auto AP : AddressPoints) {
1293
    // Create type metadata for the address point.
1294
143
    AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1295
1296
    // The class associated with each address point could also potentially be
1297
    // used for indirect calls via a member function pointer, so we need to
1298
    // annotate the address of each function pointer with the appropriate member
1299
    // function pointer type.
1300
1.05k
    for (unsigned I = 0; I != Comps.size(); 
++I912
) {
1301
912
      if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1302
659
        continue;
1303
253
      llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1304
253
          Context.getMemberPointerType(
1305
253
              Comps[I].getFunctionDecl()->getType(),
1306
253
              Context.getRecordType(AP.first).getTypePtr()));
1307
253
      VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1308
253
    }
1309
143
  }
1310
1311
77
  if (getCodeGenOpts().VirtualFunctionElimination ||
1312
77
      
getCodeGenOpts().WholeProgramVTables70
) {
1313
52
    llvm::DenseSet<const CXXRecordDecl *> Visited;
1314
52
    llvm::GlobalObject::VCallVisibility TypeVis =
1315
52
        GetVCallVisibilityLevel(RD, Visited);
1316
52
    if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1317
23
      VTable->setVCallVisibilityMetadata(TypeVis);
1318
52
  }
1319
77
}