Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/CodeGen/CGCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
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.
10
//
11
//===----------------------------------------------------------------------===//
12
13
// We might split this into multiple files if it gets too unwieldy
14
15
#include "CodeGenModule.h"
16
#include "CGCXXABI.h"
17
#include "CodeGenFunction.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/Mangle.h"
23
#include "clang/AST/RecordLayout.h"
24
#include "clang/AST/StmtCXX.h"
25
#include "clang/Basic/CodeGenOptions.h"
26
#include "llvm/ADT/StringExtras.h"
27
using namespace clang;
28
using namespace CodeGen;
29
30
31
/// Try to emit a base destructor as an alias to its primary
32
/// base-class destructor.
33
11.1k
bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
34
11.1k
  if (!getCodeGenOpts().CXXCtorDtorAliases)
35
11.0k
    return true;
36
156
37
156
  // Producing an alias to a base class ctor/dtor can degrade debug quality
38
156
  // as the debugger cannot tell them apart.
39
156
  if (getCodeGenOpts().OptimizationLevel == 0)
40
64
    return true;
41
92
42
92
  // If sanitizing memory to check for use-after-dtor, do not emit as
43
92
  //  an alias, unless this class owns no members.
44
92
  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
45
92
      
!D->getParent()->field_empty()0
)
46
0
    return true;
47
92
48
92
  // If the destructor doesn't have a trivial body, we have to emit it
49
92
  // separately.
50
92
  if (!D->hasTrivialBody())
51
2
    return true;
52
90
53
90
  const CXXRecordDecl *Class = D->getParent();
54
90
55
90
  // We are going to instrument this destructor, so give up even if it is
56
90
  // currently empty.
57
90
  if (Class->mayInsertExtraPadding())
58
6
    return true;
59
84
60
84
  // If we need to manipulate a VTT parameter, give up.
61
84
  if (Class->getNumVBases()) {
62
4
    // Extra Credit:  passing extra parameters is perfectly safe
63
4
    // in many calling conventions, so only bail out if the ctor's
64
4
    // calling convention is nonstandard.
65
4
    return true;
66
4
  }
67
80
68
80
  // If any field has a non-trivial destructor, we have to emit the
69
80
  // destructor separately.
70
80
  for (const auto *I : Class->fields())
71
14
    if (I->getType().isDestructedType())
72
5
      return true;
73
80
74
80
  // Try to find a unique base class with a non-trivial destructor.
75
80
  const CXXRecordDecl *UniqueBase = nullptr;
76
75
  for (const auto &I : Class->bases()) {
77
37
78
37
    // We're in the base destructor, so skip virtual bases.
79
37
    if (I.isVirtual()) 
continue0
;
80
37
81
37
    // Skip base classes with trivial destructors.
82
37
    const auto *Base =
83
37
        cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
84
37
    if (Base->hasTrivialDestructor()) 
continue1
;
85
36
86
36
    // If we've already found a base class with a non-trivial
87
36
    // destructor, give up.
88
36
    if (UniqueBase) 
return true0
;
89
36
    UniqueBase = Base;
90
36
  }
91
75
92
75
  // If we didn't find any bases with a non-trivial destructor, then
93
75
  // the base destructor is actually effectively trivial, which can
94
75
  // happen if it was needlessly user-defined or if there are virtual
95
75
  // bases with non-trivial destructors.
96
75
  if (!UniqueBase)
97
39
    return true;
98
36
99
36
  // If the base is at a non-zero offset, give up.
100
36
  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
101
36
  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
102
0
    return true;
103
36
104
36
  // Give up if the calling conventions don't match. We could update the call,
105
36
  // but it is probably not worth it.
106
36
  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
107
36
  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
108
36
      D->getType()->getAs<FunctionType>()->getCallConv())
109
2
    return true;
110
34
111
34
  GlobalDecl AliasDecl(D, Dtor_Base);
112
34
  GlobalDecl TargetDecl(BaseD, Dtor_Base);
113
34
114
34
  // The alias will use the linkage of the referent.  If we can't
115
34
  // support aliases with that linkage, fail.
116
34
  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
117
34
118
34
  // We can't use an alias if the linkage is not valid for one.
119
34
  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
120
2
    return true;
121
32
122
32
  llvm::GlobalValue::LinkageTypes TargetLinkage =
123
32
      getFunctionLinkage(TargetDecl);
124
32
125
32
  // Check if we have it already.
126
32
  StringRef MangledName = getMangledName(AliasDecl);
127
32
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
128
32
  if (Entry && 
!Entry->isDeclaration()16
)
129
0
    return false;
130
32
  if (Replacements.count(MangledName))
131
0
    return false;
132
32
133
32
  // Derive the type for the alias.
134
32
  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
135
32
  llvm::PointerType *AliasType = AliasValueType->getPointerTo();
136
32
137
32
  // Find the referent.  Some aliases might require a bitcast, in
138
32
  // which case the caller is responsible for ensuring the soundness
139
32
  // of these semantics.
140
32
  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
141
32
  llvm::Constant *Aliasee = Ref;
142
32
  if (Ref->getType() != AliasType)
143
32
    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
144
32
145
32
  // Instead of creating as alias to a linkonce_odr, replace all of the uses
146
32
  // of the aliasee.
147
32
  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
148
32
      
!(16
TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage16
&&
149
16
        
TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>()2
)) {
150
14
    // FIXME: An extern template instantiation will create functions with
151
14
    // linkage "AvailableExternally". In libc++, some classes also define
152
14
    // members with attribute "AlwaysInline" and expect no reference to
153
14
    // be generated. It is desirable to reenable this optimisation after
154
14
    // corresponding LLVM changes.
155
14
    addReplacement(MangledName, Aliasee);
156
14
    return false;
157
14
  }
158
18
159
18
  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
160
18
  // template instantiation or a dllexported class, avoid forming it on COFF.
161
18
  // A COFF weak external alias cannot satisfy a normal undefined symbol
162
18
  // reference from another TU. The other TU must also mark the referenced
163
18
  // symbol as weak, which we cannot rely on.
164
18
  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
165
18
      
getTriple().isOSBinFormatCOFF()8
) {
166
7
    return true;
167
7
  }
168
11
169
11
  // If we don't have a definition for the destructor yet or the definition is
170
11
  // avaialable_externally, don't emit an alias.  We can't emit aliases to
171
11
  // declarations; that's just not how aliases work.
172
11
  if (Ref->isDeclarationForLinker())
173
1
    return true;
174
10
175
10
  // Don't create an alias to a linker weak symbol. This avoids producing
176
10
  // different COMDATs in different TUs. Another option would be to
177
10
  // output the alias both for weak_odr and linkonce_odr, but that
178
10
  // requires explicit comdat support in the IL.
179
10
  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
180
2
    return true;
181
8
182
8
  // Create the alias with no name.
183
8
  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
184
8
                                          Aliasee, &getModule());
185
8
186
8
  // Destructors are always unnamed_addr.
187
8
  Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
188
8
189
8
  // Switch any previous uses to the alias.
190
8
  if (Entry) {
191
0
    assert(Entry->getType() == AliasType &&
192
0
           "declaration exists with different type");
193
0
    Alias->takeName(Entry);
194
0
    Entry->replaceAllUsesWith(Alias);
195
0
    Entry->eraseFromParent();
196
8
  } else {
197
8
    Alias->setName(MangledName);
198
8
  }
199
8
200
8
  // Finally, set up the alias with its proper name and attributes.
201
8
  SetCommonAttributes(AliasDecl, Alias);
202
8
203
8
  return false;
204
8
}
205
206
75.3k
llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
207
75.3k
  const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
208
75.3k
  auto *Fn = cast<llvm::Function>(
209
75.3k
      getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
210
75.3k
                           /*DontDefer=*/true, ForDefinition));
211
75.3k
212
75.3k
  setFunctionLinkage(GD, Fn);
213
75.3k
214
75.3k
  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
215
75.3k
  setNonAliasAttributes(GD, Fn);
216
75.3k
  SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
217
75.3k
  return Fn;
218
75.3k
}
219
220
llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
221
    GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
222
298k
    bool DontDefer, ForDefinition_t IsForDefinition) {
223
298k
  auto *MD = cast<CXXMethodDecl>(GD.getDecl());
224
298k
225
298k
  if (isa<CXXDestructorDecl>(MD)) {
226
103k
    // Always alias equivalent complete destructors to base destructors in the
227
103k
    // MS ABI.
228
103k
    if (getTarget().getCXXABI().isMicrosoft() &&
229
103k
        
GD.getDtorType() == Dtor_Complete2.18k
&&
230
103k
        
MD->getParent()->getNumVBases() == 0480
)
231
105
      GD = GD.getWithDtorType(Dtor_Base);
232
103k
  }
233
298k
234
298k
  if (!FnType) {
235
297k
    if (!FnInfo)
236
222k
      FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
237
297k
    FnType = getTypes().GetFunctionType(*FnInfo);
238
297k
  }
239
298k
240
298k
  llvm::Constant *Ptr = GetOrCreateLLVMFunction(
241
298k
      getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
242
298k
      /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
243
298k
  return {FnType, Ptr};
244
298k
}
245
246
static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
247
                                          GlobalDecl GD,
248
                                          llvm::Type *Ty,
249
14
                                          const CXXRecordDecl *RD) {
250
14
  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
251
14
         "No kext in Microsoft ABI");
252
14
  CodeGenModule &CGM = CGF.CGM;
253
14
  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
254
14
  Ty = Ty->getPointerTo()->getPointerTo();
255
14
  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
256
14
  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
257
14
  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
258
14
  const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
259
14
  VTableLayout::AddressPointLocation AddressPoint =
260
14
      VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
261
14
  VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
262
14
                 AddressPoint.AddressPointIndex;
263
14
  llvm::Value *VFuncPtr =
264
14
    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
265
14
  llvm::Value *VFunc =
266
14
    CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
267
14
  CGCallee Callee(GD, VFunc);
268
14
  return Callee;
269
14
}
270
271
/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
272
/// indirect call to virtual functions. It makes the call through indexing
273
/// into the vtable.
274
CGCallee
275
CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
276
                                           NestedNameSpecifier *Qual,
277
8
                                           llvm::Type *Ty) {
278
8
  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
279
8
         "BuildAppleKextVirtualCall - bad Qual kind");
280
8
281
8
  const Type *QTy = Qual->getAsType();
282
8
  QualType T = QualType(QTy, 0);
283
8
  const RecordType *RT = T->getAs<RecordType>();
284
8
  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
285
8
  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
286
8
287
8
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
288
2
    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
289
6
290
6
  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
291
6
}
292
293
/// BuildVirtualCall - This routine makes indirect vtable call for
294
/// call to virtual destructors. It returns 0 if it could not do it.
295
CGCallee
296
CodeGenFunction::BuildAppleKextVirtualDestructorCall(
297
                                            const CXXDestructorDecl *DD,
298
                                            CXXDtorType Type,
299
8
                                            const CXXRecordDecl *RD) {
300
8
  assert(DD->isVirtual() && Type != Dtor_Base);
301
8
  // Compute the function type we're calling.
302
8
  const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
303
8
      GlobalDecl(DD, Dtor_Complete));
304
8
  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
305
8
  return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
306
8
}