Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGDeclCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ 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 code generation of C++ declarations
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGObjCRuntime.h"
15
#include "CGOpenMPRuntime.h"
16
#include "CodeGenFunction.h"
17
#include "TargetInfo.h"
18
#include "clang/AST/Attr.h"
19
#include "clang/Basic/LangOptions.h"
20
#include "llvm/ADT/StringExtras.h"
21
#include "llvm/IR/Intrinsics.h"
22
#include "llvm/IR/MDBuilder.h"
23
#include "llvm/Support/Path.h"
24
25
using namespace clang;
26
using namespace CodeGen;
27
28
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
29
12.7k
                         ConstantAddress DeclPtr) {
30
12.7k
  assert(
31
12.7k
      (D.hasGlobalStorage() ||
32
12.7k
       (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
33
12.7k
      "VarDecl must have global or local (in the case of OpenCL) storage!");
34
12.7k
  assert(!D.getType()->isReferenceType() &&
35
12.7k
         "Should not call EmitDeclInit on a reference!");
36
37
12.7k
  QualType type = D.getType();
38
12.7k
  LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
39
40
12.7k
  const Expr *Init = D.getInit();
41
12.7k
  switch (CGF.getEvaluationKind(type)) {
42
7.87k
  case TEK_Scalar: {
43
7.87k
    CodeGenModule &CGM = CGF.CGM;
44
7.87k
    if (lv.isObjCStrong())
45
3
      CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
46
3
                                                DeclPtr, D.getTLSKind());
47
7.86k
    else if (lv.isObjCWeak())
48
2
      CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
49
2
                                              DeclPtr);
50
7.86k
    else
51
7.86k
      CGF.EmitScalarInit(Init, &D, lv, false);
52
7.87k
    return;
53
0
  }
54
3
  case TEK_Complex:
55
3
    CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
56
3
    return;
57
4.85k
  case TEK_Aggregate:
58
4.85k
    CGF.EmitAggExpr(Init,
59
4.85k
                    AggValueSlot::forLValue(lv, CGF, AggValueSlot::IsDestructed,
60
4.85k
                                            AggValueSlot::DoesNotNeedGCBarriers,
61
4.85k
                                            AggValueSlot::IsNotAliased,
62
4.85k
                                            AggValueSlot::DoesNotOverlap));
63
4.85k
    return;
64
0
  }
65
0
  llvm_unreachable("bad evaluation kind");
66
0
}
67
68
/// Emit code to cause the destruction of the given variable with
69
/// static storage duration.
70
static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
71
13.1k
                            ConstantAddress Addr) {
72
  // Honor __attribute__((no_destroy)) and bail instead of attempting
73
  // to emit a reference to a possibly nonexistent destructor, which
74
  // in turn can cause a crash. This will result in a global constructor
75
  // that isn't balanced out by a destructor call as intended by the
76
  // attribute. This also checks for -fno-c++-static-destructors and
77
  // bails even if the attribute is not present.
78
13.1k
  QualType::DestructionKind DtorKind = D.needsDestruction(CGF.getContext());
79
80
  // FIXME:  __attribute__((cleanup)) ?
81
82
13.1k
  switch (DtorKind) {
83
8.41k
  case QualType::DK_none:
84
8.41k
    return;
85
86
4.67k
  case QualType::DK_cxx_destructor:
87
4.67k
    break;
88
89
6
  case QualType::DK_objc_strong_lifetime:
90
6
  case QualType::DK_objc_weak_lifetime:
91
6
  case QualType::DK_nontrivial_c_struct:
92
    // We don't care about releasing objects during process teardown.
93
6
    assert(!D.getTLSKind() && "should have rejected this");
94
6
    return;
95
4.67k
  }
96
97
4.67k
  llvm::FunctionCallee Func;
98
4.67k
  llvm::Constant *Argument;
99
100
4.67k
  CodeGenModule &CGM = CGF.CGM;
101
4.67k
  QualType Type = D.getType();
102
103
  // Special-case non-array C++ destructors, if they have the right signature.
104
  // Under some ABIs, destructors return this instead of void, and cannot be
105
  // passed directly to __cxa_atexit if the target does not allow this
106
  // mismatch.
107
4.67k
  const CXXRecordDecl *Record = Type->getAsCXXRecordDecl();
108
4.67k
  bool CanRegisterDestructor =
109
4.67k
      Record && 
(4.33k
!CGM.getCXXABI().HasThisReturn(
110
4.33k
                     GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
111
8
                 CGM.getCXXABI().canCallMismatchedFunctionType());
112
  // If __cxa_atexit is disabled via a flag, a different helper function is
113
  // generated elsewhere which uses atexit instead, and it takes the destructor
114
  // directly.
115
4.67k
  bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
116
4.67k
  if (Record && 
(4.33k
CanRegisterDestructor4.33k
||
UsingExternalHelper1
)) {
117
4.33k
    assert(!Record->hasTrivialDestructor());
118
4.33k
    CXXDestructorDecl *Dtor = Record->getDestructor();
119
120
4.33k
    Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete));
121
4.33k
    if (CGF.getContext().getLangOpts().OpenCL) {
122
7
      auto DestAS =
123
7
          CGM.getTargetCodeGenInfo().getAddrSpaceOfCxaAtexitPtrParam();
124
7
      auto DestTy = CGF.getTypes().ConvertType(Type)->getPointerTo(
125
7
          CGM.getContext().getTargetAddressSpace(DestAS));
126
7
      auto SrcAS = D.getType().getQualifiers().getAddressSpace();
127
7
      if (DestAS == SrcAS)
128
0
        Argument = llvm::ConstantExpr::getBitCast(Addr.getPointer(), DestTy);
129
7
      else
130
        // FIXME: On addr space mismatch we are passing NULL. The generation
131
        // of the global destructor function should be adjusted accordingly.
132
7
        Argument = llvm::ConstantPointerNull::get(DestTy);
133
4.33k
    } else {
134
4.33k
      Argument = llvm::ConstantExpr::getBitCast(
135
4.33k
          Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo());
136
4.33k
    }
137
  // Otherwise, the standard logic requires a helper function.
138
338
  } else {
139
338
    Func = CodeGenFunction(CGM)
140
338
           .generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind),
141
338
                                  CGF.needsEHCleanup(DtorKind), &D);
142
338
    Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
143
338
  }
144
145
4.67k
  CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
146
4.67k
}
147
148
/// Emit code to cause the variable at the given address to be considered as
149
/// constant from this point onwards.
150
static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
151
91
                              llvm::Constant *Addr) {
152
91
  return CGF.EmitInvariantStart(
153
91
      Addr, CGF.getContext().getTypeSizeInChars(D.getType()));
154
91
}
155
156
140
void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) {
157
  // Do not emit the intrinsic if we're not optimizing.
158
140
  if (!CGM.getCodeGenOpts().OptimizationLevel)
159
130
    return;
160
161
  // Grab the llvm.invariant.start intrinsic.
162
10
  llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
163
  // Overloaded address space type.
164
10
  llvm::Type *ObjectPtr[1] = {Int8PtrTy};
165
10
  llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr);
166
167
  // Emit a call with the size in bytes of the object.
168
10
  uint64_t Width = Size.getQuantity();
169
10
  llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(Int64Ty, Width),
170
10
                           llvm::ConstantExpr::getBitCast(Addr, Int8PtrTy)};
171
10
  Builder.CreateCall(InvariantStart, Args);
172
10
}
173
174
void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
175
                                               llvm::Constant *DeclPtr,
176
13.2k
                                               bool PerformInit) {
177
178
13.2k
  const Expr *Init = D.getInit();
179
13.2k
  QualType T = D.getType();
180
181
  // The address space of a static local variable (DeclPtr) may be different
182
  // from the address space of the "this" argument of the constructor. In that
183
  // case, we need an addrspacecast before calling the constructor.
184
  //
185
  // struct StructWithCtor {
186
  //   __device__ StructWithCtor() {...}
187
  // };
188
  // __device__ void foo() {
189
  //   __shared__ StructWithCtor s;
190
  //   ...
191
  // }
192
  //
193
  // For example, in the above CUDA code, the static local variable s has a
194
  // "shared" address space qualifier, but the constructor of StructWithCtor
195
  // expects "this" in the "generic" address space.
196
13.2k
  unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
197
13.2k
  unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
198
13.2k
  if (ActualAddrSpace != ExpectedAddrSpace) {
199
12
    llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T);
200
12
    llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
201
12
    DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
202
12
  }
203
204
13.2k
  ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D));
205
206
13.2k
  if (!T->isReferenceType()) {
207
13.1k
    if (getLangOpts().OpenMP && 
!getLangOpts().OpenMPSimd3.87k
&&
208
1.66k
        D.hasAttr<OMPThreadPrivateDeclAttr>()) {
209
56
      (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
210
56
          &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
211
56
          PerformInit, this);
212
56
    }
213
13.1k
    if (PerformInit)
214
12.7k
      EmitDeclInit(*this, D, DeclAddr);
215
13.1k
    if (CGM.isTypeConstant(D.getType(), true))
216
91
      EmitDeclInvariant(*this, D, DeclPtr);
217
13.1k
    else
218
13.1k
      EmitDeclDestroy(*this, D, DeclAddr);
219
13.1k
    return;
220
13.1k
  }
221
222
97
  assert(PerformInit && "cannot have constant initializer which needs "
223
97
         "destruction for reference");
224
97
  RValue RV = EmitReferenceBindingToExpr(Init);
225
97
  EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
226
97
}
227
228
/// Create a stub function, suitable for being passed to atexit,
229
/// which passes the given address to the given destructor function.
230
llvm::Function *CodeGenFunction::createAtExitStub(const VarDecl &VD,
231
                                                  llvm::FunctionCallee dtor,
232
214
                                                  llvm::Constant *addr) {
233
  // Get the destructor function type, void(*)(void).
234
214
  llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
235
214
  SmallString<256> FnName;
236
214
  {
237
214
    llvm::raw_svector_ostream Out(FnName);
238
214
    CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
239
214
  }
240
241
214
  const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
242
214
  llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
243
214
      ty, FnName.str(), FI, VD.getLocation());
244
245
214
  CodeGenFunction CGF(CGM);
246
247
214
  CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit),
248
214
                    CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
249
214
                    VD.getLocation(), VD.getInit()->getExprLoc());
250
  // Emit an artificial location for this function.
251
214
  auto AL = ApplyDebugLocation::CreateArtificial(CGF);
252
253
214
  llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
254
255
  // Make sure the call and the callee agree on calling convention.
256
214
  if (auto *dtorFn = dyn_cast<llvm::Function>(
257
214
          dtor.getCallee()->stripPointerCastsAndAliases()))
258
214
    call->setCallingConv(dtorFn->getCallingConv());
259
260
214
  CGF.FinishFunction();
261
262
214
  return fn;
263
214
}
264
265
/// Register a global destructor using the C atexit runtime function.
266
void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
267
                                                   llvm::FunctionCallee dtor,
268
178
                                                   llvm::Constant *addr) {
269
  // Create a function which calls the destructor.
270
178
  llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
271
178
  registerGlobalDtorWithAtExit(dtorStub);
272
178
}
273
274
221
void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
275
  // extern "C" int atexit(void (*f)(void));
276
221
  assert(dtorStub->getType() ==
277
221
             llvm::PointerType::get(
278
221
                 llvm::FunctionType::get(CGM.VoidTy, false),
279
221
                 dtorStub->getType()->getPointerAddressSpace()) &&
280
221
         "Argument to atexit has a wrong type.");
281
282
221
  llvm::FunctionType *atexitTy =
283
221
      llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
284
285
221
  llvm::FunctionCallee atexit =
286
221
      CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
287
221
                                /*Local=*/true);
288
221
  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
289
221
    atexitFn->setDoesNotThrow();
290
291
221
  EmitNounwindRuntimeCall(atexit, dtorStub);
292
221
}
293
294
llvm::Value *
295
38
CodeGenFunction::unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub) {
296
  // The unatexit subroutine unregisters __dtor functions that were previously
297
  // registered by the atexit subroutine. If the referenced function is found,
298
  // it is removed from the list of functions that are called at normal program
299
  // termination and the unatexit returns a value of 0, otherwise a non-zero
300
  // value is returned.
301
  //
302
  // extern "C" int unatexit(void (*f)(void));
303
38
  assert(dtorStub->getType() ==
304
38
             llvm::PointerType::get(
305
38
                 llvm::FunctionType::get(CGM.VoidTy, false),
306
38
                 dtorStub->getType()->getPointerAddressSpace()) &&
307
38
         "Argument to unatexit has a wrong type.");
308
309
38
  llvm::FunctionType *unatexitTy =
310
38
      llvm::FunctionType::get(IntTy, {dtorStub->getType()}, /*isVarArg=*/false);
311
312
38
  llvm::FunctionCallee unatexit =
313
38
      CGM.CreateRuntimeFunction(unatexitTy, "unatexit", llvm::AttributeList());
314
315
38
  cast<llvm::Function>(unatexit.getCallee())->setDoesNotThrow();
316
317
38
  return EmitNounwindRuntimeCall(unatexit, dtorStub);
318
38
}
319
320
void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
321
                                         llvm::GlobalVariable *DeclPtr,
322
7.82k
                                         bool PerformInit) {
323
  // If we've been asked to forbid guard variables, emit an error now.
324
  // This diagnostic is hard-coded for Darwin's use case;  we can find
325
  // better phrasing if someone else needs it.
326
7.82k
  if (CGM.getCodeGenOpts().ForbidGuardVariables)
327
1
    CGM.Error(D.getLocation(),
328
1
              "this initialization requires a guard variable, which "
329
1
              "the kernel does not support");
330
331
7.82k
  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
332
7.82k
}
333
334
void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
335
                                               llvm::BasicBlock *InitBlock,
336
                                               llvm::BasicBlock *NoInitBlock,
337
                                               GuardKind Kind,
338
7.82k
                                               const VarDecl *D) {
339
7.82k
  assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
340
341
  // A guess at how many times we will enter the initialization of a
342
  // variable, depending on the kind of variable.
343
7.82k
  static const uint64_t InitsPerTLSVar = 1024;
344
7.82k
  static const uint64_t InitsPerLocalVar = 1024 * 1024;
345
346
7.82k
  llvm::MDNode *Weights;
347
7.82k
  if (Kind == GuardKind::VariableGuard && 
!D->isLocalVarDecl()7.77k
) {
348
    // For non-local variables, don't apply any weighting for now. Due to our
349
    // use of COMDATs, we expect there to be at most one initialization of the
350
    // variable per DSO, but we have no way to know how many DSOs will try to
351
    // initialize the variable.
352
173
    Weights = nullptr;
353
7.65k
  } else {
354
7.65k
    uint64_t NumInits;
355
    // FIXME: For the TLS case, collect and use profiling information to
356
    // determine a more accurate brach weight.
357
7.65k
    if (Kind == GuardKind::TlsGuard || 
D->getTLSKind()7.60k
)
358
116
      NumInits = InitsPerTLSVar;
359
7.53k
    else
360
7.53k
      NumInits = InitsPerLocalVar;
361
362
    // The probability of us entering the initializer is
363
    //   1 / (total number of times we attempt to initialize the variable).
364
7.65k
    llvm::MDBuilder MDHelper(CGM.getLLVMContext());
365
7.65k
    Weights = MDHelper.createBranchWeights(1, NumInits - 1);
366
7.65k
  }
367
368
7.82k
  Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
369
7.82k
}
370
371
llvm::Function *CodeGenModule::CreateGlobalInitOrCleanUpFunction(
372
    llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
373
10.4k
    SourceLocation Loc, bool TLS) {
374
10.4k
  llvm::Function *Fn = llvm::Function::Create(
375
10.4k
      FTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
376
377
10.4k
  if (!getLangOpts().AppleKext && 
!TLS10.3k
) {
378
    // Set the section if needed.
379
10.3k
    if (const char *Section = getTarget().getStaticInitSectionSpecifier())
380
2.41k
      Fn->setSection(Section);
381
10.3k
  }
382
383
10.4k
  SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
384
385
10.4k
  Fn->setCallingConv(getRuntimeCC());
386
387
10.4k
  if (!getLangOpts().Exceptions)
388
9.35k
    Fn->setDoesNotThrow();
389
390
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
391
91
      !isInSanitizerBlacklist(SanitizerKind::Address, Fn, Loc))
392
86
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
393
394
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
395
4
      !isInSanitizerBlacklist(SanitizerKind::KernelAddress, Fn, Loc))
396
2
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
397
398
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
399
0
      !isInSanitizerBlacklist(SanitizerKind::HWAddress, Fn, Loc))
400
0
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
401
402
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
403
0
      !isInSanitizerBlacklist(SanitizerKind::KernelHWAddress, Fn, Loc))
404
0
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
405
406
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::MemTag) &&
407
0
      !isInSanitizerBlacklist(SanitizerKind::MemTag, Fn, Loc))
408
0
    Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
409
410
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
411
6
      !isInSanitizerBlacklist(SanitizerKind::Thread, Fn, Loc))
412
3
    Fn->addFnAttr(llvm::Attribute::SanitizeThread);
413
414
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
415
41
      !isInSanitizerBlacklist(SanitizerKind::Memory, Fn, Loc))
416
41
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
417
418
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
419
0
      !isInSanitizerBlacklist(SanitizerKind::KernelMemory, Fn, Loc))
420
0
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
421
422
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
423
0
      !isInSanitizerBlacklist(SanitizerKind::SafeStack, Fn, Loc))
424
0
    Fn->addFnAttr(llvm::Attribute::SafeStack);
425
426
10.4k
  if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
427
0
      !isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc))
428
0
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
429
430
10.4k
  return Fn;
431
10.4k
}
432
433
/// Create a global pointer to a function that will initialize a global
434
/// variable.  The user has requested that this pointer be emitted in a specific
435
/// section.
436
void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
437
                                          llvm::GlobalVariable *GV,
438
                                          llvm::Function *InitFunc,
439
6
                                          InitSegAttr *ISA) {
440
6
  llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
441
6
      TheModule, InitFunc->getType(), /*isConstant=*/true,
442
6
      llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
443
6
  PtrArray->setSection(ISA->getSection());
444
6
  addUsedGlobal(PtrArray);
445
446
  // If the GV is already in a comdat group, then we have to join it.
447
6
  if (llvm::Comdat *C = GV->getComdat())
448
3
    PtrArray->setComdat(C);
449
6
}
450
451
void
452
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
453
                                            llvm::GlobalVariable *Addr,
454
5.80k
                                            bool PerformInit) {
455
456
  // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
457
  // __constant__ and __shared__ variables defined in namespace scope,
458
  // that are of class type, cannot have a non-empty constructor. All
459
  // the checks have been done in Sema by now. Whatever initializers
460
  // are allowed are empty and we just need to ignore them here.
461
5.80k
  if (getLangOpts().CUDAIsDevice && 
!getLangOpts().GPUAllowDeviceInit25
&&
462
24
      (D->hasAttr<CUDADeviceAttr>() || 
D->hasAttr<CUDAConstantAttr>()14
||
463
4
       D->hasAttr<CUDASharedAttr>()))
464
24
    return;
465
466
5.78k
  if (getLangOpts().OpenMP &&
467
3.89k
      getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit))
468
77
    return;
469
470
  // Check if we've already initialized this decl.
471
5.70k
  auto I = DelayedCXXInitPosition.find(D);
472
5.70k
  if (I != DelayedCXXInitPosition.end() && 
I->second == ~0U1.47k
)
473
22
    return;
474
475
5.68k
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
476
5.68k
  SmallString<256> FnName;
477
5.68k
  {
478
5.68k
    llvm::raw_svector_ostream Out(FnName);
479
5.68k
    getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
480
5.68k
  }
481
482
  // Create a variable initialization function.
483
5.68k
  llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
484
5.68k
      FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation());
485
486
5.68k
  auto *ISA = D->getAttr<InitSegAttr>();
487
5.68k
  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
488
5.68k
                                                          PerformInit);
489
490
5.68k
  llvm::GlobalVariable *COMDATKey =
491
5.68k
      supportsCOMDAT() && 
D->isExternallyVisible()4.56k
?
Addr3.84k
:
nullptr1.84k
;
492
493
5.68k
  if (D->getTLSKind()) {
494
    // FIXME: Should we support init_priority for thread_local?
495
    // FIXME: We only need to register one __cxa_thread_atexit function for the
496
    // entire TU.
497
177
    CXXThreadLocalInits.push_back(Fn);
498
177
    CXXThreadLocalInitVars.push_back(D);
499
5.50k
  } else if (PerformInit && 
ISA5.13k
) {
500
6
    EmitPointerToInitFunc(D, Addr, Fn, ISA);
501
5.50k
  } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
502
921
    OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
503
921
    PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
504
4.58k
  } else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) ||
505
4.47k
             getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR) {
506
    // C++ [basic.start.init]p2:
507
    //   Definitions of explicitly specialized class template static data
508
    //   members have ordered initialization. Other class template static data
509
    //   members (i.e., implicitly or explicitly instantiated specializations)
510
    //   have unordered initialization.
511
    //
512
    // As a consequence, we can put them into their own llvm.global_ctors entry.
513
    //
514
    // If the global is externally visible, put the initializer into a COMDAT
515
    // group with the global being initialized.  On most platforms, this is a
516
    // minor startup time optimization.  In the MS C++ ABI, there are no guard
517
    // variables, so this COMDAT key is required for correctness.
518
130
    AddGlobalCtor(Fn, 65535, COMDATKey);
519
130
    if (getTarget().getCXXABI().isMicrosoft() && 
COMDATKey35
) {
520
      // In The MS C++, MS add template static data member in the linker
521
      // drective.
522
31
      addUsedGlobal(COMDATKey);
523
31
    }
524
4.45k
  } else if (D->hasAttr<SelectAnyAttr>()) {
525
    // SelectAny globals will be comdat-folded. Put the initializer into a
526
    // COMDAT group associated with the global, so the initializers get folded
527
    // too.
528
6
    AddGlobalCtor(Fn, 65535, COMDATKey);
529
4.44k
  } else {
530
4.44k
    I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
531
4.44k
    if (I == DelayedCXXInitPosition.end()) {
532
3.36k
      CXXGlobalInits.push_back(Fn);
533
1.08k
    } else if (I->second != ~0U) {
534
1.08k
      assert(I->second < CXXGlobalInits.size() &&
535
1.08k
             CXXGlobalInits[I->second] == nullptr);
536
1.08k
      CXXGlobalInits[I->second] = Fn;
537
1.08k
    }
538
4.44k
  }
539
540
  // Remember that we already emitted the initializer for this global.
541
5.68k
  DelayedCXXInitPosition[D] = ~0U;
542
5.68k
}
543
544
29.6k
void CodeGenModule::EmitCXXThreadLocalInitFunc() {
545
29.6k
  getCXXABI().EmitThreadLocalInitFuncs(
546
29.6k
      *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
547
548
29.6k
  CXXThreadLocalInits.clear();
549
29.6k
  CXXThreadLocalInitVars.clear();
550
29.6k
  CXXThreadLocals.clear();
551
29.6k
}
552
553
1.33k
static SmallString<128> getTransformedFileName(llvm::Module &M) {
554
1.33k
  SmallString<128> FileName = llvm::sys::path::filename(M.getName());
555
556
1.33k
  if (FileName.empty())
557
0
    FileName = "<null>";
558
559
45.1k
  for (size_t i = 0; i < FileName.size(); 
++i43.8k
) {
560
    // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
561
    // to be the set of C preprocessing numbers.
562
43.8k
    if (!isPreprocessingNumberBody(FileName[i]))
563
873
      FileName[i] = '_';
564
43.8k
  }
565
566
1.33k
  return FileName;
567
1.33k
}
568
569
void
570
29.6k
CodeGenModule::EmitCXXGlobalInitFunc() {
571
42.9k
  while (!CXXGlobalInits.empty() && 
!CXXGlobalInits.back()14.5k
)
572
13.2k
    CXXGlobalInits.pop_back();
573
574
29.6k
  if (CXXGlobalInits.empty() && 
PrioritizedCXXGlobalInits.empty()28.3k
)
575
28.3k
    return;
576
577
1.33k
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
578
1.33k
  const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
579
580
1.33k
  const bool UseSinitAndSterm = getCXXABI().useSinitAndSterm();
581
  // Create our global prioritized initialization function.
582
1.33k
  if (!PrioritizedCXXGlobalInits.empty()) {
583
307
    assert(!UseSinitAndSterm && "Prioritized sinit and sterm functions are not"
584
307
                                " supported yet.");
585
586
307
    SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
587
307
    llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
588
307
                         PrioritizedCXXGlobalInits.end());
589
    // Iterate over "chunks" of ctors with same priority and emit each chunk
590
    // into separate function. Note - everything is sorted first by priority,
591
    // second - by lex order, so we emit ctor functions in proper order.
592
307
    for (SmallVectorImpl<GlobalInitData >::iterator
593
307
           I = PrioritizedCXXGlobalInits.begin(),
594
921
           E = PrioritizedCXXGlobalInits.end(); I != E; ) {
595
614
      SmallVectorImpl<GlobalInitData >::iterator
596
614
        PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
597
598
614
      LocalCXXGlobalInits.clear();
599
614
      unsigned Priority = I->first.priority;
600
      // Compute the function suffix from priority. Prepend with zeroes to make
601
      // sure the function names are also ordered as priorities.
602
614
      std::string PrioritySuffix = llvm::utostr(Priority);
603
      // Priority is always <= 65535 (enforced by sema).
604
614
      PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
605
614
      llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
606
614
          FTy, "_GLOBAL__I_" + PrioritySuffix, FI);
607
608
1.53k
      for (; I < PrioE; 
++I921
)
609
921
        LocalCXXGlobalInits.push_back(I->second);
610
611
614
      CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
612
614
      AddGlobalCtor(Fn, Priority);
613
614
    }
614
307
    PrioritizedCXXGlobalInits.clear();
615
307
  }
616
617
1.33k
  if (UseSinitAndSterm && 
CXXGlobalInits.empty()12
)
618
0
    return;
619
620
  // Include the filename in the symbol name. Including "sub_" matches gcc
621
  // and makes sure these symbols appear lexicographically behind the symbols
622
  // with priority emitted above.
623
1.33k
  llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
624
1.33k
      FTy, llvm::Twine("_GLOBAL__sub_I_", getTransformedFileName(getModule())),
625
1.33k
      FI);
626
627
1.33k
  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
628
1.33k
  AddGlobalCtor(Fn);
629
630
  // In OpenCL global init functions must be converted to kernels in order to
631
  // be able to launch them from the host.
632
  // FIXME: Some more work might be needed to handle destructors correctly.
633
  // Current initialization function makes use of function pointers callbacks.
634
  // We can't support function pointers especially between host and device.
635
  // However it seems global destruction has little meaning without any
636
  // dynamic resource allocation on the device and program scope variables are
637
  // destroyed by the runtime when program is released.
638
1.33k
  if (getLangOpts().OpenCL) {
639
6
    GenOpenCLArgMetadata(Fn);
640
6
    Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
641
6
  }
642
643
1.33k
  if (getLangOpts().HIP) {
644
1
    Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
645
1
    Fn->addFnAttr("device-init");
646
1
  }
647
648
1.33k
  CXXGlobalInits.clear();
649
1.33k
}
650
651
29.6k
void CodeGenModule::EmitCXXGlobalCleanUpFunc() {
652
29.6k
  if (CXXGlobalDtorsOrStermFinalizers.empty())
653
29.6k
    return;
654
655
15
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
656
15
  const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
657
658
  // Create our global cleanup function.
659
15
  llvm::Function *Fn =
660
15
      CreateGlobalInitOrCleanUpFunction(FTy, "_GLOBAL__D_a", FI);
661
662
15
  CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
663
15
      Fn, CXXGlobalDtorsOrStermFinalizers);
664
15
  AddGlobalDtor(Fn);
665
15
  CXXGlobalDtorsOrStermFinalizers.clear();
666
15
}
667
668
/// Emit the code necessary to initialize the given global variable.
669
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
670
                                                       const VarDecl *D,
671
                                                 llvm::GlobalVariable *Addr,
672
5.68k
                                                       bool PerformInit) {
673
  // Check if we need to emit debug info for variable initializer.
674
5.68k
  if (D->hasAttr<NoDebugAttr>())
675
1
    DebugInfo = nullptr; // disable debug info indefinitely for this function
676
677
5.68k
  CurEHLocation = D->getBeginLoc();
678
679
5.68k
  StartFunction(GlobalDecl(D, DynamicInitKind::Initializer),
680
5.68k
                getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
681
5.68k
                FunctionArgList());
682
  // Emit an artificial location for this function.
683
5.68k
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
684
685
  // Use guarded initialization if the global variable is weak. This
686
  // occurs for, e.g., instantiated static data members and
687
  // definitions explicitly marked weak.
688
  //
689
  // Also use guarded initialization for a variable with dynamic TLS and
690
  // unordered initialization. (If the initialization is ordered, the ABI
691
  // layer will guard the whole-TU initialization for us.)
692
5.68k
  if (Addr->hasWeakLinkage() || 
Addr->hasLinkOnceLinkage()5.61k
||
693
5.46k
      (D->getTLSKind() == VarDecl::TLS_Dynamic &&
694
219
       
isTemplateInstantiation(D->getTemplateSpecializationKind())97
)) {
695
219
    EmitCXXGuardedInit(*D, Addr, PerformInit);
696
5.46k
  } else {
697
5.46k
    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
698
5.46k
  }
699
700
5.68k
  FinishFunction();
701
5.68k
}
702
703
void
704
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
705
                                           ArrayRef<llvm::Function *> Decls,
706
2.00k
                                           ConstantAddress Guard) {
707
2.00k
  {
708
2.00k
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
709
2.00k
    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
710
2.00k
                  getTypes().arrangeNullaryFunction(), FunctionArgList());
711
    // Emit an artificial location for this function.
712
2.00k
    auto AL = ApplyDebugLocation::CreateArtificial(*this);
713
714
2.00k
    llvm::BasicBlock *ExitBlock = nullptr;
715
2.00k
    if (Guard.isValid()) {
716
      // If we have a guard variable, check whether we've already performed
717
      // these initializations. This happens for TLS initialization functions.
718
49
      llvm::Value *GuardVal = Builder.CreateLoad(Guard);
719
49
      llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
720
49
                                                 "guard.uninitialized");
721
49
      llvm::BasicBlock *InitBlock = createBasicBlock("init");
722
49
      ExitBlock = createBasicBlock("exit");
723
49
      EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
724
49
                               GuardKind::TlsGuard, nullptr);
725
49
      EmitBlock(InitBlock);
726
      // Mark as initialized before initializing anything else. If the
727
      // initializers use previously-initialized thread_local vars, that's
728
      // probably supposed to be OK, but the standard doesn't say.
729
49
      Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
730
731
      // The guard variable can't ever change again.
732
49
      EmitInvariantStart(
733
49
          Guard.getPointer(),
734
49
          CharUnits::fromQuantity(
735
49
              CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
736
49
    }
737
738
2.00k
    RunCleanupsScope Scope(*this);
739
740
    // When building in Objective-C++ ARC mode, create an autorelease pool
741
    // around the global initializers.
742
2.00k
    if (getLangOpts().ObjCAutoRefCount && 
getLangOpts().CPlusPlus4
) {
743
4
      llvm::Value *token = EmitObjCAutoreleasePoolPush();
744
4
      EmitObjCAutoreleasePoolCleanup(token);
745
4
    }
746
747
11.0k
    for (unsigned i = 0, e = Decls.size(); i != e; 
++i9.00k
)
748
9.00k
      if (Decls[i])
749
5.46k
        EmitRuntimeCall(Decls[i]);
750
751
2.00k
    Scope.ForceCleanup();
752
753
2.00k
    if (ExitBlock) {
754
49
      Builder.CreateBr(ExitBlock);
755
49
      EmitBlock(ExitBlock);
756
49
    }
757
2.00k
  }
758
759
2.00k
  FinishFunction();
760
2.00k
}
761
762
void CodeGenFunction::GenerateCXXGlobalCleanUpFunc(
763
    llvm::Function *Fn,
764
    const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
765
15
                                 llvm::Constant *>> &DtorsOrStermFinalizers) {
766
15
  {
767
15
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
768
15
    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
769
15
                  getTypes().arrangeNullaryFunction(), FunctionArgList());
770
    // Emit an artificial location for this function.
771
15
    auto AL = ApplyDebugLocation::CreateArtificial(*this);
772
773
    // Emit the cleanups, in reverse order from construction.
774
41
    for (unsigned i = 0, e = DtorsOrStermFinalizers.size(); i != e; 
++i26
) {
775
26
      llvm::FunctionType *CalleeTy;
776
26
      llvm::Value *Callee;
777
26
      llvm::Constant *Arg;
778
26
      std::tie(CalleeTy, Callee, Arg) = DtorsOrStermFinalizers[e - i - 1];
779
780
26
      llvm::CallInst *CI = nullptr;
781
26
      if (Arg == nullptr) {
782
20
        assert(
783
20
            CGM.getCXXABI().useSinitAndSterm() &&
784
20
            "Arg could not be nullptr unless using sinit and sterm functions.");
785
20
        CI = Builder.CreateCall(CalleeTy, Callee);
786
20
      } else
787
6
        CI = Builder.CreateCall(CalleeTy, Callee, Arg);
788
789
      // Make sure the call and the callee agree on calling convention.
790
26
      if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
791
26
        CI->setCallingConv(F->getCallingConv());
792
26
    }
793
15
  }
794
795
15
  FinishFunction();
796
15
}
797
798
/// generateDestroyHelper - Generates a helper function which, when
799
/// invoked, destroys the given object.  The address of the object
800
/// should be in global memory.
801
llvm::Function *CodeGenFunction::generateDestroyHelper(
802
    Address addr, QualType type, Destroyer *destroyer,
803
342
    bool useEHCleanupForArray, const VarDecl *VD) {
804
342
  FunctionArgList args;
805
342
  ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy,
806
342
                        ImplicitParamDecl::Other);
807
342
  args.push_back(&Dst);
808
809
342
  const CGFunctionInfo &FI =
810
342
    CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
811
342
  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
812
342
  llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
813
342
      FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
814
815
342
  CurEHLocation = VD->getBeginLoc();
816
817
342
  StartFunction(GlobalDecl(VD, DynamicInitKind::GlobalArrayDestructor),
818
342
                getContext().VoidTy, fn, FI, args);
819
  // Emit an artificial location for this function.
820
342
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
821
822
342
  emitDestroy(addr, type, destroyer, useEHCleanupForArray);
823
824
342
  FinishFunction();
825
826
342
  return fn;
827
342
}