Coverage Report

Created: 2020-02-15 09:57

/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
25.7k
    : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33
34
llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
35
1.04k
                                              GlobalDecl GD) {
36
1.04k
  return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
37
1.04k
                                 /*DontDefer=*/true, /*IsThunk=*/true);
38
1.04k
}
39
40
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
41
                               llvm::Function *ThunkFn, bool ForVTable,
42
623
                               GlobalDecl GD) {
43
623
  CGM.setFunctionLinkage(GD, ThunkFn);
44
623
  CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
45
623
                                  !Thunk.Return.isEmpty());
46
623
47
623
  // Set the right visibility.
48
623
  CGM.setGVProperties(ThunkFn, GD);
49
623
50
623
  if (!CGM.getCXXABI().exportThunk()) {
51
268
    ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
52
268
    ThunkFn->setDSOLocal(true);
53
268
  }
54
623
55
623
  if (CGM.supportsCOMDAT() && 
ThunkFn->isWeakForLinker()437
)
56
322
    ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
57
623
}
58
59
#ifndef NDEBUG
60
static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61
1.02k
                    const ABIArgInfo &infoR, CanQualType typeR) {
62
1.02k
  return (infoL.getKind() == infoR.getKind() &&
63
1.02k
          (typeL == typeR ||
64
1.02k
           
(100
isa<PointerType>(typeL)100
&&
isa<PointerType>(typeR)100
) ||
65
1.02k
           
(0
isa<ReferenceType>(typeL)0
&&
isa<ReferenceType>(typeR)0
)));
66
1.02k
}
67
#endif
68
69
static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70
                                      QualType ResultType, RValue RV,
71
64
                                      const ThunkInfo &Thunk) {
72
64
  // Emit the return adjustment.
73
64
  bool NullCheckValue = !ResultType->isReferenceType();
74
64
75
64
  llvm::BasicBlock *AdjustNull = nullptr;
76
64
  llvm::BasicBlock *AdjustNotNull = nullptr;
77
64
  llvm::BasicBlock *AdjustEnd = nullptr;
78
64
79
64
  llvm::Value *ReturnValue = RV.getScalarVal();
80
64
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
57
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
64
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
64
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
57
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
64
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
7
  // 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
3
127
3
  // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
128
3
  // 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
9
164
9
  // Get the original function
165
9
  assert(FnInfo.isVariadic());
166
9
  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
9
170
9
  // Cloning can't work if we don't have a definition. The Microsoft ABI may
171
9
  // require thunks when a definition is not available. Emit an error in these
172
9
  // 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
7
179
7
  // Clone to thunk.
180
7
  llvm::ValueToValueMapTy VMap;
181
7
182
7
  // We are cloning a function while some Metadata nodes are still unresolved.
183
7
  // 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
7
191
7
  // "Initialize" CGF (minimally).
192
7
  CurFn = Fn;
193
7
194
7
  // Get the "this" value
195
7
  llvm::Function::arg_iterator AI = Fn->arg_begin();
196
7
  if (CGM.ReturnTypeUsesSRet(FnInfo))
197
0
    ++AI;
198
7
199
7
  // Find the first store of "this", which will be to the alloca associated
200
7
  // 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
7
  // Adjust "this", if necessary.
211
7
  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
7
218
7
  if (!Thunk.Return.isEmpty()) {
219
5
    // 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
7
233
7
  return Fn;
234
7
}
235
236
void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
237
                                 const CGFunctionInfo &FnInfo,
238
582
                                 bool IsUnprototyped) {
239
582
  assert(!CurGD.getDecl() && "CurGD was already set!");
240
582
  CurGD = GD;
241
582
  CurFuncIsThunk = true;
242
582
243
582
  // Build FunctionArgs.
244
582
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
245
582
  QualType ThisType = MD->getThisType();
246
582
  QualType ResultType;
247
582
  if (IsUnprototyped)
248
6
    ResultType = CGM.getContext().VoidTy;
249
576
  else if (CGM.getCXXABI().HasThisReturn(GD))
250
12
    ResultType = ThisType;
251
564
  else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
252
94
    ResultType = CGM.getContext().VoidPtrTy;
253
470
  else
254
470
    ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
255
582
  FunctionArgList FunctionArgs;
256
582
257
582
  // Create the implicit 'this' parameter declaration.
258
582
  CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
259
582
260
582
  // Add the rest of the parameters, if we have a prototype to work with.
261
582
  if (!IsUnprototyped) {
262
576
    FunctionArgs.append(MD->param_begin(), MD->param_end());
263
576
264
576
    if (isa<CXXDestructorDecl>(MD))
265
243
      CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
266
243
                                                FunctionArgs);
267
576
  }
268
582
269
582
  // Start defining the function.
270
582
  auto NL = ApplyDebugLocation::CreateEmpty(*this);
271
582
  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
272
582
                MD->getLocation());
273
582
  // Create a scope with an artificial location for the body of this function.
274
582
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
275
582
276
582
  // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
277
582
  CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
278
582
  CXXThisValue = CXXABIThisValue;
279
582
  CurCodeDecl = MD;
280
582
  CurFuncDecl = MD;
281
582
}
282
283
565
void CodeGenFunction::FinishThunk() {
284
565
  // Clear these to restore the invariants expected by
285
565
  // StartFunction/FinishFunction.
286
565
  CurCodeDecl = nullptr;
287
565
  CurFuncDecl = nullptr;
288
565
289
565
  FinishFunction();
290
565
}
291
292
void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
293
                                                const ThunkInfo *Thunk,
294
582
                                                bool IsUnprototyped) {
295
582
  assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
296
582
         "Please use a new CGF for this thunk");
297
582
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
298
582
299
582
  // Adjust the 'this' pointer if necessary
300
582
  llvm::Value *AdjustedThisPtr =
301
582
    Thunk ? CGM.getCXXABI().performThisAdjustment(
302
582
                          *this, LoadCXXThisAddress(), Thunk->This)
303
582
          : 
LoadCXXThis()0
;
304
582
305
582
  // If perfect forwarding is required a variadic method, a method using
306
582
  // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
307
582
  // thunk requires a return adjustment, since that is impossible with musttail.
308
582
  if (CurFnInfo->usesInAlloca() || 
CurFnInfo->isVariadic()578
||
IsUnprototyped565
) {
309
17
    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
1
        
llvm_unreachable0
("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
17
    EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
321
17
    return;
322
565
  }
323
565
324
565
  // Start building CallArgs.
325
565
  CallArgList CallArgs;
326
565
  QualType ThisType = MD->getThisType();
327
565
  CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
328
565
329
565
  if (isa<CXXDestructorDecl>(MD))
330
243
    CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
331
565
332
565
#ifndef NDEBUG
333
565
  unsigned PrefixArgs = CallArgs.size() - 1;
334
565
#endif
335
565
  // Add the rest of the arguments.
336
565
  for (const ParmVarDecl *PD : MD->parameters())
337
47
    EmitDelegateCallArg(CallArgs, PD, SourceLocation());
338
565
339
565
  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
340
565
341
565
#ifndef NDEBUG
342
565
  const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
343
565
      CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
344
565
  assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
345
565
         CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
346
565
         CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
347
565
  assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
348
565
         similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
349
565
                 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
350
565
  assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
351
1.27k
  for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; 
++i706
)
352
565
    assert(similar(CallFnInfo.arg_begin()[i].info,
353
565
                   CallFnInfo.arg_begin()[i].type,
354
565
                   CurFnInfo->arg_begin()[i].info,
355
565
                   CurFnInfo->arg_begin()[i].type));
356
565
#endif
357
565
358
565
  // Determine whether we have a return value slot to use.
359
565
  QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
360
565
                            ? 
ThisType12
361
565
                            : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
362
553
                                  ? 
CGM.getContext().VoidPtrTy94
363
553
                                  : 
FPT->getReturnType()459
;
364
565
  ReturnValueSlot Slot;
365
565
  if (!ResultType->isVoidType() &&
366
565
      
CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect203
)
367
9
    Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
368
565
369
565
  // Now emit our call.
370
565
  llvm::CallBase *CallOrInvoke;
371
565
  RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
372
565
                       CallArgs, &CallOrInvoke);
373
565
374
565
  // Consider return adjustment if we have ThunkInfo.
375
565
  if (Thunk && !Thunk->Return.isEmpty())
376
59
    RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
377
506
  else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
378
506
    Call->setTailCallKind(llvm::CallInst::TCK_Tail);
379
565
380
565
  // Emit return.
381
565
  if (!ResultType->isVoidType() && 
Slot.isNull()203
)
382
194
    CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
383
565
384
565
  // Disable the final ARC autorelease.
385
565
  AutoreleaseResult = false;
386
565
387
565
  FinishThunk();
388
565
}
389
390
void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
391
                                        llvm::Value *AdjustedThisPtr,
392
65
                                        llvm::FunctionCallee Callee) {
393
65
  // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
394
65
  // to translate AST arguments into LLVM IR arguments.  For thunks, we know
395
65
  // that the caller prototype more or less matches the callee prototype with
396
65
  // the exception of 'this'.
397
65
  SmallVector<llvm::Value *, 8> Args;
398
65
  for (llvm::Argument &A : CurFn->args())
399
74
    Args.push_back(&A);
400
65
401
65
  // Set the adjusted 'this' pointer.
402
65
  const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
403
65
  if (ThisAI.isDirect()) {
404
63
    const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
405
63
    int ThisArgNo = RetAI.isIndirect() && 
!RetAI.isSRetAfterThis()0
?
10
: 0;
406
63
    llvm::Type *ThisType = Args[ThisArgNo]->getType();
407
63
    if (ThisType != AdjustedThisPtr->getType())
408
9
      AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
409
63
    Args[ThisArgNo] = AdjustedThisPtr;
410
63
  } else {
411
2
    assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
412
2
    Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
413
2
    llvm::Type *ThisType = ThisAddr.getElementType();
414
2
    if (ThisType != AdjustedThisPtr->getType())
415
2
      AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
416
2
    Builder.CreateStore(AdjustedThisPtr, ThisAddr);
417
2
  }
418
65
419
65
  // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
420
65
  // don't actually want to run them.
421
65
  llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
422
65
  Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
423
65
424
65
  // Apply the standard set of call attributes.
425
65
  unsigned CallingConv;
426
65
  llvm::AttributeList Attrs;
427
65
  CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
428
65
                             Attrs, CallingConv, /*AttrOnCallSite=*/true);
429
65
  Call->setAttributes(Attrs);
430
65
  Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
431
65
432
65
  if (Call->getType()->isVoidTy())
433
60
    Builder.CreateRetVoid();
434
5
  else
435
5
    Builder.CreateRet(Call);
436
65
437
65
  // Finish the function to maintain CodeGenFunction invariants.
438
65
  // FIXME: Don't emit unreachable code.
439
65
  EmitBlock(createBasicBlock());
440
65
  FinishFunction();
441
65
}
442
443
void CodeGenFunction::generateThunk(llvm::Function *Fn,
444
                                    const CGFunctionInfo &FnInfo, GlobalDecl GD,
445
                                    const ThunkInfo &Thunk,
446
582
                                    bool IsUnprototyped) {
447
582
  StartThunk(Fn, GD, FnInfo, IsUnprototyped);
448
582
  // Create a scope with an artificial location for the body of this function.
449
582
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
450
582
451
582
  // Get our callee. Use a placeholder type if this method is unprototyped so
452
582
  // that CodeGenModule doesn't try to set attributes.
453
582
  llvm::Type *Ty;
454
582
  if (IsUnprototyped)
455
6
    Ty = llvm::StructType::get(getLLVMContext());
456
576
  else
457
576
    Ty = CGM.getTypes().GetFunctionType(FnInfo);
458
582
459
582
  llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
460
582
461
582
  // Fix up the function type for an unprototyped musttail call.
462
582
  if (IsUnprototyped)
463
6
    Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
464
582
465
582
  // Make the call and return the result.
466
582
  EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
467
582
                            &Thunk, IsUnprototyped);
468
582
}
469
470
static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
471
1.04k
                                  bool IsUnprototyped, bool ForVTable) {
472
1.04k
  // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
473
1.04k
  // provide thunks for us.
474
1.04k
  if (CGM.getTarget().getCXXABI().isMicrosoft())
475
383
    return true;
476
666
477
666
  // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
478
666
  // definitions of the main method. Therefore, emitting thunks with the vtable
479
666
  // is purely an optimization. Emit the thunk if optimizations are enabled and
480
666
  // all of the parameter types are complete.
481
666
  if (ForVTable)
482
352
    return CGM.getCodeGenOpts().OptimizationLevel && 
!IsUnprototyped62
;
483
314
484
314
  // Always emit thunks along with the method definition.
485
314
  return true;
486
314
}
487
488
llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
489
                                               const ThunkInfo &TI,
490
1.04k
                                               bool ForVTable) {
491
1.04k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
492
1.04k
493
1.04k
  // First, get a declaration. Compute the mangled name. Don't worry about
494
1.04k
  // getting the function prototype right, since we may only need this
495
1.04k
  // declaration to fill in a vtable slot.
496
1.04k
  SmallString<256> Name;
497
1.04k
  MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
498
1.04k
  llvm::raw_svector_ostream Out(Name);
499
1.04k
  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
500
489
    MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
501
560
  else
502
560
    MCtx.mangleThunk(MD, TI, Out);
503
1.04k
  llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
504
1.04k
  llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
505
1.04k
506
1.04k
  // If we don't need to emit a definition, return this declaration as is.
507
1.04k
  bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
508
1.04k
      MD->getType()->castAs<FunctionType>());
509
1.04k
  if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
510
294
    return Thunk;
511
755
512
755
  // Arrange a function prototype appropriate for a function definition. In some
513
755
  // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
514
755
  const CGFunctionInfo &FnInfo =
515
755
      IsUnprototyped ? 
CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)6
516
755
                     : 
CGM.getTypes().arrangeGlobalDeclaration(GD)749
;
517
755
  llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
518
755
519
755
  // If the type of the underlying GlobalValue is wrong, we'll have to replace
520
755
  // it. It should be a declaration.
521
755
  llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
522
755
  if (ThunkFn->getFunctionType() != ThunkFnTy) {
523
7
    llvm::GlobalValue *OldThunkFn = ThunkFn;
524
7
525
7
    assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
526
7
527
7
    // Remove the name from the old thunk function and get a new thunk.
528
7
    OldThunkFn->setName(StringRef());
529
7
    ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
530
7
                                     Name.str(), &CGM.getModule());
531
7
    CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
532
7
533
7
    // If needed, replace the old thunk with a bitcast.
534
7
    if (!OldThunkFn->use_empty()) {
535
7
      llvm::Constant *NewPtrForOldDecl =
536
7
          llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
537
7
      OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
538
7
    }
539
7
540
7
    // Remove the old thunk.
541
7
    OldThunkFn->eraseFromParent();
542
7
  }
543
755
544
755
  bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
545
755
  bool UseAvailableExternallyLinkage = ForVTable && 
ABIHasKeyFunctions327
;
546
755
547
755
  if (!ThunkFn->isDeclaration()) {
548
162
    if (!ABIHasKeyFunctions || 
UseAvailableExternallyLinkage47
) {
549
130
      // There is already a thunk emitted for this function, do nothing.
550
130
      return ThunkFn;
551
130
    }
552
32
553
32
    setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
554
32
    return ThunkFn;
555
32
  }
556
593
557
593
  // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
558
593
  // that the return type is meaningless. These thunks can be used to call
559
593
  // functions with differing return types, and the caller is required to cast
560
593
  // the prototype appropriately to extract the correct value.
561
593
  if (IsUnprototyped)
562
6
    ThunkFn->addFnAttr("thunk");
563
593
564
593
  CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
565
593
566
593
  // Thunks for variadic methods are special because in general variadic
567
593
  // arguments cannot be perferctly forwarded. In the general case, clang
568
593
  // implements such thunks by cloning the original function body. However, for
569
593
  // thunks with no return adjustment on targets that support musttail, we can
570
593
  // use musttail to perfectly forward the variadic arguments.
571
593
  bool ShouldCloneVarArgs = false;
572
593
  if (!IsUnprototyped && 
ThunkFn->isVarArg()587
) {
573
18
    ShouldCloneVarArgs = true;
574
18
    if (TI.Return.isEmpty()) {
575
11
      switch (CGM.getTriple().getArch()) {
576
7
      case llvm::Triple::x86_64:
577
7
      case llvm::Triple::x86:
578
7
      case llvm::Triple::aarch64:
579
7
        ShouldCloneVarArgs = false;
580
7
        break;
581
7
      default:
582
4
        break;
583
593
      }
584
593
    }
585
18
  }
586
593
587
593
  if (ShouldCloneVarArgs) {
588
11
    if (UseAvailableExternallyLinkage)
589
2
      return ThunkFn;
590
9
    ThunkFn =
591
9
        CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
592
582
  } else {
593
582
    // Normal thunk body generation.
594
582
    CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
595
582
  }
596
593
597
593
  setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
598
591
  return ThunkFn;
599
593
}
600
601
3.94k
void CodeGenVTables::EmitThunks(GlobalDecl GD) {
602
3.94k
  const CXXMethodDecl *MD =
603
3.94k
    cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
604
3.94k
605
3.94k
  // We don't need to generate thunks for the base destructor.
606
3.94k
  if (isa<CXXDestructorDecl>(MD) && 
GD.getDtorType() == Dtor_Base2.32k
)
607
795
    return;
608
3.15k
609
3.15k
  const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
610
3.15k
      VTContext->getThunkInfo(GD);
611
3.15k
612
3.15k
  if (!ThunkInfoVector)
613
2.75k
    return;
614
403
615
403
  for (const ThunkInfo& Thunk : *ThunkInfoVector)
616
428
    maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
617
403
}
618
619
void CodeGenVTables::addVTableComponent(
620
    ConstantArrayBuilder &builder, const VTableLayout &layout,
621
11.7k
    unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
622
11.7k
  auto &component = layout.vtable_components()[idx];
623
11.7k
624
11.7k
  auto addOffsetConstant = [&](CharUnits offset) {
625
3.99k
    builder.add(llvm::ConstantExpr::getIntToPtr(
626
3.99k
        llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
627
3.99k
        CGM.Int8PtrTy));
628
3.99k
  };
629
11.7k
630
11.7k
  switch (component.getKind()) {
631
548
  case VTableComponent::CK_VCallOffset:
632
548
    return addOffsetConstant(component.getVCallOffset());
633
0
634
1.16k
  case VTableComponent::CK_VBaseOffset:
635
1.16k
    return addOffsetConstant(component.getVBaseOffset());
636
0
637
2.28k
  case VTableComponent::CK_OffsetToTop:
638
2.28k
    return addOffsetConstant(component.getOffsetToTop());
639
0
640
2.52k
  case VTableComponent::CK_RTTI:
641
2.52k
    return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
642
0
643
5.23k
  case VTableComponent::CK_FunctionPointer:
644
5.23k
  case VTableComponent::CK_CompleteDtorPointer:
645
5.23k
  case VTableComponent::CK_DeletingDtorPointer: {
646
5.23k
    GlobalDecl GD;
647
5.23k
648
5.23k
    // Get the right global decl.
649
5.23k
    switch (component.getKind()) {
650
0
    default:
651
0
      llvm_unreachable("Unexpected vtable component kind");
652
3.46k
    case VTableComponent::CK_FunctionPointer:
653
3.46k
      GD = component.getFunctionDecl();
654
3.46k
      break;
655
761
    case VTableComponent::CK_CompleteDtorPointer:
656
761
      GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
657
761
      break;
658
1.00k
    case VTableComponent::CK_DeletingDtorPointer:
659
1.00k
      GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
660
1.00k
      break;
661
5.23k
    }
662
5.23k
663
5.23k
    if (CGM.getLangOpts().CUDA) {
664
12
      // Emit NULL for methods we can't codegen on this
665
12
      // side. Otherwise we'd end up with vtable with unresolved
666
12
      // references.
667
12
      const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
668
12
      // OK on device side: functions w/ __device__ attribute
669
12
      // OK on host side: anything except __device__-only functions.
670
12
      bool CanEmitMethod =
671
12
          CGM.getLangOpts().CUDAIsDevice
672
12
              ? 
MD->hasAttr<CUDADeviceAttr>()9
673
12
              : 
(3
MD->hasAttr<CUDAHostAttr>()3
||
!MD->hasAttr<CUDADeviceAttr>()3
);
674
12
      if (!CanEmitMethod)
675
2
        return builder.addNullPointer(CGM.Int8PtrTy);
676
5.23k
      // Method is acceptable, continue processing as usual.
677
5.23k
    }
678
5.23k
679
5.23k
    auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
680
73
      // For NVPTX devices in OpenMP emit special functon as null pointers,
681
73
      // otherwise linking ends up with unresolved references.
682
73
      if (CGM.getLangOpts().OpenMP && 
CGM.getLangOpts().OpenMPIsDevice5
&&
683
73
          
CGM.getTriple().isNVPTX()3
)
684
3
        return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
685
70
      llvm::FunctionType *fnTy =
686
70
          llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
687
70
      llvm::Constant *fn = cast<llvm::Constant>(
688
70
          CGM.CreateRuntimeFunction(fnTy, name).getCallee());
689
70
      if (auto f = dyn_cast<llvm::Function>(fn))
690
70
        f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
691
70
      return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
692
70
    };
693
5.23k
694
5.23k
    llvm::Constant *fnPtr;
695
5.23k
696
5.23k
    // Pure virtual member functions.
697
5.23k
    if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
698
295
      if (!PureVirtualFn)
699
69
        PureVirtualFn =
700
69
          getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
701
295
      fnPtr = PureVirtualFn;
702
295
703
295
    // Deleted virtual member functions.
704
4.94k
    } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
705
5
      if (!DeletedVirtualFn)
706
4
        DeletedVirtualFn =
707
4
          getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
708
5
      fnPtr = DeletedVirtualFn;
709
5
710
5
    // Thunks.
711
4.93k
    } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
712
4.93k
               
layout.vtable_thunks()[nextVTableThunkIndex].first == idx1.07k
) {
713
621
      auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
714
621
715
621
      nextVTableThunkIndex++;
716
621
      fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
717
621
718
621
    // Otherwise we can use the method definition directly.
719
4.31k
    } else {
720
4.31k
      llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
721
4.31k
      fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
722
4.31k
    }
723
5.23k
724
5.23k
    fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
725
5.23k
    builder.add(fnPtr);
726
5.23k
    return;
727
5.23k
  }
728
5.23k
729
5.23k
  case VTableComponent::CK_UnusedFunctionPointer:
730
42
    return builder.addNullPointer(CGM.Int8PtrTy);
731
0
  }
732
0
733
0
  llvm_unreachable("Unexpected vtable component kind");
734
0
}
735
736
3.07k
llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
737
3.07k
  SmallVector<llvm::Type *, 4> tys;
738
6.66k
  for (unsigned i = 0, e = layout.getNumVTables(); i != e; 
++i3.59k
) {
739
3.59k
    tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
740
3.59k
  }
741
3.07k
742
3.07k
  return llvm::StructType::get(CGM.getLLVMContext(), tys);
743
3.07k
}
744
745
void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
746
                                             const VTableLayout &layout,
747
2.55k
                                             llvm::Constant *rtti) {
748
2.55k
  unsigned nextVTableThunkIndex = 0;
749
5.63k
  for (unsigned i = 0, e = layout.getNumVTables(); i != e; 
++i3.07k
) {
750
3.07k
    auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
751
3.07k
    size_t thisIndex = layout.getVTableOffset(i);
752
3.07k
    size_t nextIndex = thisIndex + layout.getVTableSize(i);
753
14.8k
    for (unsigned i = thisIndex; i != nextIndex; 
++i11.7k
) {
754
11.7k
      addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
755
11.7k
    }
756
3.07k
    vtableElem.finishAndAddTo(builder);
757
3.07k
  }
758
2.55k
}
759
760
llvm::GlobalVariable *
761
CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
762
                                      const BaseSubobject &Base,
763
                                      bool BaseIsVirtual,
764
                                   llvm::GlobalVariable::LinkageTypes Linkage,
765
300
                                      VTableAddressPointsMapTy& AddressPoints) {
766
300
  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
767
39
    DI->completeClassData(Base.getBase());
768
300
769
300
  std::unique_ptr<VTableLayout> VTLayout(
770
300
      getItaniumVTableContext().createConstructionVTableLayout(
771
300
          Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
772
300
773
300
  // Add the address points.
774
300
  AddressPoints = VTLayout->getAddressPoints();
775
300
776
300
  // Get the mangled construction vtable name.
777
300
  SmallString<256> OutName;
778
300
  llvm::raw_svector_ostream Out(OutName);
779
300
  cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
780
300
      .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
781
300
                           Base.getBase(), Out);
782
300
  StringRef Name = OutName.str();
783
300
784
300
  llvm::Type *VTType = getVTableType(*VTLayout);
785
300
786
300
  // Construction vtable symbols are not part of the Itanium ABI, so we cannot
787
300
  // guarantee that they actually will be available externally. Instead, when
788
300
  // emitting an available_externally VTT, we provide references to an internal
789
300
  // linkage construction vtable. The ABI only requires complete-object vtables
790
300
  // to be the same for all instances of a type, not construction vtables.
791
300
  if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
792
6
    Linkage = llvm::GlobalVariable::InternalLinkage;
793
300
794
300
  unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
795
300
796
300
  // Create the variable that will hold the construction vtable.
797
300
  llvm::GlobalVariable *VTable =
798
300
      CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
799
300
800
300
  // V-tables are always unnamed_addr.
801
300
  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
802
300
803
300
  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
804
300
      CGM.getContext().getTagDeclType(Base.getBase()));
805
300
806
300
  // Create and set the initializer.
807
300
  ConstantInitBuilder builder(CGM);
808
300
  auto components = builder.beginStruct();
809
300
  createVTableInitializer(components, *VTLayout, RTTI);
810
300
  components.finishAndSetAsInitializer(VTable);
811
300
812
300
  // Set properties only after the initializer has been set to ensure that the
813
300
  // GV is treated as definition and not declaration.
814
300
  assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
815
300
  CGM.setGVProperties(VTable, RD);
816
300
817
300
  CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
818
300
819
300
  return VTable;
820
300
}
821
822
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
823
1.57k
                                                const CXXRecordDecl *RD) {
824
1.57k
  return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
825
1.57k
         
CGM.getCXXABI().canSpeculativelyEmitVTable(RD)131
;
826
1.57k
}
827
828
/// Compute the required linkage of the vtable for the given class.
829
///
830
/// Note that we only call this at the end of the translation unit.
831
llvm::GlobalVariable::LinkageTypes
832
9.01k
CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
833
9.01k
  if (!RD->isExternallyVisible())
834
162
    return llvm::GlobalVariable::InternalLinkage;
835
8.84k
836
8.84k
  // We're at the end of the translation unit, so the current key
837
8.84k
  // function is fully correct.
838
8.84k
  const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
839
8.84k
  if (keyFunction && 
!RD->hasAttr<DLLImportAttr>()3.35k
) {
840
3.34k
    // If this class has a key function, use that to determine the
841
3.34k
    // linkage of the vtable.
842
3.34k
    const FunctionDecl *def = nullptr;
843
3.34k
    if (keyFunction->hasBody(def))
844
980
      keyFunction = cast<CXXMethodDecl>(def);
845
3.34k
846
3.34k
    switch (keyFunction->getTemplateSpecializationKind()) {
847
3.34k
      case TSK_Undeclared:
848
3.34k
      case TSK_ExplicitSpecialization:
849
3.34k
        assert((def || CodeGenOpts.OptimizationLevel > 0 ||
850
3.34k
                CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
851
3.34k
               "Shouldn't query vtable linkage without key function, "
852
3.34k
               "optimizations, or debug info");
853
3.34k
        if (!def && 
CodeGenOpts.OptimizationLevel > 02.36k
)
854
107
          return llvm::GlobalVariable::AvailableExternallyLinkage;
855
3.23k
856
3.23k
        if (keyFunction->isInlined())
857
73
          return !Context.getLangOpts().AppleKext ?
858
73
                   llvm::GlobalVariable::LinkOnceODRLinkage :
859
73
                   
llvm::Function::InternalLinkage0
;
860
3.16k
861
3.16k
        return llvm::GlobalVariable::ExternalLinkage;
862
3.16k
863
3.16k
      case TSK_ImplicitInstantiation:
864
0
        return !Context.getLangOpts().AppleKext ?
865
0
                 llvm::GlobalVariable::LinkOnceODRLinkage :
866
0
                 llvm::Function::InternalLinkage;
867
3.16k
868
3.16k
      case TSK_ExplicitInstantiationDefinition:
869
0
        return !Context.getLangOpts().AppleKext ?
870
0
                 llvm::GlobalVariable::WeakODRLinkage :
871
0
                 llvm::Function::InternalLinkage;
872
3.16k
873
3.16k
      case TSK_ExplicitInstantiationDeclaration:
874
0
        llvm_unreachable("Should not have been asked to emit this");
875
5.50k
    }
876
5.50k
  }
877
5.50k
878
5.50k
  // -fapple-kext mode does not support weak linkage, so we must use
879
5.50k
  // internal linkage.
880
5.50k
  if (Context.getLangOpts().AppleKext)
881
5
    return llvm::Function::InternalLinkage;
882
5.50k
883
5.50k
  llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
884
5.50k
      llvm::GlobalValue::LinkOnceODRLinkage;
885
5.50k
  llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
886
5.50k
      llvm::GlobalValue::WeakODRLinkage;
887
5.50k
  if (RD->hasAttr<DLLExportAttr>()) {
888
94
    // Cannot discard exported vtables.
889
94
    DiscardableODRLinkage = NonDiscardableODRLinkage;
890
5.40k
  } else if (RD->hasAttr<DLLImportAttr>()) {
891
48
    // Imported vtables are available externally.
892
48
    DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
893
48
    NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
894
48
  }
895
5.50k
896
5.50k
  switch (RD->getTemplateSpecializationKind()) {
897
4.38k
    case TSK_Undeclared:
898
4.38k
    case TSK_ExplicitSpecialization:
899
4.38k
    case TSK_ImplicitInstantiation:
900
4.38k
      return DiscardableODRLinkage;
901
4.38k
902
4.38k
    case TSK_ExplicitInstantiationDeclaration:
903
974
      // Explicit instantiations in MSVC do not provide vtables, so we must emit
904
974
      // our own.
905
974
      if (getTarget().getCXXABI().isMicrosoft())
906
7
        return DiscardableODRLinkage;
907
967
      return shouldEmitAvailableExternallyVTable(*this, RD)
908
967
                 ? 
llvm::GlobalVariable::AvailableExternallyLinkage9
909
967
                 : 
llvm::GlobalVariable::ExternalLinkage958
;
910
967
911
967
    case TSK_ExplicitInstantiationDefinition:
912
139
      return NonDiscardableODRLinkage;
913
0
  }
914
0
915
0
  llvm_unreachable("Invalid TemplateSpecializationKind!");
916
0
}
917
918
/// This is a callback from Sema to tell us that a particular vtable is
919
/// required to be emitted in this translation unit.
920
///
921
/// This is only called for vtables that _must_ be emitted (mainly due to key
922
/// functions).  For weak vtables, CodeGen tracks when they are needed and
923
/// emits them as-needed.
924
618
void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
925
618
  VTables.GenerateClassData(theClass);
926
618
}
927
928
void
929
2.87k
CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
930
2.87k
  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
931
536
    DI->completeClassData(RD);
932
2.87k
933
2.87k
  if (RD->getNumVBases())
934
721
    CGM.getCXXABI().emitVirtualInheritanceTables(RD);
935
2.87k
936
2.87k
  CGM.getCXXABI().emitVTableDefinitions(*this, RD);
937
2.87k
}
938
939
/// At this point in the translation unit, does it appear that can we
940
/// rely on the vtable being defined elsewhere in the program?
941
///
942
/// The response is really only definitive when called at the end of
943
/// the translation unit.
944
///
945
/// The only semantic restriction here is that the object file should
946
/// not contain a vtable definition when that vtable is defined
947
/// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
948
/// vtables when unnecessary.
949
5.05k
bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
950
5.05k
  assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
951
5.05k
952
5.05k
  // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
953
5.05k
  // emit them even if there is an explicit template instantiation.
954
5.05k
  if (CGM.getTarget().getCXXABI().isMicrosoft())
955
785
    return false;
956
4.27k
957
4.27k
  // If we have an explicit instantiation declaration (and not a
958
4.27k
  // definition), the vtable is defined elsewhere.
959
4.27k
  TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
960
4.27k
  if (TSK == TSK_ExplicitInstantiationDeclaration)
961
74
    return true;
962
4.19k
963
4.19k
  // Otherwise, if the class is an instantiated template, the
964
4.19k
  // vtable must be defined here.
965
4.19k
  if (TSK == TSK_ImplicitInstantiation ||
966
4.19k
      
TSK == TSK_ExplicitInstantiationDefinition3.77k
)
967
549
    return false;
968
3.64k
969
3.64k
  // Otherwise, if the class doesn't have a key function (possibly
970
3.64k
  // anymore), the vtable must be defined here.
971
3.64k
  const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
972
3.64k
  if (!keyFunction)
973
1.58k
    return false;
974
2.05k
975
2.05k
  // Otherwise, if we don't have a definition of the key function, the
976
2.05k
  // vtable must be defined somewhere else.
977
2.05k
  return !keyFunction->hasBody();
978
2.05k
}
979
980
/// Given that we're currently at the end of the translation unit, and
981
/// we've emitted a reference to the vtable for this class, should
982
/// we define that vtable?
983
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
984
2.76k
                                                   const CXXRecordDecl *RD) {
985
2.76k
  // If vtable is internal then it has to be done.
986
2.76k
  if (!CGM.getVTables().isVTableExternal(RD))
987
2.15k
    return true;
988
611
989
611
  // If it's external then maybe we will need it as available_externally.
990
611
  return shouldEmitAvailableExternallyVTable(CGM, RD);
991
611
}
992
993
/// Given that at some point we emitted a reference to one or more
994
/// vtables, and that we are now at the end of the translation unit,
995
/// decide whether we should emit them.
996
2.17k
void CodeGenModule::EmitDeferredVTables() {
997
2.17k
#ifndef NDEBUG
998
2.17k
  // Remember the size of DeferredVTables, because we're going to assume
999
2.17k
  // that this entire operation doesn't modify it.
1000
2.17k
  size_t savedSize = DeferredVTables.size();
1001
2.17k
#endif
1002
2.17k
1003
2.17k
  for (const CXXRecordDecl *RD : DeferredVTables)
1004
2.76k
    if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
1005
2.24k
      VTables.GenerateClassData(RD);
1006
513
    else if (shouldOpportunisticallyEmitVTables())
1007
24
      OpportunisticVTables.push_back(RD);
1008
2.17k
1009
2.17k
  assert(savedSize == DeferredVTables.size() &&
1010
2.17k
         "deferred extra vtables during vtable emission?");
1011
2.17k
  DeferredVTables.clear();
1012
2.17k
}
1013
1014
384
bool CodeGenModule::HasLTOVisibilityPublicStd(const CXXRecordDecl *RD) {
1015
384
  if (!getCodeGenOpts().LTOVisibilityPublicStd)
1016
367
    return false;
1017
17
1018
17
  const DeclContext *DC = RD;
1019
28
  while (1) {
1020
28
    auto *D = cast<Decl>(DC);
1021
28
    DC = DC->getParent();
1022
28
    if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1023
17
      if (auto *ND = dyn_cast<NamespaceDecl>(D))
1024
9
        if (const IdentifierInfo *II = ND->getIdentifier())
1025
8
          if (II->isStr("std") || 
II->isStr("stdext")4
)
1026
6
            return true;
1027
11
      break;
1028
11
    }
1029
28
  }
1030
17
1031
17
  
return false11
;
1032
17
}
1033
1034
547
bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1035
547
  LinkageInfo LV = RD->getLinkageAndVisibility();
1036
547
  if (!isExternallyVisible(LV.getLinkage()))
1037
123
    return true;
1038
424
1039
424
  if (RD->hasAttr<LTOVisibilityPublicAttr>() || 
RD->hasAttr<UuidAttr>()404
)
1040
23
    return false;
1041
401
1042
401
  if (getTriple().isOSBinFormatCOFF()) {
1043
122
    if (RD->hasAttr<DLLExportAttr>() || 
RD->hasAttr<DLLImportAttr>()120
)
1044
4
      return false;
1045
279
  } else {
1046
279
    if (LV.getVisibility() != HiddenVisibility)
1047
77
      return false;
1048
320
  }
1049
320
1050
320
  return !HasLTOVisibilityPublicStd(RD);
1051
320
}
1052
1053
llvm::GlobalObject::VCallVisibility
1054
199
CodeGenModule::GetVCallVisibilityLevel(const CXXRecordDecl *RD) {
1055
199
  LinkageInfo LV = RD->getLinkageAndVisibility();
1056
199
  llvm::GlobalObject::VCallVisibility TypeVis;
1057
199
  if (!isExternallyVisible(LV.getLinkage()))
1058
30
    TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1059
169
  else if (HasHiddenLTOVisibility(RD))
1060
123
    TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1061
46
  else
1062
46
    TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1063
199
1064
199
  for (auto B : RD->bases())
1065
82
    if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1066
82
      TypeVis = std::min(TypeVis,
1067
82
                    GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1068
199
1069
199
  for (auto B : RD->vbases())
1070
52
    if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1071
52
      TypeVis = std::min(TypeVis,
1072
52
                    GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1073
199
1074
199
  return TypeVis;
1075
199
}
1076
1077
void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1078
                                           llvm::GlobalVariable *VTable,
1079
1.63k
                                           const VTableLayout &VTLayout) {
1080
1.63k
  if (!getCodeGenOpts().LTOUnit)
1081
1.56k
    return;
1082
69
1083
69
  CharUnits PointerWidth =
1084
69
      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1085
69
1086
69
  typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1087
69
  std::vector<AddressPoint> AddressPoints;
1088
69
  for (auto &&AP : VTLayout.getAddressPoints())
1089
127
    AddressPoints.push_back(std::make_pair(
1090
127
        AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1091
127
                                AP.second.AddressPointIndex));
1092
69
1093
69
  // Sort the address points for determinism.
1094
69
  llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1095
75
                                   const AddressPoint &AP2) {
1096
75
    if (&AP1 == &AP2)
1097
0
      return false;
1098
75
1099
75
    std::string S1;
1100
75
    llvm::raw_string_ostream O1(S1);
1101
75
    getCXXABI().getMangleContext().mangleTypeName(
1102
75
        QualType(AP1.first->getTypeForDecl(), 0), O1);
1103
75
    O1.flush();
1104
75
1105
75
    std::string S2;
1106
75
    llvm::raw_string_ostream O2(S2);
1107
75
    getCXXABI().getMangleContext().mangleTypeName(
1108
75
        QualType(AP2.first->getTypeForDecl(), 0), O2);
1109
75
    O2.flush();
1110
75
1111
75
    if (S1 < S2)
1112
34
      return true;
1113
41
    if (S1 != S2)
1114
41
      return false;
1115
0
1116
0
    return AP1.second < AP2.second;
1117
0
  });
1118
69
1119
69
  ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1120
127
  for (auto AP : AddressPoints) {
1121
127
    // Create type metadata for the address point.
1122
127
    AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1123
127
1124
127
    // The class associated with each address point could also potentially be
1125
127
    // used for indirect calls via a member function pointer, so we need to
1126
127
    // annotate the address of each function pointer with the appropriate member
1127
127
    // function pointer type.
1128
923
    for (unsigned I = 0; I != Comps.size(); 
++I796
) {
1129
796
      if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1130
575
        continue;
1131
221
      llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1132
221
          Context.getMemberPointerType(
1133
221
              Comps[I].getFunctionDecl()->getType(),
1134
221
              Context.getRecordType(AP.first).getTypePtr()));
1135
221
      VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1136
221
    }
1137
127
  }
1138
69
1139
69
  if (getCodeGenOpts().VirtualFunctionElimination ||
1140
69
      
getCodeGenOpts().WholeProgramVTables62
) {
1141
44
    llvm::GlobalObject::VCallVisibility TypeVis = GetVCallVisibilityLevel(RD);
1142
44
    if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1143
23
      VTable->setVCallVisibilityMetadata(TypeVis);
1144
44
  }
1145
69
}