Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/CodeGen/CGDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDecl.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 to emit Decl nodes as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGBlocks.h"
14
#include "CGCXXABI.h"
15
#include "CGCleanup.h"
16
#include "CGDebugInfo.h"
17
#include "CGOpenCLRuntime.h"
18
#include "CGOpenMPRuntime.h"
19
#include "CodeGenFunction.h"
20
#include "CodeGenModule.h"
21
#include "ConstantEmitter.h"
22
#include "PatternInit.h"
23
#include "TargetInfo.h"
24
#include "clang/AST/ASTContext.h"
25
#include "clang/AST/Attr.h"
26
#include "clang/AST/CharUnits.h"
27
#include "clang/AST/Decl.h"
28
#include "clang/AST/DeclObjC.h"
29
#include "clang/AST/DeclOpenMP.h"
30
#include "clang/Basic/CodeGenOptions.h"
31
#include "clang/Basic/SourceManager.h"
32
#include "clang/Basic/TargetInfo.h"
33
#include "clang/CodeGen/CGFunctionInfo.h"
34
#include "clang/Sema/Sema.h"
35
#include "llvm/Analysis/ValueTracking.h"
36
#include "llvm/IR/DataLayout.h"
37
#include "llvm/IR/GlobalVariable.h"
38
#include "llvm/IR/Intrinsics.h"
39
#include "llvm/IR/Type.h"
40
#include <optional>
41
42
using namespace clang;
43
using namespace CodeGen;
44
45
static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
46
              "Clang max alignment greater than what LLVM supports?");
47
48
0
void CodeGenFunction::EmitDecl(const Decl &D) {
49
0
  switch (D.getKind()) {
50
0
  case Decl::BuiltinTemplate:
51
0
  case Decl::TranslationUnit:
52
0
  case Decl::ExternCContext:
53
0
  case Decl::Namespace:
54
0
  case Decl::UnresolvedUsingTypename:
55
0
  case Decl::ClassTemplateSpecialization:
56
0
  case Decl::ClassTemplatePartialSpecialization:
57
0
  case Decl::VarTemplateSpecialization:
58
0
  case Decl::VarTemplatePartialSpecialization:
59
0
  case Decl::TemplateTypeParm:
60
0
  case Decl::UnresolvedUsingValue:
61
0
  case Decl::NonTypeTemplateParm:
62
0
  case Decl::CXXDeductionGuide:
63
0
  case Decl::CXXMethod:
64
0
  case Decl::CXXConstructor:
65
0
  case Decl::CXXDestructor:
66
0
  case Decl::CXXConversion:
67
0
  case Decl::Field:
68
0
  case Decl::MSProperty:
69
0
  case Decl::IndirectField:
70
0
  case Decl::ObjCIvar:
71
0
  case Decl::ObjCAtDefsField:
72
0
  case Decl::ParmVar:
73
0
  case Decl::ImplicitParam:
74
0
  case Decl::ClassTemplate:
75
0
  case Decl::VarTemplate:
76
0
  case Decl::FunctionTemplate:
77
0
  case Decl::TypeAliasTemplate:
78
0
  case Decl::TemplateTemplateParm:
79
0
  case Decl::ObjCMethod:
80
0
  case Decl::ObjCCategory:
81
0
  case Decl::ObjCProtocol:
82
0
  case Decl::ObjCInterface:
83
0
  case Decl::ObjCCategoryImpl:
84
0
  case Decl::ObjCImplementation:
85
0
  case Decl::ObjCProperty:
86
0
  case Decl::ObjCCompatibleAlias:
87
0
  case Decl::PragmaComment:
88
0
  case Decl::PragmaDetectMismatch:
89
0
  case Decl::AccessSpec:
90
0
  case Decl::LinkageSpec:
91
0
  case Decl::Export:
92
0
  case Decl::ObjCPropertyImpl:
93
0
  case Decl::FileScopeAsm:
94
0
  case Decl::TopLevelStmt:
95
0
  case Decl::Friend:
96
0
  case Decl::FriendTemplate:
97
0
  case Decl::Block:
98
0
  case Decl::Captured:
99
0
  case Decl::UsingShadow:
100
0
  case Decl::ConstructorUsingShadow:
101
0
  case Decl::ObjCTypeParam:
102
0
  case Decl::Binding:
103
0
  case Decl::UnresolvedUsingIfExists:
104
0
  case Decl::HLSLBuffer:
105
0
    llvm_unreachable("Declaration should not be in declstmts!");
106
0
  case Decl::Record:    // struct/union/class X;
107
0
  case Decl::CXXRecord: // struct/union/class X; [C++]
108
0
    if (CGDebugInfo *DI = getDebugInfo())
109
0
      if (cast<RecordDecl>(D).getDefinition())
110
0
        DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
111
0
    return;
112
0
  case Decl::Enum:      // enum X;
113
0
    if (CGDebugInfo *DI = getDebugInfo())
114
0
      if (cast<EnumDecl>(D).getDefinition())
115
0
        DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
116
0
    return;
117
0
  case Decl::Function:     // void X();
118
0
  case Decl::EnumConstant: // enum ? { X = ? }
119
0
  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
120
0
  case Decl::Label:        // __label__ x;
121
0
  case Decl::Import:
122
0
  case Decl::MSGuid:    // __declspec(uuid("..."))
123
0
  case Decl::UnnamedGlobalConstant:
124
0
  case Decl::TemplateParamObject:
125
0
  case Decl::OMPThreadPrivate:
126
0
  case Decl::OMPAllocate:
127
0
  case Decl::OMPCapturedExpr:
128
0
  case Decl::OMPRequires:
129
0
  case Decl::Empty:
130
0
  case Decl::Concept:
131
0
  case Decl::ImplicitConceptSpecialization:
132
0
  case Decl::LifetimeExtendedTemporary:
133
0
  case Decl::RequiresExprBody:
134
    // None of these decls require codegen support.
135
0
    return;
136
137
0
  case Decl::NamespaceAlias:
138
0
    if (CGDebugInfo *DI = getDebugInfo())
139
0
        DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
140
0
    return;
141
0
  case Decl::Using:          // using X; [C++]
142
0
    if (CGDebugInfo *DI = getDebugInfo())
143
0
        DI->EmitUsingDecl(cast<UsingDecl>(D));
144
0
    return;
145
0
  case Decl::UsingEnum: // using enum X; [C++]
146
0
    if (CGDebugInfo *DI = getDebugInfo())
147
0
      DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
148
0
    return;
149
0
  case Decl::UsingPack:
150
0
    for (auto *Using : cast<UsingPackDecl>(D).expansions())
151
0
      EmitDecl(*Using);
152
0
    return;
153
0
  case Decl::UsingDirective: // using namespace X; [C++]
154
0
    if (CGDebugInfo *DI = getDebugInfo())
155
0
      DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
156
0
    return;
157
0
  case Decl::Var:
158
0
  case Decl::Decomposition: {
159
0
    const VarDecl &VD = cast<VarDecl>(D);
160
0
    assert(VD.isLocalVarDecl() &&
161
0
           "Should not see file-scope variables inside a function!");
162
0
    EmitVarDecl(VD);
163
0
    if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
164
0
      for (auto *B : DD->bindings())
165
0
        if (auto *HD = B->getHoldingVar())
166
0
          EmitVarDecl(*HD);
167
0
    return;
168
0
  }
169
170
0
  case Decl::OMPDeclareReduction:
171
0
    return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
172
173
0
  case Decl::OMPDeclareMapper:
174
0
    return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
175
176
0
  case Decl::Typedef:      // typedef int X;
177
0
  case Decl::TypeAlias: {  // using X = int; [C++0x]
178
0
    QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
179
0
    if (CGDebugInfo *DI = getDebugInfo())
180
0
      DI->EmitAndRetainType(Ty);
181
0
    if (Ty->isVariablyModifiedType())
182
0
      EmitVariablyModifiedType(Ty);
183
0
    return;
184
0
  }
185
0
  }
186
0
}
187
188
/// EmitVarDecl - This method handles emission of any variable declaration
189
/// inside a function, including static vars etc.
190
0
void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
191
0
  if (D.hasExternalStorage())
192
    // Don't emit it now, allow it to be emitted lazily on its first use.
193
0
    return;
194
195
  // Some function-scope variable does not have static storage but still
196
  // needs to be emitted like a static variable, e.g. a function-scope
197
  // variable in constant address space in OpenCL.
198
0
  if (D.getStorageDuration() != SD_Automatic) {
199
    // Static sampler variables translated to function calls.
200
0
    if (D.getType()->isSamplerT())
201
0
      return;
202
203
0
    llvm::GlobalValue::LinkageTypes Linkage =
204
0
        CGM.getLLVMLinkageVarDefinition(&D);
205
206
    // FIXME: We need to force the emission/use of a guard variable for
207
    // some variables even if we can constant-evaluate them because
208
    // we can't guarantee every translation unit will constant-evaluate them.
209
210
0
    return EmitStaticVarDecl(D, Linkage);
211
0
  }
212
213
0
  if (D.getType().getAddressSpace() == LangAS::opencl_local)
214
0
    return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
215
216
0
  assert(D.hasLocalStorage());
217
0
  return EmitAutoVarDecl(D);
218
0
}
219
220
0
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
221
0
  if (CGM.getLangOpts().CPlusPlus)
222
0
    return CGM.getMangledName(&D).str();
223
224
  // If this isn't C++, we don't need a mangled name, just a pretty one.
225
0
  assert(!D.isExternallyVisible() && "name shouldn't matter");
226
0
  std::string ContextName;
227
0
  const DeclContext *DC = D.getDeclContext();
228
0
  if (auto *CD = dyn_cast<CapturedDecl>(DC))
229
0
    DC = cast<DeclContext>(CD->getNonClosureContext());
230
0
  if (const auto *FD = dyn_cast<FunctionDecl>(DC))
231
0
    ContextName = std::string(CGM.getMangledName(FD));
232
0
  else if (const auto *BD = dyn_cast<BlockDecl>(DC))
233
0
    ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
234
0
  else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
235
0
    ContextName = OMD->getSelector().getAsString();
236
0
  else
237
0
    llvm_unreachable("Unknown context for static var decl");
238
239
0
  ContextName += "." + D.getNameAsString();
240
0
  return ContextName;
241
0
}
242
243
llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
244
0
    const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
245
  // In general, we don't always emit static var decls once before we reference
246
  // them. It is possible to reference them before emitting the function that
247
  // contains them, and it is possible to emit the containing function multiple
248
  // times.
249
0
  if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
250
0
    return ExistingGV;
251
252
0
  QualType Ty = D.getType();
253
0
  assert(Ty->isConstantSizeType() && "VLAs can't be static");
254
255
  // Use the label if the variable is renamed with the asm-label extension.
256
0
  std::string Name;
257
0
  if (D.hasAttr<AsmLabelAttr>())
258
0
    Name = std::string(getMangledName(&D));
259
0
  else
260
0
    Name = getStaticDeclName(*this, D);
261
262
0
  llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
263
0
  LangAS AS = GetGlobalVarAddressSpace(&D);
264
0
  unsigned TargetAS = getContext().getTargetAddressSpace(AS);
265
266
  // OpenCL variables in local address space and CUDA shared
267
  // variables cannot have an initializer.
268
0
  llvm::Constant *Init = nullptr;
269
0
  if (Ty.getAddressSpace() == LangAS::opencl_local ||
270
0
      D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
271
0
    Init = llvm::UndefValue::get(LTy);
272
0
  else
273
0
    Init = EmitNullConstant(Ty);
274
275
0
  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
276
0
      getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
277
0
      nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
278
0
  GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
279
280
0
  if (supportsCOMDAT() && GV->isWeakForLinker())
281
0
    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
282
283
0
  if (D.getTLSKind())
284
0
    setTLSMode(GV, D);
285
286
0
  setGVProperties(GV, &D);
287
288
  // Make sure the result is of the correct type.
289
0
  LangAS ExpectedAS = Ty.getAddressSpace();
290
0
  llvm::Constant *Addr = GV;
291
0
  if (AS != ExpectedAS) {
292
0
    Addr = getTargetCodeGenInfo().performAddrSpaceCast(
293
0
        *this, GV, AS, ExpectedAS,
294
0
        llvm::PointerType::get(getLLVMContext(),
295
0
                               getContext().getTargetAddressSpace(ExpectedAS)));
296
0
  }
297
298
0
  setStaticLocalDeclAddress(&D, Addr);
299
300
  // Ensure that the static local gets initialized by making sure the parent
301
  // function gets emitted eventually.
302
0
  const Decl *DC = cast<Decl>(D.getDeclContext());
303
304
  // We can't name blocks or captured statements directly, so try to emit their
305
  // parents.
306
0
  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
307
0
    DC = DC->getNonClosureContext();
308
    // FIXME: Ensure that global blocks get emitted.
309
0
    if (!DC)
310
0
      return Addr;
311
0
  }
312
313
0
  GlobalDecl GD;
314
0
  if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
315
0
    GD = GlobalDecl(CD, Ctor_Base);
316
0
  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
317
0
    GD = GlobalDecl(DD, Dtor_Base);
318
0
  else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
319
0
    GD = GlobalDecl(FD);
320
0
  else {
321
    // Don't do anything for Obj-C method decls or global closures. We should
322
    // never defer them.
323
0
    assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
324
0
  }
325
0
  if (GD.getDecl()) {
326
    // Disable emission of the parent function for the OpenMP device codegen.
327
0
    CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
328
0
    (void)GetAddrOfGlobal(GD);
329
0
  }
330
331
0
  return Addr;
332
0
}
333
334
/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
335
/// global variable that has already been created for it.  If the initializer
336
/// has a different type than GV does, this may free GV and return a different
337
/// one.  Otherwise it just returns GV.
338
llvm::GlobalVariable *
339
CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
340
0
                                               llvm::GlobalVariable *GV) {
341
0
  ConstantEmitter emitter(*this);
342
0
  llvm::Constant *Init = emitter.tryEmitForInitializer(D);
343
344
  // If constant emission failed, then this should be a C++ static
345
  // initializer.
346
0
  if (!Init) {
347
0
    if (!getLangOpts().CPlusPlus)
348
0
      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
349
0
    else if (D.hasFlexibleArrayInit(getContext()))
350
0
      CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
351
0
    else if (HaveInsertPoint()) {
352
      // Since we have a static initializer, this global variable can't
353
      // be constant.
354
0
      GV->setConstant(false);
355
356
0
      EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
357
0
    }
358
0
    return GV;
359
0
  }
360
361
0
#ifndef NDEBUG
362
0
  CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
363
0
                      D.getFlexibleArrayInitChars(getContext());
364
0
  CharUnits CstSize = CharUnits::fromQuantity(
365
0
      CGM.getDataLayout().getTypeAllocSize(Init->getType()));
366
0
  assert(VarSize == CstSize && "Emitted constant has unexpected size");
367
0
#endif
368
369
  // The initializer may differ in type from the global. Rewrite
370
  // the global to match the initializer.  (We have to do this
371
  // because some types, like unions, can't be completely represented
372
  // in the LLVM type system.)
373
0
  if (GV->getValueType() != Init->getType()) {
374
0
    llvm::GlobalVariable *OldGV = GV;
375
376
0
    GV = new llvm::GlobalVariable(
377
0
        CGM.getModule(), Init->getType(), OldGV->isConstant(),
378
0
        OldGV->getLinkage(), Init, "",
379
0
        /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
380
0
        OldGV->getType()->getPointerAddressSpace());
381
0
    GV->setVisibility(OldGV->getVisibility());
382
0
    GV->setDSOLocal(OldGV->isDSOLocal());
383
0
    GV->setComdat(OldGV->getComdat());
384
385
    // Steal the name of the old global
386
0
    GV->takeName(OldGV);
387
388
    // Replace all uses of the old global with the new global
389
0
    OldGV->replaceAllUsesWith(GV);
390
391
    // Erase the old global, since it is no longer used.
392
0
    OldGV->eraseFromParent();
393
0
  }
394
395
0
  bool NeedsDtor =
396
0
      D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
397
398
0
  GV->setConstant(
399
0
      D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
400
0
  GV->setInitializer(Init);
401
402
0
  emitter.finalize(GV);
403
404
0
  if (NeedsDtor && HaveInsertPoint()) {
405
    // We have a constant initializer, but a nontrivial destructor. We still
406
    // need to perform a guarded "initialization" in order to register the
407
    // destructor.
408
0
    EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
409
0
  }
410
411
0
  return GV;
412
0
}
413
414
void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
415
0
                                      llvm::GlobalValue::LinkageTypes Linkage) {
416
  // Check to see if we already have a global variable for this
417
  // declaration.  This can happen when double-emitting function
418
  // bodies, e.g. with complete and base constructors.
419
0
  llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
420
0
  CharUnits alignment = getContext().getDeclAlign(&D);
421
422
  // Store into LocalDeclMap before generating initializer to handle
423
  // circular references.
424
0
  llvm::Type *elemTy = ConvertTypeForMem(D.getType());
425
0
  setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
426
427
  // We can't have a VLA here, but we can have a pointer to a VLA,
428
  // even though that doesn't really make any sense.
429
  // Make sure to evaluate VLA bounds now so that we have them for later.
430
0
  if (D.getType()->isVariablyModifiedType())
431
0
    EmitVariablyModifiedType(D.getType());
432
433
  // Save the type in case adding the initializer forces a type change.
434
0
  llvm::Type *expectedType = addr->getType();
435
436
0
  llvm::GlobalVariable *var =
437
0
    cast<llvm::GlobalVariable>(addr->stripPointerCasts());
438
439
  // CUDA's local and local static __shared__ variables should not
440
  // have any non-empty initializers. This is ensured by Sema.
441
  // Whatever initializer such variable may have when it gets here is
442
  // a no-op and should not be emitted.
443
0
  bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
444
0
                         D.hasAttr<CUDASharedAttr>();
445
  // If this value has an initializer, emit it.
446
0
  if (D.getInit() && !isCudaSharedVar)
447
0
    var = AddInitializerToStaticVarDecl(D, var);
448
449
0
  var->setAlignment(alignment.getAsAlign());
450
451
0
  if (D.hasAttr<AnnotateAttr>())
452
0
    CGM.AddGlobalAnnotations(&D, var);
453
454
0
  if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
455
0
    var->addAttribute("bss-section", SA->getName());
456
0
  if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
457
0
    var->addAttribute("data-section", SA->getName());
458
0
  if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
459
0
    var->addAttribute("rodata-section", SA->getName());
460
0
  if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
461
0
    var->addAttribute("relro-section", SA->getName());
462
463
0
  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
464
0
    var->setSection(SA->getName());
465
466
0
  if (D.hasAttr<RetainAttr>())
467
0
    CGM.addUsedGlobal(var);
468
0
  else if (D.hasAttr<UsedAttr>())
469
0
    CGM.addUsedOrCompilerUsedGlobal(var);
470
471
0
  if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
472
0
    CGM.addUsedOrCompilerUsedGlobal(var);
473
474
  // We may have to cast the constant because of the initializer
475
  // mismatch above.
476
  //
477
  // FIXME: It is really dangerous to store this in the map; if anyone
478
  // RAUW's the GV uses of this constant will be invalid.
479
0
  llvm::Constant *castedAddr =
480
0
    llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
481
0
  LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
482
0
  CGM.setStaticLocalDeclAddress(&D, castedAddr);
483
484
0
  CGM.getSanitizerMetadata()->reportGlobal(var, D);
485
486
  // Emit global variable debug descriptor for static vars.
487
0
  CGDebugInfo *DI = getDebugInfo();
488
0
  if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
489
0
    DI->setLocation(D.getLocation());
490
0
    DI->EmitGlobalVariable(var, &D);
491
0
  }
492
0
}
493
494
namespace {
495
  struct DestroyObject final : EHScopeStack::Cleanup {
496
    DestroyObject(Address addr, QualType type,
497
                  CodeGenFunction::Destroyer *destroyer,
498
                  bool useEHCleanupForArray)
499
      : addr(addr), type(type), destroyer(destroyer),
500
0
        useEHCleanupForArray(useEHCleanupForArray) {}
501
502
    Address addr;
503
    QualType type;
504
    CodeGenFunction::Destroyer *destroyer;
505
    bool useEHCleanupForArray;
506
507
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
508
      // Don't use an EH cleanup recursively from an EH cleanup.
509
0
      bool useEHCleanupForArray =
510
0
        flags.isForNormalCleanup() && this->useEHCleanupForArray;
511
512
0
      CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
513
0
    }
514
  };
515
516
  template <class Derived>
517
  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
518
    DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
519
0
        : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableCXX>::DestroyNRVOVariable(clang::CodeGen::Address, clang::QualType, llvm::Value*)
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableC>::DestroyNRVOVariable(clang::CodeGen::Address, clang::QualType, llvm::Value*)
520
521
    llvm::Value *NRVOFlag;
522
    Address Loc;
523
    QualType Ty;
524
525
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
526
      // Along the exceptions path we always execute the dtor.
527
0
      bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
528
529
0
      llvm::BasicBlock *SkipDtorBB = nullptr;
530
0
      if (NRVO) {
531
        // If we exited via NRVO, we skip the destructor call.
532
0
        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
533
0
        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
534
0
        llvm::Value *DidNRVO =
535
0
          CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
536
0
        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
537
0
        CGF.EmitBlock(RunDtorBB);
538
0
      }
539
540
0
      static_cast<Derived *>(this)->emitDestructorCall(CGF);
541
542
0
      if (NRVO) CGF.EmitBlock(SkipDtorBB);
543
0
    }
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableCXX>::Emit(clang::CodeGen::CodeGenFunction&, clang::CodeGen::EHScopeStack::Cleanup::Flags)
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableC>::Emit(clang::CodeGen::CodeGenFunction&, clang::CodeGen::EHScopeStack::Cleanup::Flags)
544
545
0
    virtual ~DestroyNRVOVariable() = default;
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableCXX>::~DestroyNRVOVariable()
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableC>::~DestroyNRVOVariable()
546
  };
547
548
  struct DestroyNRVOVariableCXX final
549
      : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
550
    DestroyNRVOVariableCXX(Address addr, QualType type,
551
                           const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
552
        : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
553
0
          Dtor(Dtor) {}
554
555
    const CXXDestructorDecl *Dtor;
556
557
0
    void emitDestructorCall(CodeGenFunction &CGF) {
558
0
      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
559
0
                                /*ForVirtualBase=*/false,
560
0
                                /*Delegating=*/false, Loc, Ty);
561
0
    }
562
  };
563
564
  struct DestroyNRVOVariableC final
565
      : DestroyNRVOVariable<DestroyNRVOVariableC> {
566
    DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
567
0
        : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
568
569
0
    void emitDestructorCall(CodeGenFunction &CGF) {
570
0
      CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
571
0
    }
572
  };
573
574
  struct CallStackRestore final : EHScopeStack::Cleanup {
575
    Address Stack;
576
0
    CallStackRestore(Address Stack) : Stack(Stack) {}
577
0
    bool isRedundantBeforeReturn() override { return true; }
578
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
579
0
      llvm::Value *V = CGF.Builder.CreateLoad(Stack);
580
0
      CGF.Builder.CreateStackRestore(V);
581
0
    }
582
  };
583
584
  struct KmpcAllocFree final : EHScopeStack::Cleanup {
585
    std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
586
    KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
587
0
        : AddrSizePair(AddrSizePair) {}
588
0
    void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
589
0
      auto &RT = CGF.CGM.getOpenMPRuntime();
590
0
      RT.getKmpcFreeShared(CGF, AddrSizePair);
591
0
    }
592
  };
593
594
  struct ExtendGCLifetime final : EHScopeStack::Cleanup {
595
    const VarDecl &Var;
596
0
    ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
597
598
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
599
      // Compute the address of the local variable, in case it's a
600
      // byref or something.
601
0
      DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
602
0
                      Var.getType(), VK_LValue, SourceLocation());
603
0
      llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
604
0
                                                SourceLocation());
605
0
      CGF.EmitExtendGCLifetime(value);
606
0
    }
607
  };
608
609
  struct CallCleanupFunction final : EHScopeStack::Cleanup {
610
    llvm::Constant *CleanupFn;
611
    const CGFunctionInfo &FnInfo;
612
    const VarDecl &Var;
613
614
    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
615
                        const VarDecl *Var)
616
0
      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
617
618
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
619
0
      DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
620
0
                      Var.getType(), VK_LValue, SourceLocation());
621
      // Compute the address of the local variable, in case it's a byref
622
      // or something.
623
0
      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
624
625
      // In some cases, the type of the function argument will be different from
626
      // the type of the pointer. An example of this is
627
      // void f(void* arg);
628
      // __attribute__((cleanup(f))) void *g;
629
      //
630
      // To fix this we insert a bitcast here.
631
0
      QualType ArgTy = FnInfo.arg_begin()->type;
632
0
      llvm::Value *Arg =
633
0
        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
634
635
0
      CallArgList Args;
636
0
      Args.add(RValue::get(Arg),
637
0
               CGF.getContext().getPointerType(Var.getType()));
638
0
      auto Callee = CGCallee::forDirect(CleanupFn);
639
0
      CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
640
0
    }
641
  };
642
} // end anonymous namespace
643
644
/// EmitAutoVarWithLifetime - Does the setup required for an automatic
645
/// variable with lifetime.
646
static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
647
                                    Address addr,
648
0
                                    Qualifiers::ObjCLifetime lifetime) {
649
0
  switch (lifetime) {
650
0
  case Qualifiers::OCL_None:
651
0
    llvm_unreachable("present but none");
652
653
0
  case Qualifiers::OCL_ExplicitNone:
654
    // nothing to do
655
0
    break;
656
657
0
  case Qualifiers::OCL_Strong: {
658
0
    CodeGenFunction::Destroyer *destroyer =
659
0
      (var.hasAttr<ObjCPreciseLifetimeAttr>()
660
0
       ? CodeGenFunction::destroyARCStrongPrecise
661
0
       : CodeGenFunction::destroyARCStrongImprecise);
662
663
0
    CleanupKind cleanupKind = CGF.getARCCleanupKind();
664
0
    CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
665
0
                    cleanupKind & EHCleanup);
666
0
    break;
667
0
  }
668
0
  case Qualifiers::OCL_Autoreleasing:
669
    // nothing to do
670
0
    break;
671
672
0
  case Qualifiers::OCL_Weak:
673
    // __weak objects always get EH cleanups; otherwise, exceptions
674
    // could cause really nasty crashes instead of mere leaks.
675
0
    CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
676
0
                    CodeGenFunction::destroyARCWeak,
677
0
                    /*useEHCleanup*/ true);
678
0
    break;
679
0
  }
680
0
}
681
682
0
static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
683
0
  if (const Expr *e = dyn_cast<Expr>(s)) {
684
    // Skip the most common kinds of expressions that make
685
    // hierarchy-walking expensive.
686
0
    s = e = e->IgnoreParenCasts();
687
688
0
    if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
689
0
      return (ref->getDecl() == &var);
690
0
    if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
691
0
      const BlockDecl *block = be->getBlockDecl();
692
0
      for (const auto &I : block->captures()) {
693
0
        if (I.getVariable() == &var)
694
0
          return true;
695
0
      }
696
0
    }
697
0
  }
698
699
0
  for (const Stmt *SubStmt : s->children())
700
    // SubStmt might be null; as in missing decl or conditional of an if-stmt.
701
0
    if (SubStmt && isAccessedBy(var, SubStmt))
702
0
      return true;
703
704
0
  return false;
705
0
}
706
707
0
static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
708
0
  if (!decl) return false;
709
0
  if (!isa<VarDecl>(decl)) return false;
710
0
  const VarDecl *var = cast<VarDecl>(decl);
711
0
  return isAccessedBy(*var, e);
712
0
}
713
714
static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
715
0
                                   const LValue &destLV, const Expr *init) {
716
0
  bool needsCast = false;
717
718
0
  while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
719
0
    switch (castExpr->getCastKind()) {
720
    // Look through casts that don't require representation changes.
721
0
    case CK_NoOp:
722
0
    case CK_BitCast:
723
0
    case CK_BlockPointerToObjCPointerCast:
724
0
      needsCast = true;
725
0
      break;
726
727
    // If we find an l-value to r-value cast from a __weak variable,
728
    // emit this operation as a copy or move.
729
0
    case CK_LValueToRValue: {
730
0
      const Expr *srcExpr = castExpr->getSubExpr();
731
0
      if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
732
0
        return false;
733
734
      // Emit the source l-value.
735
0
      LValue srcLV = CGF.EmitLValue(srcExpr);
736
737
      // Handle a formal type change to avoid asserting.
738
0
      auto srcAddr = srcLV.getAddress(CGF);
739
0
      if (needsCast) {
740
0
        srcAddr =
741
0
            srcAddr.withElementType(destLV.getAddress(CGF).getElementType());
742
0
      }
743
744
      // If it was an l-value, use objc_copyWeak.
745
0
      if (srcExpr->isLValue()) {
746
0
        CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
747
0
      } else {
748
0
        assert(srcExpr->isXValue());
749
0
        CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
750
0
      }
751
0
      return true;
752
0
    }
753
754
    // Stop at anything else.
755
0
    default:
756
0
      return false;
757
0
    }
758
759
0
    init = castExpr->getSubExpr();
760
0
  }
761
0
  return false;
762
0
}
763
764
static void drillIntoBlockVariable(CodeGenFunction &CGF,
765
                                   LValue &lvalue,
766
0
                                   const VarDecl *var) {
767
0
  lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
768
0
}
769
770
void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
771
0
                                           SourceLocation Loc) {
772
0
  if (!SanOpts.has(SanitizerKind::NullabilityAssign))
773
0
    return;
774
775
0
  auto Nullability = LHS.getType()->getNullability();
776
0
  if (!Nullability || *Nullability != NullabilityKind::NonNull)
777
0
    return;
778
779
  // Check if the right hand side of the assignment is nonnull, if the left
780
  // hand side must be nonnull.
781
0
  SanitizerScope SanScope(this);
782
0
  llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
783
0
  llvm::Constant *StaticData[] = {
784
0
      EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
785
0
      llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
786
0
      llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
787
0
  EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
788
0
            SanitizerHandler::TypeMismatch, StaticData, RHS);
789
0
}
790
791
void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
792
0
                                     LValue lvalue, bool capturedByInit) {
793
0
  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
794
0
  if (!lifetime) {
795
0
    llvm::Value *value = EmitScalarExpr(init);
796
0
    if (capturedByInit)
797
0
      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
798
0
    EmitNullabilityCheck(lvalue, value, init->getExprLoc());
799
0
    EmitStoreThroughLValue(RValue::get(value), lvalue, true);
800
0
    return;
801
0
  }
802
803
0
  if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
804
0
    init = DIE->getExpr();
805
806
  // If we're emitting a value with lifetime, we have to do the
807
  // initialization *before* we leave the cleanup scopes.
808
0
  if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
809
0
    CodeGenFunction::RunCleanupsScope Scope(*this);
810
0
    return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
811
0
  }
812
813
  // We have to maintain the illusion that the variable is
814
  // zero-initialized.  If the variable might be accessed in its
815
  // initializer, zero-initialize before running the initializer, then
816
  // actually perform the initialization with an assign.
817
0
  bool accessedByInit = false;
818
0
  if (lifetime != Qualifiers::OCL_ExplicitNone)
819
0
    accessedByInit = (capturedByInit || isAccessedBy(D, init));
820
0
  if (accessedByInit) {
821
0
    LValue tempLV = lvalue;
822
    // Drill down to the __block object if necessary.
823
0
    if (capturedByInit) {
824
      // We can use a simple GEP for this because it can't have been
825
      // moved yet.
826
0
      tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
827
0
                                              cast<VarDecl>(D),
828
0
                                              /*follow*/ false));
829
0
    }
830
831
0
    auto ty =
832
0
        cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
833
0
    llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
834
835
    // If __weak, we want to use a barrier under certain conditions.
836
0
    if (lifetime == Qualifiers::OCL_Weak)
837
0
      EmitARCInitWeak(tempLV.getAddress(*this), zero);
838
839
    // Otherwise just do a simple store.
840
0
    else
841
0
      EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
842
0
  }
843
844
  // Emit the initializer.
845
0
  llvm::Value *value = nullptr;
846
847
0
  switch (lifetime) {
848
0
  case Qualifiers::OCL_None:
849
0
    llvm_unreachable("present but none");
850
851
0
  case Qualifiers::OCL_Strong: {
852
0
    if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
853
0
      value = EmitARCRetainScalarExpr(init);
854
0
      break;
855
0
    }
856
    // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
857
    // that we omit the retain, and causes non-autoreleased return values to be
858
    // immediately released.
859
0
    [[fallthrough]];
860
0
  }
861
862
0
  case Qualifiers::OCL_ExplicitNone:
863
0
    value = EmitARCUnsafeUnretainedScalarExpr(init);
864
0
    break;
865
866
0
  case Qualifiers::OCL_Weak: {
867
    // If it's not accessed by the initializer, try to emit the
868
    // initialization with a copy or move.
869
0
    if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
870
0
      return;
871
0
    }
872
873
    // No way to optimize a producing initializer into this.  It's not
874
    // worth optimizing for, because the value will immediately
875
    // disappear in the common case.
876
0
    value = EmitScalarExpr(init);
877
878
0
    if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
879
0
    if (accessedByInit)
880
0
      EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
881
0
    else
882
0
      EmitARCInitWeak(lvalue.getAddress(*this), value);
883
0
    return;
884
0
  }
885
886
0
  case Qualifiers::OCL_Autoreleasing:
887
0
    value = EmitARCRetainAutoreleaseScalarExpr(init);
888
0
    break;
889
0
  }
890
891
0
  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
892
893
0
  EmitNullabilityCheck(lvalue, value, init->getExprLoc());
894
895
  // If the variable might have been accessed by its initializer, we
896
  // might have to initialize with a barrier.  We have to do this for
897
  // both __weak and __strong, but __weak got filtered out above.
898
0
  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
899
0
    llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
900
0
    EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
901
0
    EmitARCRelease(oldValue, ARCImpreciseLifetime);
902
0
    return;
903
0
  }
904
905
0
  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
906
0
}
907
908
/// Decide whether we can emit the non-zero parts of the specified initializer
909
/// with equal or fewer than NumStores scalar stores.
910
static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
911
0
                                               unsigned &NumStores) {
912
  // Zero and Undef never requires any extra stores.
913
0
  if (isa<llvm::ConstantAggregateZero>(Init) ||
914
0
      isa<llvm::ConstantPointerNull>(Init) ||
915
0
      isa<llvm::UndefValue>(Init))
916
0
    return true;
917
0
  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
918
0
      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
919
0
      isa<llvm::ConstantExpr>(Init))
920
0
    return Init->isNullValue() || NumStores--;
921
922
  // See if we can emit each element.
923
0
  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
924
0
    for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
925
0
      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
926
0
      if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
927
0
        return false;
928
0
    }
929
0
    return true;
930
0
  }
931
932
0
  if (llvm::ConstantDataSequential *CDS =
933
0
        dyn_cast<llvm::ConstantDataSequential>(Init)) {
934
0
    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
935
0
      llvm::Constant *Elt = CDS->getElementAsConstant(i);
936
0
      if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
937
0
        return false;
938
0
    }
939
0
    return true;
940
0
  }
941
942
  // Anything else is hard and scary.
943
0
  return false;
944
0
}
945
946
/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
947
/// the scalar stores that would be required.
948
static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
949
                                        llvm::Constant *Init, Address Loc,
950
                                        bool isVolatile, CGBuilderTy &Builder,
951
0
                                        bool IsAutoInit) {
952
0
  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
953
0
         "called emitStoresForInitAfterBZero for zero or undef value.");
954
955
0
  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
956
0
      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
957
0
      isa<llvm::ConstantExpr>(Init)) {
958
0
    auto *I = Builder.CreateStore(Init, Loc, isVolatile);
959
0
    if (IsAutoInit)
960
0
      I->addAnnotationMetadata("auto-init");
961
0
    return;
962
0
  }
963
964
0
  if (llvm::ConstantDataSequential *CDS =
965
0
          dyn_cast<llvm::ConstantDataSequential>(Init)) {
966
0
    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
967
0
      llvm::Constant *Elt = CDS->getElementAsConstant(i);
968
969
      // If necessary, get a pointer to the element and emit it.
970
0
      if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
971
0
        emitStoresForInitAfterBZero(
972
0
            CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
973
0
            Builder, IsAutoInit);
974
0
    }
975
0
    return;
976
0
  }
977
978
0
  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
979
0
         "Unknown value type!");
980
981
0
  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
982
0
    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
983
984
    // If necessary, get a pointer to the element and emit it.
985
0
    if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
986
0
      emitStoresForInitAfterBZero(CGM, Elt,
987
0
                                  Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
988
0
                                  isVolatile, Builder, IsAutoInit);
989
0
  }
990
0
}
991
992
/// Decide whether we should use bzero plus some stores to initialize a local
993
/// variable instead of using a memcpy from a constant global.  It is beneficial
994
/// to use bzero if the global is all zeros, or mostly zeros and large.
995
static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
996
0
                                                 uint64_t GlobalSize) {
997
  // If a global is all zeros, always use a bzero.
998
0
  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
999
1000
  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
1001
  // do it if it will require 6 or fewer scalar stores.
1002
  // TODO: Should budget depends on the size?  Avoiding a large global warrants
1003
  // plopping in more stores.
1004
0
  unsigned StoreBudget = 6;
1005
0
  uint64_t SizeLimit = 32;
1006
1007
0
  return GlobalSize > SizeLimit &&
1008
0
         canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
1009
0
}
1010
1011
/// Decide whether we should use memset to initialize a local variable instead
1012
/// of using a memcpy from a constant global. Assumes we've already decided to
1013
/// not user bzero.
1014
/// FIXME We could be more clever, as we are for bzero above, and generate
1015
///       memset followed by stores. It's unclear that's worth the effort.
1016
static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
1017
                                                uint64_t GlobalSize,
1018
0
                                                const llvm::DataLayout &DL) {
1019
0
  uint64_t SizeLimit = 32;
1020
0
  if (GlobalSize <= SizeLimit)
1021
0
    return nullptr;
1022
0
  return llvm::isBytewiseValue(Init, DL);
1023
0
}
1024
1025
/// Decide whether we want to split a constant structure or array store into a
1026
/// sequence of its fields' stores. This may cost us code size and compilation
1027
/// speed, but plays better with store optimizations.
1028
static bool shouldSplitConstantStore(CodeGenModule &CGM,
1029
0
                                     uint64_t GlobalByteSize) {
1030
  // Don't break things that occupy more than one cacheline.
1031
0
  uint64_t ByteSizeLimit = 64;
1032
0
  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1033
0
    return false;
1034
0
  if (GlobalByteSize <= ByteSizeLimit)
1035
0
    return true;
1036
0
  return false;
1037
0
}
1038
1039
enum class IsPattern { No, Yes };
1040
1041
/// Generate a constant filled with either a pattern or zeroes.
1042
static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1043
0
                                        llvm::Type *Ty) {
1044
0
  if (isPattern == IsPattern::Yes)
1045
0
    return initializationPatternFor(CGM, Ty);
1046
0
  else
1047
0
    return llvm::Constant::getNullValue(Ty);
1048
0
}
1049
1050
static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1051
                                        llvm::Constant *constant);
1052
1053
/// Helper function for constWithPadding() to deal with padding in structures.
1054
static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1055
                                              IsPattern isPattern,
1056
                                              llvm::StructType *STy,
1057
0
                                              llvm::Constant *constant) {
1058
0
  const llvm::DataLayout &DL = CGM.getDataLayout();
1059
0
  const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1060
0
  llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1061
0
  unsigned SizeSoFar = 0;
1062
0
  SmallVector<llvm::Constant *, 8> Values;
1063
0
  bool NestedIntact = true;
1064
0
  for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1065
0
    unsigned CurOff = Layout->getElementOffset(i);
1066
0
    if (SizeSoFar < CurOff) {
1067
0
      assert(!STy->isPacked());
1068
0
      auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1069
0
      Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1070
0
    }
1071
0
    llvm::Constant *CurOp;
1072
0
    if (constant->isZeroValue())
1073
0
      CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1074
0
    else
1075
0
      CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1076
0
    auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1077
0
    if (CurOp != NewOp)
1078
0
      NestedIntact = false;
1079
0
    Values.push_back(NewOp);
1080
0
    SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1081
0
  }
1082
0
  unsigned TotalSize = Layout->getSizeInBytes();
1083
0
  if (SizeSoFar < TotalSize) {
1084
0
    auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1085
0
    Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1086
0
  }
1087
0
  if (NestedIntact && Values.size() == STy->getNumElements())
1088
0
    return constant;
1089
0
  return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1090
0
}
1091
1092
/// Replace all padding bytes in a given constant with either a pattern byte or
1093
/// 0x00.
1094
static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1095
0
                                        llvm::Constant *constant) {
1096
0
  llvm::Type *OrigTy = constant->getType();
1097
0
  if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1098
0
    return constStructWithPadding(CGM, isPattern, STy, constant);
1099
0
  if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1100
0
    llvm::SmallVector<llvm::Constant *, 8> Values;
1101
0
    uint64_t Size = ArrayTy->getNumElements();
1102
0
    if (!Size)
1103
0
      return constant;
1104
0
    llvm::Type *ElemTy = ArrayTy->getElementType();
1105
0
    bool ZeroInitializer = constant->isNullValue();
1106
0
    llvm::Constant *OpValue, *PaddedOp;
1107
0
    if (ZeroInitializer) {
1108
0
      OpValue = llvm::Constant::getNullValue(ElemTy);
1109
0
      PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1110
0
    }
1111
0
    for (unsigned Op = 0; Op != Size; ++Op) {
1112
0
      if (!ZeroInitializer) {
1113
0
        OpValue = constant->getAggregateElement(Op);
1114
0
        PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1115
0
      }
1116
0
      Values.push_back(PaddedOp);
1117
0
    }
1118
0
    auto *NewElemTy = Values[0]->getType();
1119
0
    if (NewElemTy == ElemTy)
1120
0
      return constant;
1121
0
    auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1122
0
    return llvm::ConstantArray::get(NewArrayTy, Values);
1123
0
  }
1124
  // FIXME: Add handling for tail padding in vectors. Vectors don't
1125
  // have padding between or inside elements, but the total amount of
1126
  // data can be less than the allocated size.
1127
0
  return constant;
1128
0
}
1129
1130
Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1131
                                               llvm::Constant *Constant,
1132
0
                                               CharUnits Align) {
1133
0
  auto FunctionName = [&](const DeclContext *DC) -> std::string {
1134
0
    if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1135
0
      if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1136
0
        return CC->getNameAsString();
1137
0
      if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1138
0
        return CD->getNameAsString();
1139
0
      return std::string(getMangledName(FD));
1140
0
    } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1141
0
      return OM->getNameAsString();
1142
0
    } else if (isa<BlockDecl>(DC)) {
1143
0
      return "<block>";
1144
0
    } else if (isa<CapturedDecl>(DC)) {
1145
0
      return "<captured>";
1146
0
    } else {
1147
0
      llvm_unreachable("expected a function or method");
1148
0
    }
1149
0
  };
1150
1151
  // Form a simple per-variable cache of these values in case we find we
1152
  // want to reuse them.
1153
0
  llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1154
0
  if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1155
0
    auto *Ty = Constant->getType();
1156
0
    bool isConstant = true;
1157
0
    llvm::GlobalVariable *InsertBefore = nullptr;
1158
0
    unsigned AS =
1159
0
        getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
1160
0
    std::string Name;
1161
0
    if (D.hasGlobalStorage())
1162
0
      Name = getMangledName(&D).str() + ".const";
1163
0
    else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1164
0
      Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1165
0
    else
1166
0
      llvm_unreachable("local variable has no parent function or method");
1167
0
    llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1168
0
        getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1169
0
        Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1170
0
    GV->setAlignment(Align.getAsAlign());
1171
0
    GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1172
0
    CacheEntry = GV;
1173
0
  } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1174
0
    CacheEntry->setAlignment(Align.getAsAlign());
1175
0
  }
1176
1177
0
  return Address(CacheEntry, CacheEntry->getValueType(), Align);
1178
0
}
1179
1180
static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1181
                                                const VarDecl &D,
1182
                                                CGBuilderTy &Builder,
1183
                                                llvm::Constant *Constant,
1184
0
                                                CharUnits Align) {
1185
0
  Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1186
0
  return SrcPtr.withElementType(CGM.Int8Ty);
1187
0
}
1188
1189
static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1190
                                  Address Loc, bool isVolatile,
1191
                                  CGBuilderTy &Builder,
1192
0
                                  llvm::Constant *constant, bool IsAutoInit) {
1193
0
  auto *Ty = constant->getType();
1194
0
  uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1195
0
  if (!ConstantSize)
1196
0
    return;
1197
1198
0
  bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1199
0
                          Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1200
0
  if (canDoSingleStore) {
1201
0
    auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1202
0
    if (IsAutoInit)
1203
0
      I->addAnnotationMetadata("auto-init");
1204
0
    return;
1205
0
  }
1206
1207
0
  auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1208
1209
  // If the initializer is all or mostly the same, codegen with bzero / memset
1210
  // then do a few stores afterward.
1211
0
  if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1212
0
    auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1213
0
                                   SizeVal, isVolatile);
1214
0
    if (IsAutoInit)
1215
0
      I->addAnnotationMetadata("auto-init");
1216
1217
0
    bool valueAlreadyCorrect =
1218
0
        constant->isNullValue() || isa<llvm::UndefValue>(constant);
1219
0
    if (!valueAlreadyCorrect) {
1220
0
      Loc = Loc.withElementType(Ty);
1221
0
      emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1222
0
                                  IsAutoInit);
1223
0
    }
1224
0
    return;
1225
0
  }
1226
1227
  // If the initializer is a repeated byte pattern, use memset.
1228
0
  llvm::Value *Pattern =
1229
0
      shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1230
0
  if (Pattern) {
1231
0
    uint64_t Value = 0x00;
1232
0
    if (!isa<llvm::UndefValue>(Pattern)) {
1233
0
      const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1234
0
      assert(AP.getBitWidth() <= 8);
1235
0
      Value = AP.getLimitedValue();
1236
0
    }
1237
0
    auto *I = Builder.CreateMemSet(
1238
0
        Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1239
0
    if (IsAutoInit)
1240
0
      I->addAnnotationMetadata("auto-init");
1241
0
    return;
1242
0
  }
1243
1244
  // If the initializer is small, use a handful of stores.
1245
0
  if (shouldSplitConstantStore(CGM, ConstantSize)) {
1246
0
    if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1247
0
      const llvm::StructLayout *Layout =
1248
0
          CGM.getDataLayout().getStructLayout(STy);
1249
0
      for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1250
0
        CharUnits CurOff = CharUnits::fromQuantity(Layout->getElementOffset(i));
1251
0
        Address EltPtr = Builder.CreateConstInBoundsByteGEP(
1252
0
            Loc.withElementType(CGM.Int8Ty), CurOff);
1253
0
        emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1254
0
                              constant->getAggregateElement(i), IsAutoInit);
1255
0
      }
1256
0
      return;
1257
0
    } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1258
0
      for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1259
0
        Address EltPtr = Builder.CreateConstGEP(
1260
0
            Loc.withElementType(ATy->getElementType()), i);
1261
0
        emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1262
0
                              constant->getAggregateElement(i), IsAutoInit);
1263
0
      }
1264
0
      return;
1265
0
    }
1266
0
  }
1267
1268
  // Copy from a global.
1269
0
  auto *I =
1270
0
      Builder.CreateMemCpy(Loc,
1271
0
                           createUnnamedGlobalForMemcpyFrom(
1272
0
                               CGM, D, Builder, constant, Loc.getAlignment()),
1273
0
                           SizeVal, isVolatile);
1274
0
  if (IsAutoInit)
1275
0
    I->addAnnotationMetadata("auto-init");
1276
0
}
1277
1278
static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1279
                                  Address Loc, bool isVolatile,
1280
0
                                  CGBuilderTy &Builder) {
1281
0
  llvm::Type *ElTy = Loc.getElementType();
1282
0
  llvm::Constant *constant =
1283
0
      constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1284
0
  emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1285
0
                        /*IsAutoInit=*/true);
1286
0
}
1287
1288
static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1289
                                     Address Loc, bool isVolatile,
1290
0
                                     CGBuilderTy &Builder) {
1291
0
  llvm::Type *ElTy = Loc.getElementType();
1292
0
  llvm::Constant *constant = constWithPadding(
1293
0
      CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1294
0
  assert(!isa<llvm::UndefValue>(constant));
1295
0
  emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1296
0
                        /*IsAutoInit=*/true);
1297
0
}
1298
1299
0
static bool containsUndef(llvm::Constant *constant) {
1300
0
  auto *Ty = constant->getType();
1301
0
  if (isa<llvm::UndefValue>(constant))
1302
0
    return true;
1303
0
  if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1304
0
    for (llvm::Use &Op : constant->operands())
1305
0
      if (containsUndef(cast<llvm::Constant>(Op)))
1306
0
        return true;
1307
0
  return false;
1308
0
}
1309
1310
static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1311
0
                                    llvm::Constant *constant) {
1312
0
  auto *Ty = constant->getType();
1313
0
  if (isa<llvm::UndefValue>(constant))
1314
0
    return patternOrZeroFor(CGM, isPattern, Ty);
1315
0
  if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1316
0
    return constant;
1317
0
  if (!containsUndef(constant))
1318
0
    return constant;
1319
0
  llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1320
0
  for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1321
0
    auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1322
0
    Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1323
0
  }
1324
0
  if (Ty->isStructTy())
1325
0
    return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1326
0
  if (Ty->isArrayTy())
1327
0
    return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1328
0
  assert(Ty->isVectorTy());
1329
0
  return llvm::ConstantVector::get(Values);
1330
0
}
1331
1332
/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1333
/// variable declaration with auto, register, or no storage class specifier.
1334
/// These turn into simple stack objects, or GlobalValues depending on target.
1335
0
void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1336
0
  AutoVarEmission emission = EmitAutoVarAlloca(D);
1337
0
  EmitAutoVarInit(emission);
1338
0
  EmitAutoVarCleanups(emission);
1339
0
}
1340
1341
/// Emit a lifetime.begin marker if some criteria are satisfied.
1342
/// \return a pointer to the temporary size Value if a marker was emitted, null
1343
/// otherwise
1344
llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
1345
0
                                                llvm::Value *Addr) {
1346
0
  if (!ShouldEmitLifetimeMarkers)
1347
0
    return nullptr;
1348
1349
0
  assert(Addr->getType()->getPointerAddressSpace() ==
1350
0
             CGM.getDataLayout().getAllocaAddrSpace() &&
1351
0
         "Pointer should be in alloca address space");
1352
0
  llvm::Value *SizeV = llvm::ConstantInt::get(
1353
0
      Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
1354
0
  llvm::CallInst *C =
1355
0
      Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1356
0
  C->setDoesNotThrow();
1357
0
  return SizeV;
1358
0
}
1359
1360
0
void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1361
0
  assert(Addr->getType()->getPointerAddressSpace() ==
1362
0
             CGM.getDataLayout().getAllocaAddrSpace() &&
1363
0
         "Pointer should be in alloca address space");
1364
0
  llvm::CallInst *C =
1365
0
      Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1366
0
  C->setDoesNotThrow();
1367
0
}
1368
1369
void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1370
0
    CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1371
  // For each dimension stores its QualType and corresponding
1372
  // size-expression Value.
1373
0
  SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1374
0
  SmallVector<IdentifierInfo *, 4> VLAExprNames;
1375
1376
  // Break down the array into individual dimensions.
1377
0
  QualType Type1D = D.getType();
1378
0
  while (getContext().getAsVariableArrayType(Type1D)) {
1379
0
    auto VlaSize = getVLAElements1D(Type1D);
1380
0
    if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1381
0
      Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1382
0
    else {
1383
      // Generate a locally unique name for the size expression.
1384
0
      Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1385
0
      SmallString<12> Buffer;
1386
0
      StringRef NameRef = Name.toStringRef(Buffer);
1387
0
      auto &Ident = getContext().Idents.getOwn(NameRef);
1388
0
      VLAExprNames.push_back(&Ident);
1389
0
      auto SizeExprAddr =
1390
0
          CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1391
0
      Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1392
0
      Dimensions.emplace_back(SizeExprAddr.getPointer(),
1393
0
                              Type1D.getUnqualifiedType());
1394
0
    }
1395
0
    Type1D = VlaSize.Type;
1396
0
  }
1397
1398
0
  if (!EmitDebugInfo)
1399
0
    return;
1400
1401
  // Register each dimension's size-expression with a DILocalVariable,
1402
  // so that it can be used by CGDebugInfo when instantiating a DISubrange
1403
  // to describe this array.
1404
0
  unsigned NameIdx = 0;
1405
0
  for (auto &VlaSize : Dimensions) {
1406
0
    llvm::Metadata *MD;
1407
0
    if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1408
0
      MD = llvm::ConstantAsMetadata::get(C);
1409
0
    else {
1410
      // Create an artificial VarDecl to generate debug info for.
1411
0
      IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1412
0
      auto QT = getContext().getIntTypeForBitwidth(
1413
0
          SizeTy->getScalarSizeInBits(), false);
1414
0
      auto *ArtificialDecl = VarDecl::Create(
1415
0
          getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1416
0
          D.getLocation(), D.getLocation(), NameIdent, QT,
1417
0
          getContext().CreateTypeSourceInfo(QT), SC_Auto);
1418
0
      ArtificialDecl->setImplicit();
1419
1420
0
      MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1421
0
                                         Builder);
1422
0
    }
1423
0
    assert(MD && "No Size expression debug node created");
1424
0
    DI->registerVLASizeExpression(VlaSize.Type, MD);
1425
0
  }
1426
0
}
1427
1428
/// EmitAutoVarAlloca - Emit the alloca and debug information for a
1429
/// local variable.  Does not emit initialization or destruction.
1430
CodeGenFunction::AutoVarEmission
1431
0
CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1432
0
  QualType Ty = D.getType();
1433
0
  assert(
1434
0
      Ty.getAddressSpace() == LangAS::Default ||
1435
0
      (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1436
1437
0
  AutoVarEmission emission(D);
1438
1439
0
  bool isEscapingByRef = D.isEscapingByref();
1440
0
  emission.IsEscapingByRef = isEscapingByRef;
1441
1442
0
  CharUnits alignment = getContext().getDeclAlign(&D);
1443
1444
  // If the type is variably-modified, emit all the VLA sizes for it.
1445
0
  if (Ty->isVariablyModifiedType())
1446
0
    EmitVariablyModifiedType(Ty);
1447
1448
0
  auto *DI = getDebugInfo();
1449
0
  bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1450
1451
0
  Address address = Address::invalid();
1452
0
  Address AllocaAddr = Address::invalid();
1453
0
  Address OpenMPLocalAddr = Address::invalid();
1454
0
  if (CGM.getLangOpts().OpenMPIRBuilder)
1455
0
    OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1456
0
  else
1457
0
    OpenMPLocalAddr =
1458
0
        getLangOpts().OpenMP
1459
0
            ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1460
0
            : Address::invalid();
1461
1462
0
  bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1463
1464
0
  if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1465
0
    address = OpenMPLocalAddr;
1466
0
    AllocaAddr = OpenMPLocalAddr;
1467
0
  } else if (Ty->isConstantSizeType()) {
1468
    // If this value is an array or struct with a statically determinable
1469
    // constant initializer, there are optimizations we can do.
1470
    //
1471
    // TODO: We should constant-evaluate the initializer of any variable,
1472
    // as long as it is initialized by a constant expression. Currently,
1473
    // isConstantInitializer produces wrong answers for structs with
1474
    // reference or bitfield members, and a few other cases, and checking
1475
    // for POD-ness protects us from some of these.
1476
0
    if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1477
0
        (D.isConstexpr() ||
1478
0
         ((Ty.isPODType(getContext()) ||
1479
0
           getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1480
0
          D.getInit()->isConstantInitializer(getContext(), false)))) {
1481
1482
      // If the variable's a const type, and it's neither an NRVO
1483
      // candidate nor a __block variable and has no mutable members,
1484
      // emit it as a global instead.
1485
      // Exception is if a variable is located in non-constant address space
1486
      // in OpenCL.
1487
0
      bool NeedsDtor =
1488
0
          D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
1489
0
      if ((!getLangOpts().OpenCL ||
1490
0
           Ty.getAddressSpace() == LangAS::opencl_constant) &&
1491
0
          (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1492
0
           !isEscapingByRef &&
1493
0
           Ty.isConstantStorage(getContext(), true, !NeedsDtor))) {
1494
0
        EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1495
1496
        // Signal this condition to later callbacks.
1497
0
        emission.Addr = Address::invalid();
1498
0
        assert(emission.wasEmittedAsGlobal());
1499
0
        return emission;
1500
0
      }
1501
1502
      // Otherwise, tell the initialization code that we're in this case.
1503
0
      emission.IsConstantAggregate = true;
1504
0
    }
1505
1506
    // A normal fixed sized variable becomes an alloca in the entry block,
1507
    // unless:
1508
    // - it's an NRVO variable.
1509
    // - we are compiling OpenMP and it's an OpenMP local variable.
1510
0
    if (NRVO) {
1511
      // The named return value optimization: allocate this variable in the
1512
      // return slot, so that we can elide the copy when returning this
1513
      // variable (C++0x [class.copy]p34).
1514
0
      address = ReturnValue;
1515
0
      AllocaAddr = ReturnValue;
1516
1517
0
      if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1518
0
        const auto *RD = RecordTy->getDecl();
1519
0
        const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1520
0
        if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1521
0
            RD->isNonTrivialToPrimitiveDestroy()) {
1522
          // Create a flag that is used to indicate when the NRVO was applied
1523
          // to this variable. Set it to zero to indicate that NRVO was not
1524
          // applied.
1525
0
          llvm::Value *Zero = Builder.getFalse();
1526
0
          Address NRVOFlag =
1527
0
              CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1528
0
          EnsureInsertPoint();
1529
0
          Builder.CreateStore(Zero, NRVOFlag);
1530
1531
          // Record the NRVO flag for this variable.
1532
0
          NRVOFlags[&D] = NRVOFlag.getPointer();
1533
0
          emission.NRVOFlag = NRVOFlag.getPointer();
1534
0
        }
1535
0
      }
1536
0
    } else {
1537
0
      CharUnits allocaAlignment;
1538
0
      llvm::Type *allocaTy;
1539
0
      if (isEscapingByRef) {
1540
0
        auto &byrefInfo = getBlockByrefInfo(&D);
1541
0
        allocaTy = byrefInfo.Type;
1542
0
        allocaAlignment = byrefInfo.ByrefAlignment;
1543
0
      } else {
1544
0
        allocaTy = ConvertTypeForMem(Ty);
1545
0
        allocaAlignment = alignment;
1546
0
      }
1547
1548
      // Create the alloca.  Note that we set the name separately from
1549
      // building the instruction so that it's there even in no-asserts
1550
      // builds.
1551
0
      address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1552
0
                                 /*ArraySize=*/nullptr, &AllocaAddr);
1553
1554
      // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1555
      // the catch parameter starts in the catchpad instruction, and we can't
1556
      // insert code in those basic blocks.
1557
0
      bool IsMSCatchParam =
1558
0
          D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1559
1560
      // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1561
      // if we don't have a valid insertion point (?).
1562
0
      if (HaveInsertPoint() && !IsMSCatchParam) {
1563
        // If there's a jump into the lifetime of this variable, its lifetime
1564
        // gets broken up into several regions in IR, which requires more work
1565
        // to handle correctly. For now, just omit the intrinsics; this is a
1566
        // rare case, and it's better to just be conservatively correct.
1567
        // PR28267.
1568
        //
1569
        // We have to do this in all language modes if there's a jump past the
1570
        // declaration. We also have to do it in C if there's a jump to an
1571
        // earlier point in the current block because non-VLA lifetimes begin as
1572
        // soon as the containing block is entered, not when its variables
1573
        // actually come into scope; suppressing the lifetime annotations
1574
        // completely in this case is unnecessarily pessimistic, but again, this
1575
        // is rare.
1576
0
        if (!Bypasses.IsBypassed(&D) &&
1577
0
            !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1578
0
          llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1579
0
          emission.SizeForLifetimeMarkers =
1580
0
              EmitLifetimeStart(Size, AllocaAddr.getPointer());
1581
0
        }
1582
0
      } else {
1583
0
        assert(!emission.useLifetimeMarkers());
1584
0
      }
1585
0
    }
1586
0
  } else {
1587
0
    EnsureInsertPoint();
1588
1589
    // Delayed globalization for variable length declarations. This ensures that
1590
    // the expression representing the length has been emitted and can be used
1591
    // by the definition of the VLA. Since this is an escaped declaration, in
1592
    // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
1593
    // deallocation call to __kmpc_free_shared() is emitted later.
1594
0
    bool VarAllocated = false;
1595
0
    if (getLangOpts().OpenMPIsTargetDevice) {
1596
0
      auto &RT = CGM.getOpenMPRuntime();
1597
0
      if (RT.isDelayedVariableLengthDecl(*this, &D)) {
1598
        // Emit call to __kmpc_alloc_shared() instead of the alloca.
1599
0
        std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1600
0
            RT.getKmpcAllocShared(*this, &D);
1601
1602
        // Save the address of the allocation:
1603
0
        LValue Base = MakeAddrLValue(AddrSizePair.first, D.getType(),
1604
0
                                     CGM.getContext().getDeclAlign(&D),
1605
0
                                     AlignmentSource::Decl);
1606
0
        address = Base.getAddress(*this);
1607
1608
        // Push a cleanup block to emit the call to __kmpc_free_shared in the
1609
        // appropriate location at the end of the scope of the
1610
        // __kmpc_alloc_shared functions:
1611
0
        pushKmpcAllocFree(NormalCleanup, AddrSizePair);
1612
1613
        // Mark variable as allocated:
1614
0
        VarAllocated = true;
1615
0
      }
1616
0
    }
1617
1618
0
    if (!VarAllocated) {
1619
0
      if (!DidCallStackSave) {
1620
        // Save the stack.
1621
0
        Address Stack =
1622
0
            CreateDefaultAlignTempAlloca(AllocaInt8PtrTy, "saved_stack");
1623
1624
0
        llvm::Value *V = Builder.CreateStackSave();
1625
0
        assert(V->getType() == AllocaInt8PtrTy);
1626
0
        Builder.CreateStore(V, Stack);
1627
1628
0
        DidCallStackSave = true;
1629
1630
        // Push a cleanup block and restore the stack there.
1631
        // FIXME: in general circumstances, this should be an EH cleanup.
1632
0
        pushStackRestore(NormalCleanup, Stack);
1633
0
      }
1634
1635
0
      auto VlaSize = getVLASize(Ty);
1636
0
      llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1637
1638
      // Allocate memory for the array.
1639
0
      address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1640
0
                                 &AllocaAddr);
1641
0
    }
1642
1643
    // If we have debug info enabled, properly describe the VLA dimensions for
1644
    // this type by registering the vla size expression for each of the
1645
    // dimensions.
1646
0
    EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1647
0
  }
1648
1649
0
  setAddrOfLocalVar(&D, address);
1650
0
  emission.Addr = address;
1651
0
  emission.AllocaAddr = AllocaAddr;
1652
1653
  // Emit debug info for local var declaration.
1654
0
  if (EmitDebugInfo && HaveInsertPoint()) {
1655
0
    Address DebugAddr = address;
1656
0
    bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1657
0
    DI->setLocation(D.getLocation());
1658
1659
    // If NRVO, use a pointer to the return address.
1660
0
    if (UsePointerValue) {
1661
0
      DebugAddr = ReturnValuePointer;
1662
0
      AllocaAddr = ReturnValuePointer;
1663
0
    }
1664
0
    (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
1665
0
                                        UsePointerValue);
1666
0
  }
1667
1668
0
  if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1669
0
    EmitVarAnnotations(&D, address.getPointer());
1670
1671
  // Make sure we call @llvm.lifetime.end.
1672
0
  if (emission.useLifetimeMarkers())
1673
0
    EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1674
0
                                         emission.getOriginalAllocatedAddress(),
1675
0
                                         emission.getSizeForLifetimeMarkers());
1676
1677
0
  return emission;
1678
0
}
1679
1680
static bool isCapturedBy(const VarDecl &, const Expr *);
1681
1682
/// Determines whether the given __block variable is potentially
1683
/// captured by the given statement.
1684
0
static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1685
0
  if (const Expr *E = dyn_cast<Expr>(S))
1686
0
    return isCapturedBy(Var, E);
1687
0
  for (const Stmt *SubStmt : S->children())
1688
0
    if (isCapturedBy(Var, SubStmt))
1689
0
      return true;
1690
0
  return false;
1691
0
}
1692
1693
/// Determines whether the given __block variable is potentially
1694
/// captured by the given expression.
1695
0
static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1696
  // Skip the most common kinds of expressions that make
1697
  // hierarchy-walking expensive.
1698
0
  E = E->IgnoreParenCasts();
1699
1700
0
  if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1701
0
    const BlockDecl *Block = BE->getBlockDecl();
1702
0
    for (const auto &I : Block->captures()) {
1703
0
      if (I.getVariable() == &Var)
1704
0
        return true;
1705
0
    }
1706
1707
    // No need to walk into the subexpressions.
1708
0
    return false;
1709
0
  }
1710
1711
0
  if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1712
0
    const CompoundStmt *CS = SE->getSubStmt();
1713
0
    for (const auto *BI : CS->body())
1714
0
      if (const auto *BIE = dyn_cast<Expr>(BI)) {
1715
0
        if (isCapturedBy(Var, BIE))
1716
0
          return true;
1717
0
      }
1718
0
      else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1719
          // special case declarations
1720
0
          for (const auto *I : DS->decls()) {
1721
0
              if (const auto *VD = dyn_cast<VarDecl>((I))) {
1722
0
                const Expr *Init = VD->getInit();
1723
0
                if (Init && isCapturedBy(Var, Init))
1724
0
                  return true;
1725
0
              }
1726
0
          }
1727
0
      }
1728
0
      else
1729
        // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1730
        // Later, provide code to poke into statements for capture analysis.
1731
0
        return true;
1732
0
    return false;
1733
0
  }
1734
1735
0
  for (const Stmt *SubStmt : E->children())
1736
0
    if (isCapturedBy(Var, SubStmt))
1737
0
      return true;
1738
1739
0
  return false;
1740
0
}
1741
1742
/// Determine whether the given initializer is trivial in the sense
1743
/// that it requires no code to be generated.
1744
0
bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1745
0
  if (!Init)
1746
0
    return true;
1747
1748
0
  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1749
0
    if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1750
0
      if (Constructor->isTrivial() &&
1751
0
          Constructor->isDefaultConstructor() &&
1752
0
          !Construct->requiresZeroInitialization())
1753
0
        return true;
1754
1755
0
  return false;
1756
0
}
1757
1758
void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1759
                                                      const VarDecl &D,
1760
0
                                                      Address Loc) {
1761
0
  auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1762
0
  CharUnits Size = getContext().getTypeSizeInChars(type);
1763
0
  bool isVolatile = type.isVolatileQualified();
1764
0
  if (!Size.isZero()) {
1765
0
    switch (trivialAutoVarInit) {
1766
0
    case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1767
0
      llvm_unreachable("Uninitialized handled by caller");
1768
0
    case LangOptions::TrivialAutoVarInitKind::Zero:
1769
0
      if (CGM.stopAutoInit())
1770
0
        return;
1771
0
      emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1772
0
      break;
1773
0
    case LangOptions::TrivialAutoVarInitKind::Pattern:
1774
0
      if (CGM.stopAutoInit())
1775
0
        return;
1776
0
      emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1777
0
      break;
1778
0
    }
1779
0
    return;
1780
0
  }
1781
1782
  // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1783
  // them, so emit a memcpy with the VLA size to initialize each element.
1784
  // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1785
  // will catch that code, but there exists code which generates zero-sized
1786
  // VLAs. Be nice and initialize whatever they requested.
1787
0
  const auto *VlaType = getContext().getAsVariableArrayType(type);
1788
0
  if (!VlaType)
1789
0
    return;
1790
0
  auto VlaSize = getVLASize(VlaType);
1791
0
  auto SizeVal = VlaSize.NumElts;
1792
0
  CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1793
0
  switch (trivialAutoVarInit) {
1794
0
  case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1795
0
    llvm_unreachable("Uninitialized handled by caller");
1796
1797
0
  case LangOptions::TrivialAutoVarInitKind::Zero: {
1798
0
    if (CGM.stopAutoInit())
1799
0
      return;
1800
0
    if (!EltSize.isOne())
1801
0
      SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1802
0
    auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1803
0
                                   SizeVal, isVolatile);
1804
0
    I->addAnnotationMetadata("auto-init");
1805
0
    break;
1806
0
  }
1807
1808
0
  case LangOptions::TrivialAutoVarInitKind::Pattern: {
1809
0
    if (CGM.stopAutoInit())
1810
0
      return;
1811
0
    llvm::Type *ElTy = Loc.getElementType();
1812
0
    llvm::Constant *Constant = constWithPadding(
1813
0
        CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1814
0
    CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1815
0
    llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1816
0
    llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1817
0
    llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1818
0
    llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1819
0
        SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1820
0
        "vla.iszerosized");
1821
0
    Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1822
0
    EmitBlock(SetupBB);
1823
0
    if (!EltSize.isOne())
1824
0
      SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1825
0
    llvm::Value *BaseSizeInChars =
1826
0
        llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1827
0
    Address Begin = Loc.withElementType(Int8Ty);
1828
0
    llvm::Value *End = Builder.CreateInBoundsGEP(
1829
0
        Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
1830
0
    llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1831
0
    EmitBlock(LoopBB);
1832
0
    llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1833
0
    Cur->addIncoming(Begin.getPointer(), OriginBB);
1834
0
    CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1835
0
    auto *I =
1836
0
        Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
1837
0
                             createUnnamedGlobalForMemcpyFrom(
1838
0
                                 CGM, D, Builder, Constant, ConstantAlign),
1839
0
                             BaseSizeInChars, isVolatile);
1840
0
    I->addAnnotationMetadata("auto-init");
1841
0
    llvm::Value *Next =
1842
0
        Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1843
0
    llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1844
0
    Builder.CreateCondBr(Done, ContBB, LoopBB);
1845
0
    Cur->addIncoming(Next, LoopBB);
1846
0
    EmitBlock(ContBB);
1847
0
  } break;
1848
0
  }
1849
0
}
1850
1851
0
void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1852
0
  assert(emission.Variable && "emission was not valid!");
1853
1854
  // If this was emitted as a global constant, we're done.
1855
0
  if (emission.wasEmittedAsGlobal()) return;
1856
1857
0
  const VarDecl &D = *emission.Variable;
1858
0
  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1859
0
  QualType type = D.getType();
1860
1861
  // If this local has an initializer, emit it now.
1862
0
  const Expr *Init = D.getInit();
1863
1864
  // If we are at an unreachable point, we don't need to emit the initializer
1865
  // unless it contains a label.
1866
0
  if (!HaveInsertPoint()) {
1867
0
    if (!Init || !ContainsLabel(Init)) return;
1868
0
    EnsureInsertPoint();
1869
0
  }
1870
1871
  // Initialize the structure of a __block variable.
1872
0
  if (emission.IsEscapingByRef)
1873
0
    emitByrefStructureInit(emission);
1874
1875
  // Initialize the variable here if it doesn't have a initializer and it is a
1876
  // C struct that is non-trivial to initialize or an array containing such a
1877
  // struct.
1878
0
  if (!Init &&
1879
0
      type.isNonTrivialToPrimitiveDefaultInitialize() ==
1880
0
          QualType::PDIK_Struct) {
1881
0
    LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1882
0
    if (emission.IsEscapingByRef)
1883
0
      drillIntoBlockVariable(*this, Dst, &D);
1884
0
    defaultInitNonTrivialCStructVar(Dst);
1885
0
    return;
1886
0
  }
1887
1888
  // Check whether this is a byref variable that's potentially
1889
  // captured and moved by its own initializer.  If so, we'll need to
1890
  // emit the initializer first, then copy into the variable.
1891
0
  bool capturedByInit =
1892
0
      Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1893
1894
0
  bool locIsByrefHeader = !capturedByInit;
1895
0
  const Address Loc =
1896
0
      locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1897
1898
  // Note: constexpr already initializes everything correctly.
1899
0
  LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1900
0
      (D.isConstexpr()
1901
0
           ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1902
0
           : (D.getAttr<UninitializedAttr>()
1903
0
                  ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1904
0
                  : getContext().getLangOpts().getTrivialAutoVarInit()));
1905
1906
0
  auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1907
0
    if (trivialAutoVarInit ==
1908
0
        LangOptions::TrivialAutoVarInitKind::Uninitialized)
1909
0
      return;
1910
1911
    // Only initialize a __block's storage: we always initialize the header.
1912
0
    if (emission.IsEscapingByRef && !locIsByrefHeader)
1913
0
      Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1914
1915
0
    return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1916
0
  };
1917
1918
0
  if (isTrivialInitializer(Init))
1919
0
    return initializeWhatIsTechnicallyUninitialized(Loc);
1920
1921
0
  llvm::Constant *constant = nullptr;
1922
0
  if (emission.IsConstantAggregate ||
1923
0
      D.mightBeUsableInConstantExpressions(getContext())) {
1924
0
    assert(!capturedByInit && "constant init contains a capturing block?");
1925
0
    constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1926
0
    if (constant && !constant->isZeroValue() &&
1927
0
        (trivialAutoVarInit !=
1928
0
         LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1929
0
      IsPattern isPattern =
1930
0
          (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1931
0
              ? IsPattern::Yes
1932
0
              : IsPattern::No;
1933
      // C guarantees that brace-init with fewer initializers than members in
1934
      // the aggregate will initialize the rest of the aggregate as-if it were
1935
      // static initialization. In turn static initialization guarantees that
1936
      // padding is initialized to zero bits. We could instead pattern-init if D
1937
      // has any ImplicitValueInitExpr, but that seems to be unintuitive
1938
      // behavior.
1939
0
      constant = constWithPadding(CGM, IsPattern::No,
1940
0
                                  replaceUndef(CGM, isPattern, constant));
1941
0
    }
1942
0
  }
1943
1944
0
  if (!constant) {
1945
0
    initializeWhatIsTechnicallyUninitialized(Loc);
1946
0
    LValue lv = MakeAddrLValue(Loc, type);
1947
0
    lv.setNonGC(true);
1948
0
    return EmitExprAsInit(Init, &D, lv, capturedByInit);
1949
0
  }
1950
1951
0
  if (!emission.IsConstantAggregate) {
1952
    // For simple scalar/complex initialization, store the value directly.
1953
0
    LValue lv = MakeAddrLValue(Loc, type);
1954
0
    lv.setNonGC(true);
1955
0
    return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1956
0
  }
1957
1958
0
  emitStoresForConstant(CGM, D, Loc.withElementType(CGM.Int8Ty),
1959
0
                        type.isVolatileQualified(), Builder, constant,
1960
0
                        /*IsAutoInit=*/false);
1961
0
}
1962
1963
/// Emit an expression as an initializer for an object (variable, field, etc.)
1964
/// at the given location.  The expression is not necessarily the normal
1965
/// initializer for the object, and the address is not necessarily
1966
/// its normal location.
1967
///
1968
/// \param init the initializing expression
1969
/// \param D the object to act as if we're initializing
1970
/// \param lvalue the lvalue to initialize
1971
/// \param capturedByInit true if \p D is a __block variable
1972
///   whose address is potentially changed by the initializer
1973
void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1974
0
                                     LValue lvalue, bool capturedByInit) {
1975
0
  QualType type = D->getType();
1976
1977
0
  if (type->isReferenceType()) {
1978
0
    RValue rvalue = EmitReferenceBindingToExpr(init);
1979
0
    if (capturedByInit)
1980
0
      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1981
0
    EmitStoreThroughLValue(rvalue, lvalue, true);
1982
0
    return;
1983
0
  }
1984
0
  switch (getEvaluationKind(type)) {
1985
0
  case TEK_Scalar:
1986
0
    EmitScalarInit(init, D, lvalue, capturedByInit);
1987
0
    return;
1988
0
  case TEK_Complex: {
1989
0
    ComplexPairTy complex = EmitComplexExpr(init);
1990
0
    if (capturedByInit)
1991
0
      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1992
0
    EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1993
0
    return;
1994
0
  }
1995
0
  case TEK_Aggregate:
1996
0
    if (type->isAtomicType()) {
1997
0
      EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1998
0
    } else {
1999
0
      AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
2000
0
      if (isa<VarDecl>(D))
2001
0
        Overlap = AggValueSlot::DoesNotOverlap;
2002
0
      else if (auto *FD = dyn_cast<FieldDecl>(D))
2003
0
        Overlap = getOverlapForFieldInit(FD);
2004
      // TODO: how can we delay here if D is captured by its initializer?
2005
0
      EmitAggExpr(init, AggValueSlot::forLValue(
2006
0
                            lvalue, *this, AggValueSlot::IsDestructed,
2007
0
                            AggValueSlot::DoesNotNeedGCBarriers,
2008
0
                            AggValueSlot::IsNotAliased, Overlap));
2009
0
    }
2010
0
    return;
2011
0
  }
2012
0
  llvm_unreachable("bad evaluation kind");
2013
0
}
2014
2015
/// Enter a destroy cleanup for the given local variable.
2016
void CodeGenFunction::emitAutoVarTypeCleanup(
2017
                            const CodeGenFunction::AutoVarEmission &emission,
2018
0
                            QualType::DestructionKind dtorKind) {
2019
0
  assert(dtorKind != QualType::DK_none);
2020
2021
  // Note that for __block variables, we want to destroy the
2022
  // original stack object, not the possibly forwarded object.
2023
0
  Address addr = emission.getObjectAddress(*this);
2024
2025
0
  const VarDecl *var = emission.Variable;
2026
0
  QualType type = var->getType();
2027
2028
0
  CleanupKind cleanupKind = NormalAndEHCleanup;
2029
0
  CodeGenFunction::Destroyer *destroyer = nullptr;
2030
2031
0
  switch (dtorKind) {
2032
0
  case QualType::DK_none:
2033
0
    llvm_unreachable("no cleanup for trivially-destructible variable");
2034
2035
0
  case QualType::DK_cxx_destructor:
2036
    // If there's an NRVO flag on the emission, we need a different
2037
    // cleanup.
2038
0
    if (emission.NRVOFlag) {
2039
0
      assert(!type->isArrayType());
2040
0
      CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2041
0
      EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
2042
0
                                                  emission.NRVOFlag);
2043
0
      return;
2044
0
    }
2045
0
    break;
2046
2047
0
  case QualType::DK_objc_strong_lifetime:
2048
    // Suppress cleanups for pseudo-strong variables.
2049
0
    if (var->isARCPseudoStrong()) return;
2050
2051
    // Otherwise, consider whether to use an EH cleanup or not.
2052
0
    cleanupKind = getARCCleanupKind();
2053
2054
    // Use the imprecise destroyer by default.
2055
0
    if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2056
0
      destroyer = CodeGenFunction::destroyARCStrongImprecise;
2057
0
    break;
2058
2059
0
  case QualType::DK_objc_weak_lifetime:
2060
0
    break;
2061
2062
0
  case QualType::DK_nontrivial_c_struct:
2063
0
    destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2064
0
    if (emission.NRVOFlag) {
2065
0
      assert(!type->isArrayType());
2066
0
      EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2067
0
                                                emission.NRVOFlag, type);
2068
0
      return;
2069
0
    }
2070
0
    break;
2071
0
  }
2072
2073
  // If we haven't chosen a more specific destroyer, use the default.
2074
0
  if (!destroyer) destroyer = getDestroyer(dtorKind);
2075
2076
  // Use an EH cleanup in array destructors iff the destructor itself
2077
  // is being pushed as an EH cleanup.
2078
0
  bool useEHCleanup = (cleanupKind & EHCleanup);
2079
0
  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2080
0
                                     useEHCleanup);
2081
0
}
2082
2083
0
void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2084
0
  assert(emission.Variable && "emission was not valid!");
2085
2086
  // If this was emitted as a global constant, we're done.
2087
0
  if (emission.wasEmittedAsGlobal()) return;
2088
2089
  // If we don't have an insertion point, we're done.  Sema prevents
2090
  // us from jumping into any of these scopes anyway.
2091
0
  if (!HaveInsertPoint()) return;
2092
2093
0
  const VarDecl &D = *emission.Variable;
2094
2095
  // Check the type for a cleanup.
2096
0
  if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2097
0
    emitAutoVarTypeCleanup(emission, dtorKind);
2098
2099
  // In GC mode, honor objc_precise_lifetime.
2100
0
  if (getLangOpts().getGC() != LangOptions::NonGC &&
2101
0
      D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2102
0
    EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2103
0
  }
2104
2105
  // Handle the cleanup attribute.
2106
0
  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2107
0
    const FunctionDecl *FD = CA->getFunctionDecl();
2108
2109
0
    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2110
0
    assert(F && "Could not find function!");
2111
2112
0
    const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2113
0
    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2114
0
  }
2115
2116
  // If this is a block variable, call _Block_object_destroy
2117
  // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2118
  // mode.
2119
0
  if (emission.IsEscapingByRef &&
2120
0
      CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2121
0
    BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2122
0
    if (emission.Variable->getType().isObjCGCWeak())
2123
0
      Flags |= BLOCK_FIELD_IS_WEAK;
2124
0
    enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2125
0
                      /*LoadBlockVarAddr*/ false,
2126
0
                      cxxDestructorCanThrow(emission.Variable->getType()));
2127
0
  }
2128
0
}
2129
2130
CodeGenFunction::Destroyer *
2131
0
CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2132
0
  switch (kind) {
2133
0
  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2134
0
  case QualType::DK_cxx_destructor:
2135
0
    return destroyCXXObject;
2136
0
  case QualType::DK_objc_strong_lifetime:
2137
0
    return destroyARCStrongPrecise;
2138
0
  case QualType::DK_objc_weak_lifetime:
2139
0
    return destroyARCWeak;
2140
0
  case QualType::DK_nontrivial_c_struct:
2141
0
    return destroyNonTrivialCStruct;
2142
0
  }
2143
0
  llvm_unreachable("Unknown DestructionKind");
2144
0
}
2145
2146
/// pushEHDestroy - Push the standard destructor for the given type as
2147
/// an EH-only cleanup.
2148
void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2149
0
                                    Address addr, QualType type) {
2150
0
  assert(dtorKind && "cannot push destructor for trivial type");
2151
0
  assert(needsEHCleanup(dtorKind));
2152
2153
0
  pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2154
0
}
2155
2156
/// pushDestroy - Push the standard destructor for the given type as
2157
/// at least a normal cleanup.
2158
void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2159
0
                                  Address addr, QualType type) {
2160
0
  assert(dtorKind && "cannot push destructor for trivial type");
2161
2162
0
  CleanupKind cleanupKind = getCleanupKind(dtorKind);
2163
0
  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2164
0
              cleanupKind & EHCleanup);
2165
0
}
2166
2167
void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2168
                                  QualType type, Destroyer *destroyer,
2169
0
                                  bool useEHCleanupForArray) {
2170
0
  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2171
0
                                     destroyer, useEHCleanupForArray);
2172
0
}
2173
2174
0
void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2175
0
  EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2176
0
}
2177
2178
void CodeGenFunction::pushKmpcAllocFree(
2179
0
    CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
2180
0
  EHStack.pushCleanup<KmpcAllocFree>(Kind, AddrSizePair);
2181
0
}
2182
2183
void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2184
                                                  Address addr, QualType type,
2185
                                                  Destroyer *destroyer,
2186
0
                                                  bool useEHCleanupForArray) {
2187
  // If we're not in a conditional branch, we don't need to bother generating a
2188
  // conditional cleanup.
2189
0
  if (!isInConditionalBranch()) {
2190
    // Push an EH-only cleanup for the object now.
2191
    // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2192
    // around in case a temporary's destructor throws an exception.
2193
0
    if (cleanupKind & EHCleanup)
2194
0
      EHStack.pushCleanup<DestroyObject>(
2195
0
          static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2196
0
          destroyer, useEHCleanupForArray);
2197
2198
0
    return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2199
0
        cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2200
0
  }
2201
2202
  // Otherwise, we should only destroy the object if it's been initialized.
2203
  // Re-use the active flag and saved address across both the EH and end of
2204
  // scope cleanups.
2205
2206
0
  using SavedType = typename DominatingValue<Address>::saved_type;
2207
0
  using ConditionalCleanupType =
2208
0
      EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2209
0
                                       Destroyer *, bool>;
2210
2211
0
  Address ActiveFlag = createCleanupActiveFlag();
2212
0
  SavedType SavedAddr = saveValueInCond(addr);
2213
2214
0
  if (cleanupKind & EHCleanup) {
2215
0
    EHStack.pushCleanup<ConditionalCleanupType>(
2216
0
        static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2217
0
        destroyer, useEHCleanupForArray);
2218
0
    initFullExprCleanupWithFlag(ActiveFlag);
2219
0
  }
2220
2221
0
  pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2222
0
      cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2223
0
      useEHCleanupForArray);
2224
0
}
2225
2226
/// emitDestroy - Immediately perform the destruction of the given
2227
/// object.
2228
///
2229
/// \param addr - the address of the object; a type*
2230
/// \param type - the type of the object; if an array type, all
2231
///   objects are destroyed in reverse order
2232
/// \param destroyer - the function to call to destroy individual
2233
///   elements
2234
/// \param useEHCleanupForArray - whether an EH cleanup should be
2235
///   used when destroying array elements, in case one of the
2236
///   destructions throws an exception
2237
void CodeGenFunction::emitDestroy(Address addr, QualType type,
2238
                                  Destroyer *destroyer,
2239
0
                                  bool useEHCleanupForArray) {
2240
0
  const ArrayType *arrayType = getContext().getAsArrayType(type);
2241
0
  if (!arrayType)
2242
0
    return destroyer(*this, addr, type);
2243
2244
0
  llvm::Value *length = emitArrayLength(arrayType, type, addr);
2245
2246
0
  CharUnits elementAlign =
2247
0
    addr.getAlignment()
2248
0
        .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2249
2250
  // Normally we have to check whether the array is zero-length.
2251
0
  bool checkZeroLength = true;
2252
2253
  // But if the array length is constant, we can suppress that.
2254
0
  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2255
    // ...and if it's constant zero, we can just skip the entire thing.
2256
0
    if (constLength->isZero()) return;
2257
0
    checkZeroLength = false;
2258
0
  }
2259
2260
0
  llvm::Value *begin = addr.getPointer();
2261
0
  llvm::Value *end =
2262
0
      Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
2263
0
  emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2264
0
                   checkZeroLength, useEHCleanupForArray);
2265
0
}
2266
2267
/// emitArrayDestroy - Destroys all the elements of the given array,
2268
/// beginning from last to first.  The array cannot be zero-length.
2269
///
2270
/// \param begin - a type* denoting the first element of the array
2271
/// \param end - a type* denoting one past the end of the array
2272
/// \param elementType - the element type of the array
2273
/// \param destroyer - the function to call to destroy elements
2274
/// \param useEHCleanup - whether to push an EH cleanup to destroy
2275
///   the remaining elements in case the destruction of a single
2276
///   element throws
2277
void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2278
                                       llvm::Value *end,
2279
                                       QualType elementType,
2280
                                       CharUnits elementAlign,
2281
                                       Destroyer *destroyer,
2282
                                       bool checkZeroLength,
2283
0
                                       bool useEHCleanup) {
2284
0
  assert(!elementType->isArrayType());
2285
2286
  // The basic structure here is a do-while loop, because we don't
2287
  // need to check for the zero-element case.
2288
0
  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2289
0
  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2290
2291
0
  if (checkZeroLength) {
2292
0
    llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2293
0
                                                "arraydestroy.isempty");
2294
0
    Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2295
0
  }
2296
2297
  // Enter the loop body, making that address the current address.
2298
0
  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2299
0
  EmitBlock(bodyBB);
2300
0
  llvm::PHINode *elementPast =
2301
0
    Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2302
0
  elementPast->addIncoming(end, entryBB);
2303
2304
  // Shift the address back by one element.
2305
0
  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2306
0
  llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
2307
0
  llvm::Value *element = Builder.CreateInBoundsGEP(
2308
0
      llvmElementType, elementPast, negativeOne, "arraydestroy.element");
2309
2310
0
  if (useEHCleanup)
2311
0
    pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2312
0
                                   destroyer);
2313
2314
  // Perform the actual destruction there.
2315
0
  destroyer(*this, Address(element, llvmElementType, elementAlign),
2316
0
            elementType);
2317
2318
0
  if (useEHCleanup)
2319
0
    PopCleanupBlock();
2320
2321
  // Check whether we've reached the end.
2322
0
  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2323
0
  Builder.CreateCondBr(done, doneBB, bodyBB);
2324
0
  elementPast->addIncoming(element, Builder.GetInsertBlock());
2325
2326
  // Done.
2327
0
  EmitBlock(doneBB);
2328
0
}
2329
2330
/// Perform partial array destruction as if in an EH cleanup.  Unlike
2331
/// emitArrayDestroy, the element type here may still be an array type.
2332
static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2333
                                    llvm::Value *begin, llvm::Value *end,
2334
                                    QualType type, CharUnits elementAlign,
2335
0
                                    CodeGenFunction::Destroyer *destroyer) {
2336
0
  llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
2337
2338
  // If the element type is itself an array, drill down.
2339
0
  unsigned arrayDepth = 0;
2340
0
  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2341
    // VLAs don't require a GEP index to walk into.
2342
0
    if (!isa<VariableArrayType>(arrayType))
2343
0
      arrayDepth++;
2344
0
    type = arrayType->getElementType();
2345
0
  }
2346
2347
0
  if (arrayDepth) {
2348
0
    llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2349
2350
0
    SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2351
0
    begin = CGF.Builder.CreateInBoundsGEP(
2352
0
        elemTy, begin, gepIndices, "pad.arraybegin");
2353
0
    end = CGF.Builder.CreateInBoundsGEP(
2354
0
        elemTy, end, gepIndices, "pad.arrayend");
2355
0
  }
2356
2357
  // Destroy the array.  We don't ever need an EH cleanup because we
2358
  // assume that we're in an EH cleanup ourselves, so a throwing
2359
  // destructor causes an immediate terminate.
2360
0
  CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2361
0
                       /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2362
0
}
2363
2364
namespace {
2365
  /// RegularPartialArrayDestroy - a cleanup which performs a partial
2366
  /// array destroy where the end pointer is regularly determined and
2367
  /// does not need to be loaded from a local.
2368
  class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2369
    llvm::Value *ArrayBegin;
2370
    llvm::Value *ArrayEnd;
2371
    QualType ElementType;
2372
    CodeGenFunction::Destroyer *Destroyer;
2373
    CharUnits ElementAlign;
2374
  public:
2375
    RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2376
                               QualType elementType, CharUnits elementAlign,
2377
                               CodeGenFunction::Destroyer *destroyer)
2378
      : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2379
        ElementType(elementType), Destroyer(destroyer),
2380
0
        ElementAlign(elementAlign) {}
2381
2382
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2383
0
      emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2384
0
                              ElementType, ElementAlign, Destroyer);
2385
0
    }
2386
  };
2387
2388
  /// IrregularPartialArrayDestroy - a cleanup which performs a
2389
  /// partial array destroy where the end pointer is irregularly
2390
  /// determined and must be loaded from a local.
2391
  class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2392
    llvm::Value *ArrayBegin;
2393
    Address ArrayEndPointer;
2394
    QualType ElementType;
2395
    CodeGenFunction::Destroyer *Destroyer;
2396
    CharUnits ElementAlign;
2397
  public:
2398
    IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2399
                                 Address arrayEndPointer,
2400
                                 QualType elementType,
2401
                                 CharUnits elementAlign,
2402
                                 CodeGenFunction::Destroyer *destroyer)
2403
      : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2404
        ElementType(elementType), Destroyer(destroyer),
2405
0
        ElementAlign(elementAlign) {}
2406
2407
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2408
0
      llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2409
0
      emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2410
0
                              ElementType, ElementAlign, Destroyer);
2411
0
    }
2412
  };
2413
} // end anonymous namespace
2414
2415
/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2416
/// already-constructed elements of the given array.  The cleanup
2417
/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2418
///
2419
/// \param elementType - the immediate element type of the array;
2420
///   possibly still an array type
2421
void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2422
                                                       Address arrayEndPointer,
2423
                                                       QualType elementType,
2424
                                                       CharUnits elementAlign,
2425
0
                                                       Destroyer *destroyer) {
2426
0
  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2427
0
                                                    arrayBegin, arrayEndPointer,
2428
0
                                                    elementType, elementAlign,
2429
0
                                                    destroyer);
2430
0
}
2431
2432
/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2433
/// already-constructed elements of the given array.  The cleanup
2434
/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2435
///
2436
/// \param elementType - the immediate element type of the array;
2437
///   possibly still an array type
2438
void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2439
                                                     llvm::Value *arrayEnd,
2440
                                                     QualType elementType,
2441
                                                     CharUnits elementAlign,
2442
0
                                                     Destroyer *destroyer) {
2443
0
  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2444
0
                                                  arrayBegin, arrayEnd,
2445
0
                                                  elementType, elementAlign,
2446
0
                                                  destroyer);
2447
0
}
2448
2449
/// Lazily declare the @llvm.lifetime.start intrinsic.
2450
0
llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2451
0
  if (LifetimeStartFn)
2452
0
    return LifetimeStartFn;
2453
0
  LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2454
0
    llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2455
0
  return LifetimeStartFn;
2456
0
}
2457
2458
/// Lazily declare the @llvm.lifetime.end intrinsic.
2459
0
llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2460
0
  if (LifetimeEndFn)
2461
0
    return LifetimeEndFn;
2462
0
  LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2463
0
    llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2464
0
  return LifetimeEndFn;
2465
0
}
2466
2467
namespace {
2468
  /// A cleanup to perform a release of an object at the end of a
2469
  /// function.  This is used to balance out the incoming +1 of a
2470
  /// ns_consumed argument when we can't reasonably do that just by
2471
  /// not doing the initial retain for a __block argument.
2472
  struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2473
    ConsumeARCParameter(llvm::Value *param,
2474
                        ARCPreciseLifetime_t precise)
2475
0
      : Param(param), Precise(precise) {}
2476
2477
    llvm::Value *Param;
2478
    ARCPreciseLifetime_t Precise;
2479
2480
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2481
0
      CGF.EmitARCRelease(Param, Precise);
2482
0
    }
2483
  };
2484
} // end anonymous namespace
2485
2486
/// Emit an alloca (or GlobalValue depending on target)
2487
/// for the specified parameter and set up LocalDeclMap.
2488
void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2489
0
                                   unsigned ArgNo) {
2490
0
  bool NoDebugInfo = false;
2491
  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2492
0
  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2493
0
         "Invalid argument to EmitParmDecl");
2494
2495
  // Set the name of the parameter's initial value to make IR easier to
2496
  // read. Don't modify the names of globals.
2497
0
  if (!isa<llvm::GlobalValue>(Arg.getAnyValue()))
2498
0
    Arg.getAnyValue()->setName(D.getName());
2499
2500
0
  QualType Ty = D.getType();
2501
2502
  // Use better IR generation for certain implicit parameters.
2503
0
  if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2504
    // The only implicit argument a block has is its literal.
2505
    // This may be passed as an inalloca'ed value on Windows x86.
2506
0
    if (BlockInfo) {
2507
0
      llvm::Value *V = Arg.isIndirect()
2508
0
                           ? Builder.CreateLoad(Arg.getIndirectAddress())
2509
0
                           : Arg.getDirectValue();
2510
0
      setBlockContextParameter(IPD, ArgNo, V);
2511
0
      return;
2512
0
    }
2513
    // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2514
    // debug info of TLS variables.
2515
0
    NoDebugInfo =
2516
0
        (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
2517
0
  }
2518
2519
0
  Address DeclPtr = Address::invalid();
2520
0
  Address AllocaPtr = Address::invalid();
2521
0
  bool DoStore = false;
2522
0
  bool IsScalar = hasScalarEvaluationKind(Ty);
2523
0
  bool UseIndirectDebugAddress = false;
2524
2525
  // If we already have a pointer to the argument, reuse the input pointer.
2526
0
  if (Arg.isIndirect()) {
2527
0
    DeclPtr = Arg.getIndirectAddress();
2528
0
    DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));
2529
    // Indirect argument is in alloca address space, which may be different
2530
    // from the default address space.
2531
0
    auto AllocaAS = CGM.getASTAllocaAddressSpace();
2532
0
    auto *V = DeclPtr.getPointer();
2533
0
    AllocaPtr = DeclPtr;
2534
2535
    // For truly ABI indirect arguments -- those that are not `byval` -- store
2536
    // the address of the argument on the stack to preserve debug information.
2537
0
    ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2538
0
    if (ArgInfo.isIndirect())
2539
0
      UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2540
0
    if (UseIndirectDebugAddress) {
2541
0
      auto PtrTy = getContext().getPointerType(Ty);
2542
0
      AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
2543
0
                                D.getName() + ".indirect_addr");
2544
0
      EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
2545
0
    }
2546
2547
0
    auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2548
0
    auto DestLangAS =
2549
0
        getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2550
0
    if (SrcLangAS != DestLangAS) {
2551
0
      assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2552
0
             CGM.getDataLayout().getAllocaAddrSpace());
2553
0
      auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2554
0
      auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);
2555
0
      DeclPtr =
2556
0
          DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
2557
0
                                  *this, V, SrcLangAS, DestLangAS, T, true),
2558
0
                              DeclPtr.isKnownNonNull());
2559
0
    }
2560
2561
    // Push a destructor cleanup for this parameter if the ABI requires it.
2562
    // Don't push a cleanup in a thunk for a method that will also emit a
2563
    // cleanup.
2564
0
    if (Ty->isRecordType() && !CurFuncIsThunk &&
2565
0
        Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2566
0
      if (QualType::DestructionKind DtorKind =
2567
0
              D.needsDestruction(getContext())) {
2568
0
        assert((DtorKind == QualType::DK_cxx_destructor ||
2569
0
                DtorKind == QualType::DK_nontrivial_c_struct) &&
2570
0
               "unexpected destructor type");
2571
0
        pushDestroy(DtorKind, DeclPtr, Ty);
2572
0
        CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2573
0
            EHStack.stable_begin();
2574
0
      }
2575
0
    }
2576
0
  } else {
2577
    // Check if the parameter address is controlled by OpenMP runtime.
2578
0
    Address OpenMPLocalAddr =
2579
0
        getLangOpts().OpenMP
2580
0
            ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2581
0
            : Address::invalid();
2582
0
    if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2583
0
      DeclPtr = OpenMPLocalAddr;
2584
0
      AllocaPtr = DeclPtr;
2585
0
    } else {
2586
      // Otherwise, create a temporary to hold the value.
2587
0
      DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2588
0
                              D.getName() + ".addr", &AllocaPtr);
2589
0
    }
2590
0
    DoStore = true;
2591
0
  }
2592
2593
0
  llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2594
2595
0
  LValue lv = MakeAddrLValue(DeclPtr, Ty);
2596
0
  if (IsScalar) {
2597
0
    Qualifiers qs = Ty.getQualifiers();
2598
0
    if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2599
      // We honor __attribute__((ns_consumed)) for types with lifetime.
2600
      // For __strong, it's handled by just skipping the initial retain;
2601
      // otherwise we have to balance out the initial +1 with an extra
2602
      // cleanup to do the release at the end of the function.
2603
0
      bool isConsumed = D.hasAttr<NSConsumedAttr>();
2604
2605
      // If a parameter is pseudo-strong then we can omit the implicit retain.
2606
0
      if (D.isARCPseudoStrong()) {
2607
0
        assert(lt == Qualifiers::OCL_Strong &&
2608
0
               "pseudo-strong variable isn't strong?");
2609
0
        assert(qs.hasConst() && "pseudo-strong variable should be const!");
2610
0
        lt = Qualifiers::OCL_ExplicitNone;
2611
0
      }
2612
2613
      // Load objects passed indirectly.
2614
0
      if (Arg.isIndirect() && !ArgVal)
2615
0
        ArgVal = Builder.CreateLoad(DeclPtr);
2616
2617
0
      if (lt == Qualifiers::OCL_Strong) {
2618
0
        if (!isConsumed) {
2619
0
          if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2620
            // use objc_storeStrong(&dest, value) for retaining the
2621
            // object. But first, store a null into 'dest' because
2622
            // objc_storeStrong attempts to release its old value.
2623
0
            llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2624
0
            EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2625
0
            EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2626
0
            DoStore = false;
2627
0
          }
2628
0
          else
2629
          // Don't use objc_retainBlock for block pointers, because we
2630
          // don't want to Block_copy something just because we got it
2631
          // as a parameter.
2632
0
            ArgVal = EmitARCRetainNonBlock(ArgVal);
2633
0
        }
2634
0
      } else {
2635
        // Push the cleanup for a consumed parameter.
2636
0
        if (isConsumed) {
2637
0
          ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2638
0
                                ? ARCPreciseLifetime : ARCImpreciseLifetime);
2639
0
          EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2640
0
                                                   precise);
2641
0
        }
2642
2643
0
        if (lt == Qualifiers::OCL_Weak) {
2644
0
          EmitARCInitWeak(DeclPtr, ArgVal);
2645
0
          DoStore = false; // The weak init is a store, no need to do two.
2646
0
        }
2647
0
      }
2648
2649
      // Enter the cleanup scope.
2650
0
      EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2651
0
    }
2652
0
  }
2653
2654
  // Store the initial value into the alloca.
2655
0
  if (DoStore)
2656
0
    EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2657
2658
0
  setAddrOfLocalVar(&D, DeclPtr);
2659
2660
  // Emit debug info for param declarations in non-thunk functions.
2661
0
  if (CGDebugInfo *DI = getDebugInfo()) {
2662
0
    if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
2663
0
        !NoDebugInfo) {
2664
0
      llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2665
0
          &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
2666
0
      if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2667
0
        DI->getParamDbgMappings().insert({Var, DILocalVar});
2668
0
    }
2669
0
  }
2670
2671
0
  if (D.hasAttr<AnnotateAttr>())
2672
0
    EmitVarAnnotations(&D, DeclPtr.getPointer());
2673
2674
  // We can only check return value nullability if all arguments to the
2675
  // function satisfy their nullability preconditions. This makes it necessary
2676
  // to emit null checks for args in the function body itself.
2677
0
  if (requiresReturnValueNullabilityCheck()) {
2678
0
    auto Nullability = Ty->getNullability();
2679
0
    if (Nullability && *Nullability == NullabilityKind::NonNull) {
2680
0
      SanitizerScope SanScope(this);
2681
0
      RetValNullabilityPrecondition =
2682
0
          Builder.CreateAnd(RetValNullabilityPrecondition,
2683
0
                            Builder.CreateIsNotNull(Arg.getAnyValue()));
2684
0
    }
2685
0
  }
2686
0
}
2687
2688
void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2689
0
                                            CodeGenFunction *CGF) {
2690
0
  if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2691
0
    return;
2692
0
  getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2693
0
}
2694
2695
void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2696
0
                                         CodeGenFunction *CGF) {
2697
0
  if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2698
0
      (!LangOpts.EmitAllDecls && !D->isUsed()))
2699
0
    return;
2700
0
  getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2701
0
}
2702
2703
0
void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2704
0
  getOpenMPRuntime().processRequiresDirective(D);
2705
0
}
2706
2707
0
void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2708
0
  for (const Expr *E : D->varlists()) {
2709
0
    const auto *DE = cast<DeclRefExpr>(E);
2710
0
    const auto *VD = cast<VarDecl>(DE->getDecl());
2711
2712
    // Skip all but globals.
2713
0
    if (!VD->hasGlobalStorage())
2714
0
      continue;
2715
2716
    // Check if the global has been materialized yet or not. If not, we are done
2717
    // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2718
    // we already emitted the global we might have done so before the
2719
    // OMPAllocateDeclAttr was attached, leading to the wrong address space
2720
    // (potentially). While not pretty, common practise is to remove the old IR
2721
    // global and generate a new one, so we do that here too. Uses are replaced
2722
    // properly.
2723
0
    StringRef MangledName = getMangledName(VD);
2724
0
    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2725
0
    if (!Entry)
2726
0
      continue;
2727
2728
    // We can also keep the existing global if the address space is what we
2729
    // expect it to be, if not, it is replaced.
2730
0
    QualType ASTTy = VD->getType();
2731
0
    clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
2732
0
    auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2733
0
    if (Entry->getType()->getAddressSpace() == TargetAS)
2734
0
      continue;
2735
2736
    // Make a new global with the correct type / address space.
2737
0
    llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2738
0
    llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2739
2740
    // Replace all uses of the old global with a cast. Since we mutate the type
2741
    // in place we neeed an intermediate that takes the spot of the old entry
2742
    // until we can create the cast.
2743
0
    llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2744
0
        getModule(), Entry->getValueType(), false,
2745
0
        llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2746
0
        llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2747
0
    Entry->replaceAllUsesWith(DummyGV);
2748
2749
0
    Entry->mutateType(PTy);
2750
0
    llvm::Constant *NewPtrForOldDecl =
2751
0
        llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2752
0
            Entry, DummyGV->getType());
2753
2754
    // Now we have a casted version of the changed global, the dummy can be
2755
    // replaced and deleted.
2756
0
    DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2757
0
    DummyGV->eraseFromParent();
2758
0
  }
2759
0
}
2760
2761
std::optional<CharUnits>
2762
0
CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
2763
0
  if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2764
0
    if (Expr *Alignment = AA->getAlignment()) {
2765
0
      unsigned UserAlign =
2766
0
          Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
2767
0
      CharUnits NaturalAlign =
2768
0
          getNaturalTypeAlignment(VD->getType().getNonReferenceType());
2769
2770
      // OpenMP5.1 pg 185 lines 7-10
2771
      //   Each item in the align modifier list must be aligned to the maximum
2772
      //   of the specified alignment and the type's natural alignment.
2773
0
      return CharUnits::fromQuantity(
2774
0
          std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
2775
0
    }
2776
0
  }
2777
0
  return std::nullopt;
2778
0
}